Tool params typed Sequence/Set/Tuple/BaseModel are advertised as "string" and never coerced, Task.depends_on does not order or validate execution, and import still installs the root log handler

Aperta
#6,294 0 commenti 0 reazioni 0 assegnatari Vedi su GitHub

I maintainer di solito rispondono entro 1 giorno

Nessuno ha ancora preso questa issue.

  • #6295 di @praisonai-triage-agent — chiusa senza merge

Valutazione

Difficoltà
5/5
Tempo stimato
Più di una settimana
Idoneità per principianti
20/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Ferma
Stack tecnologico
python
Ambito
backend

Direzione di ricerca

Start with tools/schema.py::annotation_to_json_schema and agent/tool_execution.py::_cast_arguments for the tool parameter cases; compare the schema converters in mcp/mcp_utils.py and runtime/context_builder.py. Then trace Task.depends_on through task/task.py and AgentTeam in agents/agents.py, and inspect _logging.py and __init__.py for import side effects. The acceptance criteria specify the expected schemas, execution order and logging behavior; an open linked pull request already covers work on this issue.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

bug claude enhancement origin/outsider

All findings are in src/praisonai-agents/praisonaiagents. Reproduced on main (v4.7.24) with no LLM, using small scripts. I checked open and closed issues first. #6279 covers malformed tool-call arguments and cached schemas. #6134 is the earlier import-side-effects fix, and finding 3 is the part of it that is still open.

1. Container and model-typed tool parameters get a "string" schema, and the runtime does not cast them

tools/schema.py::annotation_to_json_schema handles list, dict, Union, Literal and Enum. Everything else falls through to type_map.get(annotation, "string"). Measured on this checkout:

from typing import Sequence, Set, Tuple, Mapping, Iterable, FrozenSet, Optional, List, TypedDict
from dataclasses import dataclass
from pydantic import BaseModel
from praisonaiagents.tools.schema import annotation_to_json_schema as s

class Addr(BaseModel): city: str
@dataclass
class P: x: int
class TD(TypedDict): a: int

for t in (Sequence[str], Set[str], Tuple[int, int], Mapping[str, int], Iterable[int],
          FrozenSet[int], tuple, set, Addr, List[Addr], P, TD):
    print(t, s(t))
# every one of these prints {"type": "string"}  (List[Addr] -> array of string items)

So the model is told to send a plain string for Sequence[str], Tuple[float, float], a Pydantic model, a dataclass and so on. Nothing converts it back. Agent._cast_arguments (agent/tool_execution.py:879) only handles the exact annotations int, float and bool:

def send(recipients: Sequence[str], tags: Set[str], point: Tuple[float, float]) -> str: ...
agent.execute_tool("send", {"recipients": "[email protected],[email protected]", "tags": "a,b", "point": "1.0,2.0"})
# tool receives: recipients=<str>, tags=<str>, point=<str>
# list(recipients)[:5] -> ['a', 'l', 'i', 'c', 'e']   # silently iterates characters

The cast has the same gap for wrapped scalars (param.annotation == int is a direct equality check):

def f(n: Optional[int] = None): ...
agent.execute_tool("f", {"n": "5"})   # -> '5' (str); plain `n: int` gives 5
def g(xs: List[int]): ...
agent.execute_tool("g", {"xs": "[1,2]"})   # stays the str '[1,2]'

Three schema generators have drifted from each other. mcp/mcp_utils.py::python_type_to_json_schema handles tuple and set but not Sequence or BaseModel. runtime/context_builder.py::_python_type_to_json_type is a third copy. In build_tool_definition (tools/schema.py:~365), a failed schema build is swallowed by except Exception and logged only at debug level, then replaced with {"type": "string"}.

Suggested fix: make annotation_to_json_schema the single converter, extend it, and drive the cast from the same annotation.

# tools/schema.py
import collections.abc as cabc, dataclasses

_SEQ = (list, tuple, set, frozenset, cabc.Sequence, cabc.MutableSequence,
        cabc.Set, cabc.MutableSet, cabc.Iterable, cabc.Collection)

def annotation_to_json_schema(annotation):
    ...
    if origin in _SEQ or annotation in _SEQ:
        item = annotation_to_json_schema(args[0]) if args else {}
        schema = {"type": "array", "items": item}
        if origin in (set, frozenset, cabc.Set, cabc.MutableSet):
            schema["uniqueItems"] = True
        return schema
    if origin in (dict, cabc.Mapping, cabc.MutableMapping): ...
    if isinstance(annotation, type):
        if hasattr(annotation, "model_json_schema"):          # pydantic v2
            return annotation.model_json_schema()
        if dataclasses.is_dataclass(annotation) or hasattr(annotation, "__required_keys__"):
            return _object_schema_from_hints(annotation)      # dataclass / TypedDict via get_type_hints
# agent/tool_execution.py  (_cast_arguments): reuse one coercer instead of ==int/float/bool checks
def _coerce(value, annotation):
    origin, args = get_origin(annotation), get_args(annotation)
    if origin is Union:                                   # Optional[int] etc.
        for a in args:
            if a is type(None): continue
            try: return _coerce(value, a)
            except (TypeError, ValueError): pass
        return value
    if annotation in (int, float, bool) or origin is None and annotation in (int, float, bool): ...
    if origin in _SEQ and isinstance(value, str):
        value = json.loads(value)                         # "[1,2]" -> [1, 2]
    if origin in (set, frozenset): return origin(value)
    if origin is tuple: return tuple(value)
    if hasattr(annotation, "model_validate"): return annotation.model_validate(value)

Acceptance: Sequence[str], Set[str], Tuple[int, int], Mapping, BaseModel, dataclass and TypedDict parameters produce array or object schemas, and a JSON array or object from the model reaches the tool as the annotated type. Note the full-signature Optional[int] and List[int] cases above.

2. Task.depends_on is an alias for context: it neither orders execution nor is validated

task/task.py:435 documents depends_on as "Alias for context". AgentTeam runs tasks in list order for sequential and workflow. The only dependency-aware code is _depends_on_pending (agents/agents.py:1910, used at :2009), which only flushes a parallel async batch. Measured with a stubbed Agent.chat:

t1 = Task(name="t1", description="d1", agent=a, expected_output="o")
t2 = Task(name="t2", description="d2", agent=a, expected_output="o", depends_on=[t1])
AgentTeam(agents=[a], tasks=[t2, t1], process="sequential").start()   # order run: t2, t1
AgentTeam(agents=[a], tasks=[t2, t1], process="workflow").start()     # order run: t2, t1

t2 runs first and builds its prompt from an empty t1 result, with no error or warning. Two related cases are also accepted without any error:

t1.depends_on = [t2]        # cycle: t1 <-> t2
AgentTeam(agents=[a], tasks=[t1, t2], process="workflow").start()     # runs both, status "completed"

t4 = Task(..., depends_on=[t3])                                       # t3 is not in the team
AgentTeam(agents=[a], tasks=[t4], process="sequential").start()       # runs t4; t3 never runs

The name depends_on promises ordering, and most users will read it that way. A mistyped graph produces plausible but wrong output instead of a failure.

Suggested fix: validate once in AgentTeam.__init__, and for non-parallel processes order tasks topologically only when depends_on / context edges exist, so existing linear flows are unchanged.

# agents/agents.py
def _validate_and_order_tasks(self, tasks):
    ids = {id(t): t for t in tasks}
    deps = {id(t): [d for d in (t.context or []) if isinstance(d, Task)] for t in tasks}
    for t in tasks:
        for d in deps[id(t)]:
            if id(d) not in ids:
                raise ValueError(f"Task '{t.name}' depends on '{d.name}', which is not part of this AgentTeam")
    # Kahn's algorithm, stable w.r.t. the user's original order
    order, seen, visiting = [], set(), set()
    def visit(t):
        if id(t) in seen: return
        if id(t) in visiting:
            raise ValueError(f"Circular task dependency involving '{t.name}'")
        visiting.add(id(t))
        for d in deps[id(t)]: visit(d)
        visiting.discard(id(t)); seen.add(id(t)); order.append(t)
    for t in tasks: visit(t)
    return order      # unchanged when no edges point "forward"

Acceptance: the cycle and dangling cases raise ValueError at construction. tasks=[t2, t1] with t2.depends_on=[t1] runs t1 first. A list with no forward references runs in exactly the same order as today.

3. import praisonaiagents still installs a root log handler, so a host's later logging.basicConfig() becomes a no-op (follow-up to #6134)

The #6134 fix added _host_configured_logging() (_logging.py:62). That only protects hosts that configure logging before they import the SDK. The usual order is the reverse: imports at the top of the file, then basicConfig in main(). __init__.py:57 still calls _logging.configure_root_logger(), which runs logging.basicConfig(...) (_logging.py:161) on import. The host's own call then does nothing:

import logging, praisonaiagents                      # SDK adds a stderr StreamHandler at WARNING
logging.basicConfig(filename="app.log", level=logging.DEBUG)
logging.getLogger("myapp").debug("hello")
# app.log is never created; root level stays 30 (WARNING)

Measured effects of a bare import praisonaiagents on current main:

  • logging.getLogger().handlers goes from [] to [<StreamHandler stderr>], and the root level goes to 30.
  • The httpx, litellm, LiteLLM and pydantic loggers are set to level 50 (CRITICAL). A host that uses httpx or pydantic directly loses their errors.
  • The global warning filters include ignore, UserWarning, module=pydantic.*, which hides pydantic UserWarnings from the host's own code.
  • Import time is not the problem: import Agent takes about 0.07s and Agent() about 16ms, with no heavy modules loaded. Only the global-state mutation is.

Suggested fix: a library should attach a NullHandler to its own logger at import and leave the root alone. The stderr handler and LOGLEVEL handling move to the places where the SDK owns the output.

# __init__.py
logging.getLogger("praisonaiagents").addHandler(logging.NullHandler())   # replaces configure_root_logger()

# _logging.py
def configure_logging(*, force: bool = False) -> None:
    """Explicit opt-in; the praisonai CLI entrypoint and `Agent(output="verbose")` call this."""
    if _host_configured_logging() and not force:
        return
    logging.basicConfig(...)

def _configure_noisy_loggers():
    for name in _NOISY:                       # applied lazily with configure_litellm(), not at import
        logging.getLogger(name).setLevel(logging.WARNING)   # raise the level; do not use CRITICAL, do not clear handlers

Acceptance: a subprocess test shows import praisonaiagents leaves logging.getLogger().handlers and the level unchanged and the httpx / litellm / pydantic logger levels untouched, and that a later logging.basicConfig(filename=...) takes effect. The praisonai CLI still shows warnings on stderr by default.

All three are core-SDK changes that add no new public API. They reuse annotation_to_json_schema, Task.context and the existing logger names.

Lingua principale
Python
Stelle
9.3k
Fork
1.5k
Merge medio
1g 5h
PR unite (30g)
520

Preparare l'ambiente

Questo progetto non fornisce container di sviluppo, Dockerfile né guida per i contributori, quindi l'ambiente è a tuo carico: parti dal suo README e consulta la nostra guida al primo contributo per i passaggi generali.

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di MervinPraison/PraisonAI

Tutte le issue di MervinPraison/PraisonAI

Issue simili

Altre issue su Python

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.