PraisonAI icon indicating copy to clipboard operation
PraisonAI copied to clipboard

Core SDK: guardrail retries re-run side-effecting tools, custom base_url endpoints break the LiteLLM and hierarchical-manager paths, and Enum/date tool arguments are never converted

Open MervinPraison opened this issue 3 days ago • 1 comments

Summary

This audit covers the core SDK (src/praisonai-agents/praisonaiagents) at 7f0f2b6. It found three gaps that ordinary single-agent and team usage hits, and the Python, YAML and CLI surfaces all reach them through the same code paths. Each gap was reproduced against a local OpenAI-compatible stub server on 127.0.0.1 with no real network. Where noted, the proposed fix was checked against a patched scratch copy.

# Gap Paths affected User-visible effect
1 A guardrail retry drops the tool calls and results that produced the rejected answer chat() + achat() Side-effecting tools run again on every retry (a card was charged twice in the repro)
2 Custom base_url endpoints are not honoured across the LLM layer LiteLLM LLM class; hierarchical manager Requests go to /v1/responses and fail on vLLM, LM Studio and gateways; the hierarchical manager calls the wrong host or crashes
3 Tool argument conversion ignores Enum, date/datetime, UUID, Decimal and Path sync + async, OpenAI + LiteLLM Tools with these idiomatic type hints fail on every call

All three are fixes inside existing code paths. None of them needs a new parameter, module or export.


1. A guardrail retry loses tool context, so tools are called again on each retry

Where

praisonaiagents/agent/agent.py:

  • sync _apply_guardrail_with_retry: lines 6257, 6282 and 6310-6323
  • async _aapply_guardrail_with_retry: lines 6331, 6341 and about 6385-6399
# agent.py:6282
conversation = list(messages) if messages else None      # pre-call messages only, with no tool turns
...
# agent.py:6311-6323
feedback = self._guardrail_retry_feedback(error)
if conversation is not None:
    retry_messages = self._extend_guardrail_conversation(
        conversation, current_response, feedback          # [user, assistant(rejected), user(feedback)]
    )
...
with _capture_tool_turns(enabled=tool_turns is not None) as captured:
    response = self._chat_completion(list(retry_messages), temperature, tools, ...)
if tool_turns is not None:
    tool_turns[:] = _tool_turns_for_response(captured, response)   # overwrites the original tool turns
  • The callers (for example agent/chat_mixin.py around 4676 and 4719) pass the pre-call messages and a separate tool_turns list.
  • The retry conversation is built from messages only, so the model never sees the assistant(tool_calls) turn or the tool result that its rejected answer was built from.
  • tool_turns[:] = replaces the original turns. If the retry makes no tool call, the tool evidence for the final answer is also dropped from the history that gets committed.

Repro (validated: sync and async give the same result)

# stub: turn 1 -> tool_call charge_card(42); after the tool result -> "Order 42 total is $19!!!"
# after guardrail feedback: if a tool result is visible, answer from it; otherwise call the tool again
from praisonaiagents import Agent

CHARGES = []
def charge_card(order: int) -> str:
    """Charge the customer's card for an order (side effect!)."""
    CHARGES.append(order)
    return f"charged order {order}: $19"

def no_shouting(out):
    return (True, out) if "!!!" not in out.raw else (False, "remove the exclamation marks")

a = Agent(name="a", instructions="x", model="gpt-4o-mini", output="silent",
          tools=[charge_card], guardrails=no_shouting)
print(a.chat("charge order 42"), "charged:", len(CHARGES))

Output on current main:

[sync]  result='Order 42 total is $19'  card charged 2x  LLM calls=4
   guardrail-retry request messages: [('user','charge order 42'), ('assistant','Order 42 total is $19!!!'), ('user','Previous response failed validation due to: r')]
[async] result='Order 42 total is $19'  card charged 2x  LLM calls=4

Why it matters

  • Guardrails most often reject the form of an answer (format, tone, PII redaction, length), not the facts behind it.
  • Because the evidence is removed, the model either makes the answer up or calls the tools again. Side-effecting tools (payments, emails, writes) can then run up to max_guardrail_retries + 1 times.
  • Guardrails are the SDK's main safety control. As things stand, adding one to an agent that uses tools makes it less safe.

Proposed fix (validated: 1 charge and 3 LLM calls on both paths)

Use the same change in the sync and async methods. Keep the tool turns in the retry conversation, and add new turns instead of overwriting the old ones:

conversation = list(messages) if messages else None
seen_turns = 0
...
if conversation is not None:
    # keep the tool calls and results that produced the rejected answer
    conversation.extend(self._normalize_tool_turn(t) for t in (tool_turns or ())[seen_turns:])
    seen_turns = len(tool_turns or ())
    retry_messages = self._extend_guardrail_conversation(conversation, current_response, feedback)
...
if tool_turns is not None:
    tool_turns.extend(_tool_turns_for_response(captured, response))   # was: tool_turns[:] = ...

Patched request on retry: [user, assistant(tool_calls), tool("charged order 42: $19"), assistant(rejected), user(feedback)], which gives card charged 1x.


2. Custom base_url endpoints are not honoured across the LLM layer

The default OpenAI client treats a custom endpoint correctly. The LiteLLM LLM class and the hierarchical manager do not, so the same Agent(base_url=...) setup works on one path and fails on another.

2a. LLM._supports_responses_api() ignores base_url

praisonaiagents/llm/llm.py:7667-7709 decides from the model name only:

def _supports_responses_api(self) -> bool:
    ...
    for prefix in _openai_prefixes:          # gpt-4o, gpt-4.1, o1, o3, o4, ...
        if model_lower.startswith(prefix):
            return True
    if model_lower.startswith("openai/"):
        ...
                return True

It is used at llm.py:3629 (sync), :5160 (stream) and :6080 (async). The default client already guards this case. llm/openai_client.py:901-912:

def _use_responses_api(self, model: str) -> bool:
    if self.base_url:
        return False          # "No custom base_url is set (not a local server)"

Repro (validated). The gateway returns 404 on /v1/responses and serves /v1/chat/completions. The agent is Agent(name="a", instructions="x", llm=model, base_url=url, output="silent").

llm='gpt-4o-mini'    stream=False -> RAISED LLMResponseError: ... litellm.NotFoundError ...   paths=['/v1/responses']
llm='gpt-4o-mini'    stream=True  -> 'hello from gateway'   paths=['/v1/responses', '/v1/chat/completions']
llm='openai/gpt-4o'  stream=False -> RAISED LLMResponseError: ... litellm.NotFoundError ...   paths=['/v1/responses']
llm='openai/gpt-4o'  stream=True  -> 'hello from gateway'   paths=['/v1/responses', '/v1/chat/completions']

Non-streaming is the default for tasks, teams and workflows, and on that path it fails hard. These are common setups: LiteLLM proxy, vLLM, LM Studio, corporate gateways and Azure-style front doors that use OpenAI model names.

2b. The hierarchical manager LLM drops endpoint settings and crashes on a dict config

praisonaiagents/process/process.py:114-117:

def _create_llm_instance(self):
    from ..llm import LLM
    return LLM(model=self.manager_llm, temperature=0.7)
  • agents/agents.py:1241 makes manager_llm a bare string by default: manager_llm or os.getenv('OPENAI_MODEL_NAME', 'gpt-4o-mini').
  • The manager Agent built in hierarchical() accepts the dict form {"model":..., "base_url":...}. _create_llm_instance then passes that dict as model=.

Repro (validated). Endpoint A is the user's server, set on every worker Agent and in manager_llm. Endpoint B stands in for the global default and returns 401.

manager_llm="my-local-model"
  -> AuthenticationError ... Incorrect API key provided
  agent endpoint A requests: 0      default endpoint B requests: 5
  t1 status: not started
manager_llm={"model": "my-local-model", "base_url": urlA}
  -> AttributeError: 'dict' object has no attribute 'lower'
  t1 status: not started

process="hierarchical" therefore does not work at all against a self-hosted or gateway endpoint, and the manager prompt is sent to the wrong host.

Proposed fix (one rule, two call sites; both validated)

# llm/llm.py  _supports_responses_api: same rule as OpenAIClient._use_responses_api
base = getattr(self, "base_url", None) or getattr(self, "api_base", None)
if base and "api.openai.com" not in str(base):
    return False
# process/process.py  _create_llm_instance: accept the same shapes Agent(llm=...) accepts
def _create_llm_instance(self):
    from ..llm import LLM
    cfg = self.manager_llm
    if isinstance(cfg, LLM):
        return cfg
    if isinstance(cfg, dict):
        return LLM(**{"temperature": 0.7, **cfg})
    return LLM(model=cfg, temperature=0.7)

With both patches, all four llm= and stream combinations go only to /v1/chat/completions. The hierarchical run completes against endpoint A, with 0 requests to B.

Follow-up worth considering: the "should this call use the Responses API" rule lives in two places (LLM._supports_responses_api and OpenAIClient._use_responses_api). One shared helper would stop the two from drifting apart again.


3. Tool argument conversion skips Enum, date/datetime, UUID, Decimal and Path, so those tools fail on every call

Related to #6294, which covers containers and BaseModel (BaseModel now converts correctly). This gap is about scalar classes.

Where

praisonaiagents/agent/tool_execution.py:122-197 (_coerce_value, called through _cast_arguments at about line 1043). The async path uses the same caster from agent/execution_mixin.py (about line 2066).

# tool_execution.py:162-191
container = origin or annotation
if not isinstance(container, type):
    return value
is_model = hasattr(container, "model_validate")
...                                   # only JSON containers, pydantic models and dataclasses are handled
# Keep parsed JSON only if it matches the container (e.g. bare ``list``).
return value if isinstance(value, container) else original     # Enum/date/UUID -> raw str

The schema generator tells the model {"type":"string","enum":["red","blue"]} for an Enum, and "type":"string" for date, UUID, Decimal and Path. The model sends exactly that, but the function receives a plain str.

Repro (validated on all four paths: OpenAI client and LiteLLM, each with chat() and achat())

import enum, datetime
from praisonaiagents import Agent

class Color(enum.Enum):
    RED = "red"; BLUE = "blue"

def paint(color: Color) -> str:
    """Paint the wall."""
    return f"painted {color.name}"

def when(day: datetime.date) -> str:
    """Weekday for a date."""
    return day.strftime("%A")

Agent(name="a", instructions="x", tools=[paint, when]).chat("paint it blue; what day is 2024-05-01?")
# stub sends {"color": "blue"} and {"day": "2024-05-01"}

Output on current main:

FINAL: ["{\"error\": \"'str' object has no attribute 'name'\"}",
        "{\"error\": \"'str' object has no attribute 'strftime'\"}", ...]

Calling the caster directly:

Color 'blue' -> str 'blue'
date '2024-05-01' -> str '2024-05-01'
datetime '2024-05-01T10:00:00' -> str
UUID '1234...' -> str      Path '/tmp/x' -> str      Decimal '1.10' -> str

Why it matters

Enum, date and UUID are standard Python type hints for tool parameters. Today the SDK advertises a schema it then does not honour, so the tool breaks even though the model did exactly what it was asked. This is the opposite of "simple to adopt, hard to misuse".

Proposed fix (validated: ["painted BLUE", "Wednesday", ...] on all four paths)

pydantic is already a hard dependency, so delegate scalar classes to it inside _coerce_value, just before container = origin or annotation:

import enum, datetime, uuid, decimal, pathlib
_SCALAR_TYPES = (enum.Enum, datetime.date, datetime.time, datetime.timedelta,
                 uuid.UUID, decimal.Decimal, pathlib.PurePath)

if isinstance(annotation, type) and issubclass(annotation, _SCALAR_TYPES) \
        and not isinstance(value, annotation):
    from pydantic import TypeAdapter
    return TypeAdapter(annotation).validate_python(value)   # a failure falls through to `except` -> original

Optional[Color] and Union[...] work without further changes, because the union branch already calls _coerce_value on each member.


Validation notes

  • Environment: HEAD 7f0f2b6, Python 3.11, openai 1.x client and litellm. All LLM traffic went to a scripted OpenAI-compatible stub on 127.0.0.1.
  • Each "current main" output above was reproduced twice, once by the original audit and once in an independent re-run.
  • Each proposed fix was checked by patching a scratch copy of the package and re-running the same script. The repo's unit suite was not run against these fixes. Implementation PRs should add regression tests and run pytest tests/unit/ in src/praisonai-agents.
  • All three fixes stay inside existing functions. They add no new public API, parameter or dependency, and they do not touch Agent.__init__ or import time.

🤖 Generated with Claude Code


Generated by Claude Code

MervinPraison avatar Nov 30 '26 08:11 MervinPraison

The audit's gap 1 is the one that generalizes: every framework I have checked handles "tool raised, state unknown" differently, and the side effect lands twice. PraisonAI's fix is in-repo. Do you see value in a shared repro suite for this semantics, or is each framework's contract too different to test one way?

xka0085-byte avatar Dec 01 '26 08:12 xka0085-byte