From a282b6f311cda1c53224c826d7a332d173eaac4e Mon Sep 17 00:00:00 2001 From: Lorenze Jay Date: Thu, 26 Nov 2026 16:53:15 -0800 Subject: [PATCH 1/7] The CrewAI Bot is a CrewAI conversational Agent The CrewAI engine was a one-step Flow that called the model through LiteLLM directly, so no CrewAI Agent ever ran. It now runs CrewAI 1.15.45's conversational Agent session, served by ag-ui-crewai with conversational=True, and keeps OpenBot's contract: - The server's system messages (the Bot's role and tool guidance), which ag-ui-crewai's conversational mode drops, reach the Agent after CrewAI's own system prompt. - OpenBot's tools are handed back to the server: each is a result_as_answer stand-in that ends the turn with the model's own call id, and its phantom backend tool events are suppressed. - Messages keep the ids they arrived with, so the authoritative snapshot doesn't show the thread twice. - An image on the request survives a continuation run. Same harness id, image, port and route; no API change. OpenAI, Anthropic and Google models go through CrewAI's native SDK clients (extras added); LiteLLM stays the fallback. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 + agent-crewai/requirements.txt | 12 +- agent-crewai/src/main.py | 512 +++++++++++++++++++++++++------- agent-crewai/tests/test_main.py | 233 +++++++++------ docs/agent-frameworks.md | 14 + 5 files changed, 577 insertions(+), 200 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 9c48135468..214b4119a8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,12 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. ## Unreleased +- **The CrewAI Bot is a CrewAI Agent.** A Bot on the CrewAI engine now answers through CrewAI's + conversational Agent (`Agent(conversational=True)`, new in CrewAI 1.15.45), served by + ag-ui-crewai's conversational mode. Before, it called the model directly from a one-step CrewAI + Flow. The Bot's role, the whole thread and OpenBot's tools reach it as they did, and its replies + still arrive whole rather than word by word. CrewAI now calls OpenAI, Anthropic and Google models + through their own SDKs, and calls any other model through LiteLLM as before. - **OpenBot Desktop on a Mac asks for your password only after you choose Continue.** When OpenBot installs the software it runs on, a card says your Mac will ask for your password and why, and macOS's prompt comes up only once you choose Continue. Before, the prompt came up by itself a diff --git a/agent-crewai/requirements.txt b/agent-crewai/requirements.txt index f089be47bb..58e75df500 100644 --- a/agent-crewai/requirements.txt +++ b/agent-crewai/requirements.txt @@ -1,4 +1,12 @@ -ag-ui-crewai +# The Bot is a conversational CrewAI Agent (`Agent(conversational=True)`'s Flow session), which +# CrewAI shipped in 1.15.45, and ag-ui-crewai serves it with `conversational=True`, which 1.0.0 has. +# Floors, not pins: CI installs these the way the image does, so a new release upstream is tested +# before it ships. +# +# The extras are CrewAI's own clients for the providers OpenBot offers. CrewAI calls a model it +# knows through the provider's SDK and refuses to start without it, even with LiteLLM installed. +crewai[anthropic,google-genai]>=1.15.45 +ag-ui-crewai>=1.0.0 uvicorn[standard] # litellm 1.106.0 imports `CacheableResult` from `mcp.types`, which exists only in mcp 2.x, while # ag-ui-crewai 1.0.0 requires mcp<2. The two cannot both be satisfied, so every CrewAI run failed @@ -8,4 +16,6 @@ uvicorn[standard] # Held here rather than raising mcp, because mcp>=2 is only reachable by letting the resolver walk # ag-ui-crewai back to 0.3.1 and crewai to 1.6.1. 1.105.1 does not reference the symbol at all and # leaves every other version exactly where it was. Lift this when ag-ui-crewai supports mcp 2. +# +# Still installed: CrewAI calls a model through LiteLLM when no provider SDK of its own knows it. litellm<1.106.0 diff --git a/agent-crewai/src/main.py b/agent-crewai/src/main.py index 943970295b..67ead52f2b 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -1,20 +1,44 @@ -"""CrewAI as a Bot. - -The third harness in the box, and the first built the way every one after it will be: the AG-UI -integration that CrewAI's own ecosystem publishes, mounted on FastAPI, with nothing of the protocol -written here: we do not write adapters. This one imports `ag_ui_crewai` and stops. - -The contract with the rest of OpenBot is the same one the other Bots meet, and it is small: -serve AG-UI on a port, answer `/health`, and refuse anybody who does not carry the server's token. +"""CrewAI as a Bot: a conversational CrewAI Agent, served over AG-UI. + +The Bot is a real `crewai.Agent`, run the way CrewAI runs one in a chat session: a conversational +Flow (`conversational=True`, a `converse` route, `stream_turn`) whose one handler gives the +conversation to the Agent and appends its reply. That is the same bridge CrewAI builds for +`Agent(conversational=True).as_flow()` (see `crewai.agent.conversation`), and `ag_ui_crewai` +serves it with `add_crewai_flow_fastapi_endpoint(..., conversational=True)`, which maps AG-UI's +`threadId` to CrewAI's session and runs the turn through `stream_turn`. Nothing of the protocol is +written here. + +Three things OpenBot needs that CrewAI's own bridge does not do, and that this file adds: + +- THE BOT'S ROLE. The server sends its instructions as system messages, and the conversational + path drops system messages before the Flow sees them. They are kept aside here and given to the + Agent as system messages, right after CrewAI's own system prompt. +- THE WHOLE THREAD, EVERY RUN. A CrewAI session keeps its history in memory; OpenBot's server + sends the whole thread on every run, and a fresh process must answer from it. ag-ui-crewai seeds + the session from the run's messages, and the Agent is built anew for each turn, so nothing + depends on an earlier run having happened in this process. +- THE CALLER'S TOOLS ARE HANDED BACK. A CrewAI Agent runs its tools itself. OpenBot's tools are + run by the server: the Bot asks for one, the run ends, and the next run carries the result. Each + AG-UI tool becomes a CrewAI tool that records the call and ends the turn, and the turn's reply + is then the assistant message that asks for it. + +The contract with the rest of OpenBot is the one every Bot meets: serve AG-UI on a port, answer +`/health`, and refuse anybody who does not carry the server's token. """ +from __future__ import annotations + import hmac +import json import os import sys -from collections.abc import Mapping +import threading +from collections.abc import Iterator +from contextlib import contextmanager from copy import deepcopy from pathlib import Path -from typing import Any +from typing import Any, ClassVar +from uuid import uuid4 # The spec file every language in the box reads: one level above this Bot in the repository, and # one level above /app/src in the image the Dockerfile builds. @@ -25,104 +49,72 @@ import ag_ui_crewai.endpoint as crewai_endpoint from ag_ui.core import Message, Tool from ag_ui_crewai import add_crewai_flow_fastapi_endpoint -from crewai.flow.flow import Flow, listen, start +from crewai import LLM, Agent +from crewai.agent.conversation import AgentConversationState +from crewai.flow import ConversationConfig, Flow, listen +from crewai.flow.conversational import ConversationMessage +from crewai.tools import BaseTool +from crewai.utilities.pydantic_schema_utils import create_model_from_schema from fastapi import FastAPI, Request from fastapi.responses import JSONResponse -from litellm import acompletion +from pydantic import BaseModel, Field, PrivateAttr, field_validator # The one header OpenBot's server sends when it calls a managed Bot. Same name the TypeScript Bots # check, because a Bot is a Bot whatever it is written in. TOKEN_HEADER = "x-openbot-agent-token" +# Where the run's system messages and tools wait for the turn, in the Flow's state. Not names a +# CrewAI or AG-UI key uses, so neither ever reads or overwrites them. +INSTRUCTIONS_KEY = "openbot_instructions" +CALLER_TOOLS_KEY = "openbot_caller_tools" + +# What the Bot is to CrewAI. CrewAI opens its system prompt with "You are {role}. {backstory}" and +# the goal; these say only that the server's instructions, sent right after, are who it is. +ROLE = "the assistant your instructions describe" +BACKSTORY = "Your instructions follow, and they take precedence." +GOAL = "Help the person you are talking to, following your instructions." + def _expected_token() -> str: return (os.environ.get("MANAGED_AGENT_TOKEN") or "").strip() def _model() -> str: - """The provider and model OpenBot chose, in the form litellm wants. + """The provider and model OpenBot chose, in the form CrewAI's `LLM` wants. - `BOT_PROVIDER` and `BOT_MODEL` are set by the shell from the model screen. litellm addresses a - model as `provider/model`, and it reads that provider's key from the environment itself, which - is why nothing here touches a key. + `BOT_PROVIDER` and `BOT_MODEL` are set by the shell from the model screen. CrewAI addresses a + model as `provider/model`, and reads that provider's key and base URL from the environment + itself, which is why nothing here touches a key. - The model half is whatever the endpoint publishes, slashes included. litellm takes the first - path component as the provider and sends the rest as the model name, so a name that already + The model half is whatever the endpoint publishes, slashes included. The first path component + is taken as the provider and the rest is sent as the model name, so a name that already contains a slash still needs the chosen provider in front: `qwen/qwen3-8b` on an OpenAI-compatible endpoint is `openai/qwen/qwen3-8b`, and `openai/gpt-5.6-terra` is `openai/openai/gpt-5.6-terra`. Treating a slash as "already a provider" dropped the prefix, - and litellm then either routed to a provider nobody configured (`LLM Provider NOT provided`) - or sent only the second half to the endpoint. + and the call then either went to a provider nobody configured or sent only the second half to + the endpoint. """ settings = bot_settings("agent-crewai") - provider = settings.provider - model = settings.model - return f"{provider}/{model}" - - -_PROVIDER_MESSAGE_FIELDS = { - "developer": {"role", "content", "name"}, - "system": {"role", "content", "name"}, - "user": {"role", "content", "name"}, - "assistant": { - "role", - "audio", - "content", - "function_call", - "name", - "refusal", - "tool_calls", - }, - "tool": {"role", "content", "tool_call_id"}, -} + return f"{settings.provider}/{settings.model}" -def _message_dict(message: Any) -> dict[str, Any]: - if isinstance(message, Mapping): - return dict(message) - return message.model_dump() +def _llm() -> LLM: + return LLM(model=_model()) -def _strip_none(message: dict[str, Any]) -> dict[str, Any]: - return {key: value for key, value in message.items() if value is not None} +# --- The run's system messages, kept for the Agent -------------------------------------------- -def _provider_tool_calls(tool_calls: Any) -> Any: - if not isinstance(tool_calls, list): - return deepcopy(tool_calls) - projected = [] - for tool_call in tool_calls: - if not isinstance(tool_call, Mapping): - tool_call = tool_call.model_dump() - projected.append( - _strip_none( - { - key: deepcopy(tool_call[key]) - for key in ("id", "type", "function") - if key in tool_call - } - ) +def _text(content: Any) -> str: + if isinstance(content, str): + return content + if isinstance(content, list): + return "\n".join( + part.get("text", "") + for part in content + if isinstance(part, dict) and part.get("type") == "text" ) - return projected - - -def _provider_messages(messages: list[Any]) -> list[dict[str, Any]]: - """Project AG-UI state messages to provider chat fields without mutating state.""" - provider_messages = [] - for message in messages: - message_dict = _message_dict(message) - allowed_fields = _PROVIDER_MESSAGE_FIELDS.get(message_dict.get("role")) - if allowed_fields is None: - continue - projected = { - key: deepcopy(value) - for key, value in message_dict.items() - if key in allowed_fields - } - if "tool_calls" in projected: - projected["tool_calls"] = _provider_tool_calls(projected["tool_calls"]) - provider_messages.append(_strip_none(projected)) - return provider_messages + return "" _prepare_crewai_inputs = crewai_endpoint.crewai_prepare_inputs @@ -136,6 +128,12 @@ def _openbot_prepare_crewai_inputs( context: list[Any] | None = None, forwarded_props: Any = None, ): + """ag-ui-crewai's inputs, plus every system message of the run and its tools, set aside. + + The conversational path seeds the session with the run's messages less every system message, + and the server's are the Bot's role and the guidance for the tools it holds. They are kept + under a key of their own here, in order, and the turn hands them to the Agent. + """ inputs = _prepare_crewai_inputs( state=state, messages=messages, @@ -143,37 +141,345 @@ def _openbot_prepare_crewai_inputs( context=context, forwarded_props=forwarded_props, ) - if messages and getattr(messages[0], "role", None) == "system": - prepared_messages = inputs.get("messages") - if isinstance(prepared_messages, list): - leading_system = messages[0].model_dump() - if prepared_messages[:1] != [leading_system]: - inputs["messages"] = [leading_system, *prepared_messages] + inputs[INSTRUCTIONS_KEY] = [ + text + for message in messages + if getattr(message, "role", None) in ("system", "developer") + and (text := _text(getattr(message, "content", None)).strip()) + ] + inputs[CALLER_TOOLS_KEY] = [tool.model_dump() for tool in tools] return inputs crewai_endpoint.crewai_prepare_inputs = _openbot_prepare_crewai_inputs -class OpenBotFlow(Flow): - """A crew of one, which is the right size for a Bot answering a person. +# --- The caller's tools, handed back ---------------------------------------------------------- + + +class HandBack: + """Which of the caller's tools the Agent called in one turn, for the server to run. + + One per turn, never shared. The lock is for the Agent calling more than one tool at once, + which CrewAI runs on a pool. + """ + + def __init__(self) -> None: + self._lock = threading.Lock() + self.names: list[str] = [] + + def record(self, name: str) -> None: + with self._lock: + self.names.append(name) + + def calls(self, messages: list[Any], names: dict[str, str]) -> list[dict[str, Any]]: + """The calls to hand back, as the model made them: its own ids and arguments. + + The model's call id, not one made up here, because the next run carries the tool's result + under that id and CrewAI sends it to the model with the call it answers. `names` maps the + name the model was shown to the name the server knows. + """ + if not self.names: + return [] + asked = next( + ( + message.get("tool_calls") + for message in reversed(messages) + if isinstance(message, dict) + and message.get("role") == "assistant" + and message.get("tool_calls") + ), + None, + ) or [] + handed_back = [] + for call in asked: + function = call.get("function") or {} + name = names.get(function.get("name")) + if name is None: + continue + arguments = function.get("arguments") + handed_back.append( + { + "id": call.get("id") or f"call_{uuid4().hex}", + "type": "function", + "function": { + "name": name, + "arguments": arguments + if isinstance(arguments, str) + else json.dumps(arguments or {}), + }, + } + ) + return handed_back + - CrewAI's own examples build multi-agent crews, and a person who wants that edits this. What - ships has to answer the first question somebody asks it without a role, a goal and a backstory - being invented on their behalf. +class CallerTool(BaseTool): + """An AG-UI tool, as a CrewAI tool that is not run here. + + Calling it records the call and ends the turn (`result_as_answer`), so the Agent never sees a + result it would have to invent. The server runs the tool, and the next run carries the result + in the thread like any other tool message. """ - @start() - async def answer(self): - messages = self.state.get("messages", []) - response = await acompletion( - model=_model(), - messages=_provider_messages(messages), - tools=self.state.get("tools") or None, - stream=False, + result_as_answer: bool = True + _hand_back: HandBack = PrivateAttr() + caller_name: str + + def __init__(self, *, hand_back: HandBack, **data: Any) -> None: + # The name the server knows it by, whatever CrewAI makes of `name` for the model. + super().__init__(caller_name=data["name"], **data) + self._hand_back = hand_back + + def _run(self, **arguments: Any) -> str: + self._hand_back.record(self.caller_name) + return "Handed to the caller to run." + + +# CrewAI reports every tool it runs, and ag-ui-crewai turns that report into a tool call with its +# result. For a caller's tool that is a call already "answered" (by the stand-in above), under an id +# the model never made, next to the real one the turn hands back: the server would store a phantom +# call and a result for it, and the provider would be sent an orphaned tool result on the next run. +# So a report of a caller's tool, by the Agent of a turn in progress, is not passed on. Any other +# tool an Agent here is given (one a person adds to this file) is reported as before. +_caller_tools_by_agent: dict[str, frozenset[str]] = {} +_caller_tools_lock = threading.Lock() +_is_backend_tool_event = crewai_endpoint.is_backend_tool_event + + +def _is_caller_tool_event(event: Any) -> bool: + with _caller_tools_lock: + names = _caller_tools_by_agent.get(str(getattr(event, "agent_id", None))) + return bool(names) and getattr(event, "tool_name", None) in names + + +def _reported_backend_tool_event(event: Any) -> bool: + return _is_backend_tool_event(event) and not _is_caller_tool_event(event) + + +crewai_endpoint.is_backend_tool_event = _reported_backend_tool_event + + +@contextmanager +def _handing_back(agent: Agent, tools: list[CallerTool]) -> Iterator[None]: + """While the Agent's turn runs, its reports of these tools stay here.""" + key = str(agent.id) + with _caller_tools_lock: + _caller_tools_by_agent[key] = frozenset( + name for tool in tools for name in (tool.name, tool.caller_name) + ) + try: + yield + finally: + with _caller_tools_lock: + _caller_tools_by_agent.pop(key, None) + + +def _caller_tools(tools: list[dict[str, Any]], hand_back: HandBack) -> list[CallerTool]: + built: list[CallerTool] = [] + for tool in tools: + name = tool.get("name") + if not isinstance(name, str) or not name: + continue + parameters = tool.get("parameters") or {"type": "object", "properties": {}} + built.append( + CallerTool( + hand_back=hand_back, + name=name, + description=tool.get("description") or name, + args_schema=create_model_from_schema( + {"title": f"{name}_arguments", **parameters} + ), + ) + ) + return built + + +# --- The conversation ------------------------------------------------------------------------- + + +# What a provider accepts on each message, and on each tool call. AG-UI messages carry more (ids, +# metadata, encrypted values), CrewAI's session adds its own, and a strict provider refuses a +# request with a field it does not know rather than ignoring it. +_MESSAGE_FIELDS = { + "user": {"role", "content", "name", "files"}, + "assistant": {"role", "content", "name", "tool_calls"}, + "tool": {"role", "content", "name", "tool_call_id"}, +} +_TOOL_CALL_FIELDS = ("id", "type", "function") + + +def _message_dict(message: Any) -> dict[str, Any] | None: + """A session message as CrewAI's `kickoff` takes it, or None for one that is not a turn. + + The session holds `ConversationMessage` models, except the turn's own user message, which + CrewAI appends as a plain dict. System messages are not turns: the run's are handed to the + Agent separately, ahead of the conversation. + """ + if isinstance(message, BaseModel): + message = message.model_dump(exclude_unset=True) + allowed = _MESSAGE_FIELDS.get(message.get("role")) + if allowed is None: + return None + kept = { + key: deepcopy(value) + for key, value in message.items() + if key in allowed and value is not None + } + if isinstance(kept.get("tool_calls"), list): + kept["tool_calls"] = [ + {key: call[key] for key in _TOOL_CALL_FIELDS if key in call} + for call in kept["tool_calls"] + if isinstance(call, dict) + ] + # `content` stays even when empty: CrewAI requires it, and a message that only calls tools + # has none. + kept.setdefault("content", None) + return kept + + +class OpenBotConversationMessage(ConversationMessage): + """CrewAI's session message, with the AG-UI id it arrived under. + + ag-ui-crewai builds every MESSAGES_SNAPSHOT from the session and keeps a message's `id` when it + has one; CrewAI's own message has none, so every earlier message of the thread would come back + under a new id. A snapshot is authoritative (entries it repeats replace the client's copies), + and a whole thread under new ids is a thread shown twice. + """ + + id: str | None = None + + +class OpenBotConversationState(AgentConversationState): + messages: list[OpenBotConversationMessage] = Field(default_factory=list) + openbot_instructions: list[str] = Field(default_factory=list) + openbot_caller_tools: list[dict[str, Any]] = Field(default_factory=list) + + @field_validator("messages", mode="before") + @classmethod + def content_may_be_empty(cls, value: Any) -> Any: + """An assistant message that only calls tools has no content, and AG-UI leaves it out. + + CrewAI's session message requires the field, so the thread's tool calls would refuse the + whole run on the turn after the server ran a tool. + """ + if isinstance(value, list): + return [ + {**message, "content": None} + if isinstance(message, dict) and "content" not in message + else message + for message in value + ] + return value + + +def _with_request_media(conversation: list[dict[str, Any]]) -> list[dict[str, Any]]: + """The newest user message's pictures and files, kept as a message of their own. + + CrewAI makes the newest user message the turn's request and keeps only its text; every other + message goes to the model whole. ag-ui-crewai already splits a run that ends on the person's + message this way. A run that ends on a tool's result (the server ran a tool and the Bot + continues) does not get that split, so it is made here: the media just before the request, as + the person sent it. + """ + for index in range(len(conversation) - 1, -1, -1): + message = conversation[index] + if message.get("role") != "user": + continue + content = message.get("content") + if not isinstance(content, list): + return conversation + text = [part for part in content if isinstance(part, dict) and part.get("type") == "text"] + media = [part for part in content if not (isinstance(part, dict) and part.get("type") == "text")] + if not media: + return conversation + return [ + *conversation[:index], + {**message, "content": media}, + {**message, "content": "\n".join(part.get("text", "") for part in text)}, + *conversation[index + 1 :], + ] + return conversation + + +def _agent(tools: list[CallerTool]) -> Agent: + """The Bot, as a CrewAI Agent, for one turn. + + Its role, goal and backstory defer to the server's instructions, which follow CrewAI's own + system prompt as system messages of their own: they already say who the Bot is, and a role + invented here would only compete with them. + """ + return Agent( + role=ROLE, + goal=GOAL, + backstory=BACKSTORY, + llm=_llm(), + tools=tools, + allow_delegation=False, + verbose=False, + ) + + +class OpenBotAgentFlow(Flow[OpenBotConversationState]): + """The Agent's conversational session, the shape CrewAI gives `Agent(conversational=True)`. + + Every turn takes the `converse` route; there is nothing to route between. The Agent is built + for the turn from the run's own instructions and tools, so two Bots, or two runs of one, never + share one. + """ + + _standalone_agent: ClassVar[bool] = True + conversational: ClassVar[bool] = True + conversational_config: ClassVar[ConversationConfig] = ConversationConfig( + defer_trace_finalization=False + ) + _skip_auto_memory = True + + def route_turn(self, context: dict[str, Any]) -> str: + return "converse" + + @listen("converse") + async def converse_turn(self): + instructions = [ + {"role": "system", "content": text} for text in self.state.openbot_instructions + ] + conversation = [ + message + for message in map(_message_dict, self.state.messages) + if message is not None + ] + if not conversation: + raise ValueError("A turn needs at least one message") + conversation = _with_request_media(conversation) + hand_back = HandBack() + tools = _caller_tools(self.state.openbot_caller_tools, hand_back) + agent = _agent(tools) + with self._conversation_streaming_enabled(agent.llm), _handing_back(agent, tools): + # CrewAI keeps every message before the newest user message as history, with its + # role, after its own system prompt: the server's instructions lead it. + result = await agent.kickoff_async(messages=[*instructions, *conversation]) + calls = hand_back.calls( + result.messages, {tool.name: tool.caller_name for tool in tools} + ) + if calls: + # The turn's reply asks the caller to run its tools, and the run ends there. + self._reply(None, tool_calls=calls) + return None + self._reply(result.raw) + return result + + def _reply(self, content: str | None, **fields: Any) -> None: + """The turn's reply, appended the way `append_assistant_message` does, with an id. + + One id for the run, so every snapshot the run sends after it agrees on which message it is. + """ + object.__setattr__(self, "_assistant_reply_appended", True) + self.state.messages.append( + OpenBotConversationMessage( + id=str(uuid4()), role="assistant", content=content, **fields + ) ) - self.state.setdefault("messages", []).append( - response.choices[0].message.model_dump() + self._emit_conversation_message_added( + role="assistant", content=content, message_index=len(self.state.messages) - 1 ) @@ -204,4 +510,4 @@ async def health(): return {"ok": True, "harness": "crewai"} -add_crewai_flow_fastapi_endpoint(app, OpenBotFlow(), "/") +add_crewai_flow_fastapi_endpoint(app, OpenBotAgentFlow(), "/", conversational=True) diff --git a/agent-crewai/tests/test_main.py b/agent-crewai/tests/test_main.py index a46d33fac6..58c9ffb3aa 100644 --- a/agent-crewai/tests/test_main.py +++ b/agent-crewai/tests/test_main.py @@ -15,7 +15,7 @@ import uvicorn from fastapi import FastAPI, Request from fastapi.testclient import TestClient -from fastapi.responses import JSONResponse +from fastapi.responses import JSONResponse, StreamingResponse sys.path.insert(0, str(Path(__file__).resolve().parents[1])) @@ -77,81 +77,14 @@ def test_model_normalizes_blank_provider_and_model_before_defaults( assert main._model() == expected -def test_crewai_endpoint_preserves_leading_bot_role_for_provider(monkeypatch): - monkeypatch.setenv("MANAGED_AGENT_TOKEN", "test-token") - provider_messages = [] - provider_tools = [] - - async def record_completion(*, model, messages, tools, stream): - provider_messages.append(deepcopy(messages)) - provider_tools.append(deepcopy(tools)) - return FakeCompletion() - - monkeypatch.setattr(main, "acompletion", record_completion) - - client = TestClient(main.app) - response = client.post( - "/", - headers={"x-openbot-agent-token": "test-token"}, - json=run_input( - [ - { - "id": "system-1", - "role": "system", - "content": "You are Ada, a Bot-specific finance analyst.", - }, - { - "id": "user-1", - "role": "user", - "content": "What should I review first?", - }, - ] - ), - ) - - assert response.status_code == 200 - assert provider_messages == [ - [ - { - "role": "system", - "content": "You are Ada, a Bot-specific finance analyst.", - }, - { - "role": "user", - "content": "What should I review first?", - }, - ] - ] - assert provider_tools == [None] - snapshots = [ - event["messages"] - for event in agui_events(response.text) - if event.get("type") == "MESSAGES_SNAPSHOT" - ] - assert snapshots - assert snapshots[-1][:2] == [ - { - "id": "system-1", - "role": "system", - "content": "You are Ada, a Bot-specific finance analyst.", - }, - { - "id": "user-1", - "role": "user", - "content": "What should I review first?", - }, - ] - - -def test_provider_message_projection_keeps_supported_fields_without_mutating_state(): +def test_session_messages_are_projected_to_provider_fields_without_mutating_state(): + """What the Agent is given is what a strict provider accepts; the session keeps the rest.""" original_messages = [ { "id": "system-1", "role": "system", "content": "System instructions", - "name": "system_name", "metadata": {"transport": "ag-ui"}, - "encrypted_value": "system-secret", }, { "id": "user-1", @@ -166,7 +99,6 @@ def test_provider_message_projection_keeps_supported_fields_without_mutating_sta { "id": "assistant-1", "role": "assistant", - "content": None, "name": "assistant_name", "tool_calls": [ { @@ -189,14 +121,10 @@ def test_provider_message_projection_keeps_supported_fields_without_mutating_sta ] state_messages = deepcopy(original_messages) - projected = main._provider_messages(state_messages) + projected = [main._message_dict(message) for message in state_messages] assert projected == [ - { - "role": "system", - "content": "System instructions", - "name": "system_name", - }, + None, { "role": "user", "content": [ @@ -207,6 +135,7 @@ def test_provider_message_projection_keeps_supported_fields_without_mutating_sta }, { "role": "assistant", + "content": None, "name": "assistant_name", "tool_calls": [ { @@ -225,6 +154,26 @@ def test_provider_message_projection_keeps_supported_fields_without_mutating_sta assert state_messages == original_messages +def test_every_system_message_of_the_run_is_kept_for_the_agent(): + """ag-ui-crewai's conversational path drops system messages; the Bot's role is among them.""" + from ag_ui.core import SystemMessage, UserMessage + + inputs = main.crewai_endpoint.crewai_prepare_inputs( + state={}, + messages=[ + SystemMessage(id="standing-role:bot", role="system", content="You are Ada."), + SystemMessage(id="granted-tools:bot", role="system", content="You hold: notes."), + UserMessage(id="u1", role="user", content="Hello"), + ], + tools=[], + context=[], + forwarded_props={}, + ) + + assert inputs[main.INSTRUCTIONS_KEY] == ["You are Ada.", "You hold: notes."] + assert inputs[main.CALLER_TOOLS_KEY] == [] + + def isolated_environment(directory): directory.mkdir(parents=True, exist_ok=True) inherited = ( @@ -286,18 +235,55 @@ def stop_loopback_server(server, thread): assert not thread.is_alive(), "loopback server did not stop" +def as_stream(completion): + """A Chat Completions answer as the SSE stream a streamed request gets.""" + message = completion["choices"][0]["message"] + delta = {key: value for key, value in message.items() if value is not None} + for index, call in enumerate(delta.get("tool_calls") or []): + call["index"] = index + base = { + "id": completion["id"], + "object": "chat.completion.chunk", + "created": completion["created"], + "model": completion["model"], + } + chunks = [ + {**base, "choices": [{"index": 0, "delta": delta, "finish_reason": None}]}, + { + **base, + "choices": [ + {"index": 0, "delta": {}, "finish_reason": completion["choices"][0]["finish_reason"]} + ], + }, + {**base, "choices": [], "usage": completion["usage"]}, + ] + + async def stream(): + for chunk in chunks: + yield f"data: {json.dumps(chunk)}\n\n" + yield "data: [DONE]\n\n" + + return StreamingResponse(stream(), media_type="text/event-stream") + + def loopback_openai_receiver(records, strict_messages=False): app = FastAPI() @app.post("/chat/completions") async def chat_completions(request: Request): body = await request.json() + completion = answer(body, request.headers) + if isinstance(completion, dict) and body.get("stream"): + return as_stream(completion) + return completion + + def answer(body, headers): records.append( { "model": body.get("model"), "messages": body.get("messages"), "tools": body.get("tools"), - "authorization": request.headers.get("authorization"), + "authorization": headers.get("authorization"), } ) if not body.get("model"): @@ -343,7 +329,7 @@ async def chat_completions(request: Request): }, status_code=400, ) - if body.get("tools") == [show_note_provider_tool()] and not any( + if provider_tool_shapes(body.get("tools")) == [show_note_shape()] and not any( message.get("role") == "tool" for message in body.get("messages") or [] ): return { @@ -457,7 +443,7 @@ def agui_events(response_text): return events -def run_litellm_loopback_proof(proof_case, output): +def run_loopback_proof(proof_case, output): sys.addaudithook(prohibit_external_connections) provider, model, expected_provider_model, expected_receiver_model = { "blank-provider": (" ", "gpt-4o", "openai/gpt-4o", "gpt-4o"), @@ -580,12 +566,23 @@ def run_litellm_loopback_proof(proof_case, output): assert not result["runError"], result assert len(records) == (2 if proof_case == "caller-tool" else 1), result assert all(record["model"] == expected_receiver_model for record in records), result - assert records[0]["messages"][0] == { + # CrewAI's own system prompt for the Agent, then the Bot's role as the server sent it. + assert records[0]["messages"][0]["role"] == "system", result + assert records[0]["messages"][1] == { "role": "system", "content": "You are Ada, a Bot-specific finance analyst.", }, result if proof_case == "caller-tool": - assert records[0]["tools"] == [show_note_provider_tool()], result + assert provider_tool_shapes(records[0]["tools"]) == [show_note_shape()], result + # Handed back, not run: no result on the wire and none in the thread, and the one call the + # snapshot asks for is the model's own. + assert "TOOL_CALL_RESULT" not in result["eventTypes"], result + assert "TOOL_CALL_START" not in result["eventTypes"], result + first_snapshot = result["messagesSnapshots"][-1] + assert not [m for m in first_snapshot if m["role"] == "tool"], result + assert [call["id"] for m in first_snapshot for call in m.get("toolCalls") or []] == [ + "call_show_note_1" + ], result assert result["decodedToolCall"] == { "id": "call_show_note_1", "type": "function", @@ -596,8 +593,8 @@ def run_litellm_loopback_proof(proof_case, output): }, result assert result["secondStatusCode"] == 200, result assert "RUN_FINISHED" in result["secondEventTypes"], result - assert records[1]["tools"] == [show_note_provider_tool()], result - assert records[1]["messages"][-2:] == [ + assert provider_tool_shapes(records[1]["tools"]) == [show_note_shape()], result + assert without_empty_content(records[1]["messages"][-2:]) == [ { "role": "assistant", "tool_calls": [ @@ -620,28 +617,72 @@ def run_litellm_loopback_proof(proof_case, output): assert result["messagesSnapshots"][-1][-1]["toolCalls"][0]["id"] == "call_show_note_1" elif proof_case == "strict-projection": assert_provider_messages_are_projected(records[0]["messages"]) - assert records[0]["messages"][1] == { + # The picture reaches the model, just before the question CrewAI makes the request. + assert records[0]["messages"][2] == { "role": "user", "content": [ - {"type": "text", "text": "What should I review first?"}, {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}, ], "name": "analyst", }, result + assert records[0]["messages"][3]["role"] == "user", result + assert "What should I review first?" in records[0]["messages"][3]["content"], result + assert without_empty_content(records[0]["messages"][4:]) == [ + { + "role": "assistant", + "tool_calls": [ + { + "id": "call-1", + "type": "function", + "function": {"name": "lookup", "arguments": "{\"symbol\":\"ACME\"}"}, + } + ], + }, + {"role": "tool", "content": "Synthetic result", "tool_call_id": "call-1"}, + ], result + # Every message of the thread keeps the id it arrived under, so the snapshot replaces the + # client's copies instead of adding the thread again under new ones. It carries no system + # message, which leaves the client's as they are. snapshot = result["messagesSnapshots"][-1] - assert [message["id"] for message in snapshot[:4]] == [ - "system-1", + assert [message["id"] for message in snapshot[:3]] == [ "user-1", "assistant-1", "tool-1", ], result - assert snapshot[2]["toolCalls"][0]["id"] == "call-1", result - assert snapshot[3]["toolCallId"] == "call-1", result + assert not [message for message in snapshot if message["role"] == "system"], result + assert snapshot[1]["toolCalls"][0]["id"] == "call-1", result + assert snapshot[2]["toolCallId"] == "call-1", result else: - assert records[0]["messages"][1] == { - "role": "user", - "content": "What should I review first?", - }, result + assert records[0]["messages"][2]["role"] == "user", result + assert "What should I review first?" in records[0]["messages"][2]["content"], result + + +def without_empty_content(messages): + """CrewAI sends `content: null` on a message that only calls tools; the old harness left it out.""" + return [ + {key: value for key, value in message.items() if not (key == "content" and value is None)} + for message in messages + ] + + +def show_note_shape(): + return { + "name": "show_note", + "properties": {"title"}, + "required": ["title"], + } + + +def provider_tool_shapes(tools): + """The tools the model was offered, by what matters: CrewAI writes its own schema around them.""" + return [ + { + "name": tool["function"]["name"], + "properties": set(tool["function"]["parameters"]["properties"]), + "required": tool["function"]["parameters"].get("required"), + } + for tool in tools or [] + ] def basic_messages(): @@ -733,7 +774,7 @@ def assert_provider_messages_are_projected(messages): "proof_case", ["blank-provider", "blank-model", "strict-projection", "namespaced-model", "gateway-model"], ) -def test_crewai_endpoint_uses_normalized_model_with_real_litellm_loopback( +def test_crewai_endpoint_uses_normalized_model_with_real_provider_loopback( tmp_path, proof_case ): output = tmp_path / f"{proof_case}.json" @@ -791,4 +832,4 @@ def test_crewai_endpoint_forwards_caller_tools_and_accepts_tool_result_continuat ) parser.add_argument("--output", type=Path, required=True) arguments = parser.parse_args() - run_litellm_loopback_proof(arguments.proof_case, arguments.output) + run_loopback_proof(arguments.proof_case, arguments.output) diff --git a/docs/agent-frameworks.md b/docs/agent-frameworks.md index 1da569e9a2..af5ad7288f 100644 --- a/docs/agent-frameworks.md +++ b/docs/agent-frameworks.md @@ -165,6 +165,20 @@ app.include_router(router) Your flow then reads the role and the guidance in `self.state.messages`. Choose **CrewAI** in New Bot. +### A conversational CrewAI Agent + +An `Agent(conversational=True)` served with `add_crewai_flow_fastapi_endpoint(..., conversational=True)` +needs more than the route above. That path drops every system message of a run, not only the first. +CrewAI also runs an Agent's tools itself, while the tools OpenBot gives a Bot are run by the server. +The Bot asks for one and the run ends. Finally, the adapter gives each earlier message of the thread a +new id in its snapshots, so the app shows the conversation twice. + +OpenBot's own CrewAI Bot is built this way, and +[`agent-crewai/src/main.py`](../agent-crewai/src/main.py) handles all three. It keeps the run's system +messages for the Agent and turns OpenBot's tools into tools that hand the call back. It also keeps +each message's id. Start from that file and give the Agent your own role, goal and tools. Tools you +add run in your process as usual. + ## Claude Agent SDK `ag-ui-claude-sdk` sends Claude only the last message of a run, so the system messages never reach From aea91a645dc1db8db21b328f4a5ac39d11a036e8 Mon Sep 17 00:00:00 2001 From: Lorenze Jay Date: Thu, 26 Nov 2026 17:55:38 -0800 Subject: [PATCH 2/7] CrewAI Bot: serialize in-place session messages as session messages A live run appends the current user message to the session as a plain dict, and CrewAI appends its base ConversationMessage. Pydantic never sees in-place appends, and CrewAI serializes the state on every step, so every run logged "serialized value may not be as expected". The state's serializer now coerces those entries, leaving the list itself untouched. Co-Authored-By: Claude Opus 5.5 --- agent-crewai/src/main.py | 36 ++++++++++++++++++++++++++++++++- agent-crewai/tests/test_main.py | 32 +++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 1 deletion(-) diff --git a/agent-crewai/src/main.py b/agent-crewai/src/main.py index 67ead52f2b..39df3e222b 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -57,7 +57,14 @@ from crewai.utilities.pydantic_schema_utils import create_model_from_schema from fastapi import FastAPI, Request from fastapi.responses import JSONResponse -from pydantic import BaseModel, Field, PrivateAttr, field_validator +from pydantic import ( + BaseModel, + Field, + PrivateAttr, + SerializerFunctionWrapHandler, + field_serializer, + field_validator, +) # The one header OpenBot's server sends when it calls a managed Bot. Same name the TypeScript Bots # check, because a Bot is a Bot whatever it is written in. @@ -371,6 +378,33 @@ def content_may_be_empty(cls, value: Any) -> Any: ] return value + @field_serializer("messages", mode="wrap") + def messages_as_session_messages( + self, value: Any, handler: SerializerFunctionWrapHandler + ) -> Any: + """Messages appended to the list after validation are serialized as session messages too. + + The session's list is appended to in place, which pydantic never sees: the current user + message arrives as a plain dict, and CrewAI's own appends are its base `ConversationMessage`. + CrewAI serializes the state on every step, so each of those logged a pydantic "serialized value + may not be as expected" warning on every run. Coerced here, they serialize as the messages + they are, and the list itself is left as it is. + """ + if isinstance(value, list): + value = [_session_message(message) for message in value] + return handler(value) + + +def _session_message(message: Any) -> Any: + """One entry of the session's list, as the message the state declares.""" + if isinstance(message, OpenBotConversationMessage): + return message + if isinstance(message, BaseModel): + message = message.model_dump() + if isinstance(message, dict): + return OpenBotConversationMessage.model_validate({"content": None, **message}) + return message + def _with_request_media(conversation: list[dict[str, Any]]) -> list[dict[str, Any]]: """The newest user message's pictures and files, kept as a message of their own. diff --git a/agent-crewai/tests/test_main.py b/agent-crewai/tests/test_main.py index 58c9ffb3aa..00471fc5ad 100644 --- a/agent-crewai/tests/test_main.py +++ b/agent-crewai/tests/test_main.py @@ -174,6 +174,38 @@ def test_every_system_message_of_the_run_is_kept_for_the_agent(): assert inputs[main.CALLER_TOOLS_KEY] == [] +def test_messages_appended_after_validation_serialize_without_a_warning(): + """A live run appends the user message as a dict and CrewAI appends its base message class. + + CrewAI serializes the state on every step, and each of those used to log pydantic's + "serialized value may not be as expected" on every run. + """ + import warnings + + from crewai.flow.conversational import ConversationMessage + + state = main.OpenBotConversationState() + # Appended the way a run appends them: in place, past validation. + session: list = state.messages + session.append({"role": "user", "content": "Hello", "metadata": {}, "id": "u1"}) + session.append(ConversationMessage(role="assistant", content="Hi")) + session.append({"role": "assistant", "tool_calls": [], "id": "a2"}) + + with warnings.catch_warnings(): + warnings.simplefilter("error") + dumped = state.model_dump(mode="json") + copied = state.model_copy(deep=True).model_dump() + + assert [(m["role"], m["content"], m["id"]) for m in dumped["messages"]] == [ + ("user", "Hello", "u1"), + ("assistant", "Hi", None), + ("assistant", None, "a2"), + ] + assert copied["messages"] == dumped["messages"] + # Serializing does not rewrite the session's own list. + assert isinstance(state.messages[0], dict) + + def isolated_environment(directory): directory.mkdir(parents=True, exist_ok=True) inherited = ( From 96526136995f3cb850e0a6177a064a84d1bcb91d Mon Sep 17 00:00:00 2001 From: Lorenze Jay Date: Thu, 26 Nov 2026 19:28:58 -0800 Subject: [PATCH 3/7] CrewAI Bot: Gemini gets tool names, its own image parts and signed tool calls CrewAI's Gemini client failed every run that followed an OpenBot tool, and dropped images: - A tool result now carries the name of the tool it answers, taken from the matching tool call; Gemini refuses an empty function_response name. - Image parts become Gemini's inlineData / fileData parts, the only image parts CrewAI's Gemini client reads. - A replayed tool call carries Google's documented placeholder thought signature, since AG-UI has nowhere to keep the real one between runs. All three apply to Google only: a strict OpenAI-compatible server refuses a name on a tool message. Co-Authored-By: Claude Opus 5.5 --- agent-crewai/src/main.py | 100 +++++++++++++++++++++++++++++++- agent-crewai/tests/test_main.py | 64 ++++++++++++++++++++ 2 files changed, 163 insertions(+), 1 deletion(-) diff --git a/agent-crewai/src/main.py b/agent-crewai/src/main.py index 39df3e222b..5694b263c9 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -30,6 +30,7 @@ import hmac import json +import mimetypes import os import sys import threading @@ -435,6 +436,101 @@ def _with_request_media(conversation: list[dict[str, Any]]) -> list[dict[str, An return conversation +def _with_tool_names(conversation: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Each tool result names the tool it answers, read off the call it answers. + + AG-UI's tool message carries only the call's id. Gemini's function response needs the + function's name, and CrewAI's Gemini client reads it from the message, so without it every run + after the server ran a tool was refused ("function_response.name: Name cannot be empty"). + Gemini's only: an OpenAI-compatible server that accepts no field beyond the spec's refuses a + tool message that carries a name, and the others go by the id. + """ + names: dict[str, str] = {} + named: list[dict[str, Any]] = [] + for message in conversation: + for call in message.get("tool_calls") or []: + function = call.get("function") or {} + if call.get("id") and function.get("name"): + names[call["id"]] = function["name"] + if message.get("role") == "tool" and not message.get("name"): + name = names.get(message.get("tool_call_id") or "") + if name: + message = {**message, "name": name} + named.append(message) + return named + + +def _gemini_part(part: Any) -> Any: + """An `image_url` part as the inline data CrewAI's Gemini client reads. + + That client turns only `text`, `inlineData` and `fileData` parts into Gemini parts and drops + the rest without a word, so a picture the person sent never reached the model ("No image + provided"). A data URL carries its own type; an address is handed over as a file by URI with + the type its name implies, which Gemini needs. + """ + if not (isinstance(part, dict) and part.get("type") == "image_url"): + return part + url = str((part.get("image_url") or {}).get("url") or "") + if url.startswith("data:") and ";base64," in url: + header, data = url[len("data:") :].split(";base64,", 1) + return {"inlineData": {"mimeType": header or "application/octet-stream", "data": data}} + if url.startswith(("https://", "http://")): + mime_type, _ = mimetypes.guess_type(url.split("?", 1)[0]) + return {"fileData": {"fileUri": url, "mimeType": mime_type or "image/jpeg"}} + return part + + +# Gemini 3 refuses a function call in the history that does not carry the thought signature it was +# made with ("Function call is missing a thought_signature"). OpenBot runs each tool between two +# runs, and AG-UI's tool call has no field for a signature, so a call always comes back without +# its own. Keeping the real one would mean holding it between runs, on whichever replica answered +# the first. Google documents this value for a history whose signatures are not available. +GEMINI_UNSIGNED_CALL = b"skip_thought_signature_validator" + + +def _gemini_tool_call_parts(message: dict[str, Any]) -> list[Any]: + """The assistant's tool calls as Gemini parts, each carrying the unsigned-call signature. + + CrewAI's Gemini client sends `raw_tool_call_parts` as they are, in place of the parts it would + build from `tool_calls` without a signature. + """ + from google.genai import types + + parts = [] + for call in message.get("tool_calls") or []: + function = call.get("function") or {} + arguments = function.get("arguments") or {} + if isinstance(arguments, str): + try: + arguments = json.loads(arguments) if arguments else {} + except ValueError: + arguments = {} + parts.append( + types.Part( + function_call=types.FunctionCall( + name=str(function.get("name") or ""), + args=arguments if isinstance(arguments, dict) else {}, + ), + thought_signature=GEMINI_UNSIGNED_CALL, + ) + ) + return parts + + +def _for_provider(conversation: list[dict[str, Any]], provider: str) -> list[dict[str, Any]]: + """The conversation in the shape this provider's CrewAI client reads.""" + if provider != "google": + return conversation + shaped = [] + for message in _with_tool_names(conversation): + if isinstance(message.get("content"), list): + message = {**message, "content": [_gemini_part(part) for part in message["content"]]} + if message.get("role") == "assistant" and message.get("tool_calls"): + message = {**message, "raw_tool_call_parts": _gemini_tool_call_parts(message)} + shaped.append(message) + return shaped + + def _agent(tools: list[CallerTool]) -> Agent: """The Bot, as a CrewAI Agent, for one turn. @@ -483,7 +579,9 @@ async def converse_turn(self): ] if not conversation: raise ValueError("A turn needs at least one message") - conversation = _with_request_media(conversation) + conversation = _for_provider( + _with_request_media(conversation), bot_settings("agent-crewai").provider + ) hand_back = HandBack() tools = _caller_tools(self.state.openbot_caller_tools, hand_back) agent = _agent(tools) diff --git a/agent-crewai/tests/test_main.py b/agent-crewai/tests/test_main.py index 00471fc5ad..981443b1e0 100644 --- a/agent-crewai/tests/test_main.py +++ b/agent-crewai/tests/test_main.py @@ -174,6 +174,70 @@ def test_every_system_message_of_the_run_is_kept_for_the_agent(): assert inputs[main.CALLER_TOOLS_KEY] == [] +def test_tool_results_name_the_tool_they_answer(): + """Gemini refuses a function response without the function's name; AG-UI sends only the id.""" + conversation = [ + {"role": "user", "content": "Weather in Lisbon and Rome?"}, + { + "role": "assistant", + "content": None, + "tool_calls": [ + {"id": "call-1", "type": "function", "function": {"name": "get_weather", "arguments": "{}"}}, + {"id": "call-2", "type": "function", "function": {"name": "show_note", "arguments": "{}"}}, + ], + }, + {"role": "tool", "tool_call_id": "call-2", "content": "shown"}, + {"role": "tool", "tool_call_id": "call-1", "content": "sunny", "name": "kept"}, + {"role": "tool", "tool_call_id": "call-unknown", "content": "?"}, + ] + original = deepcopy(conversation) + + named = main._with_tool_names(conversation) + + assert [m.get("name") for m in named[2:]] == ["show_note", "kept", None] + assert conversation == original + + +def test_gemini_gets_its_own_image_parts_and_unsigned_tool_calls(): + """CrewAI's Gemini client drops `image_url` parts, and Gemini 3 refuses an unsigned call.""" + conversation = [ + { + "role": "user", + "content": [ + {"type": "image_url", "image_url": {"url": "data:image/png;base64,AAAA"}}, + {"type": "image_url", "image_url": {"url": "https://example.com/files/cat.jpg?x=1"}}, + {"type": "text", "text": "What is this?"}, + ], + }, + { + "role": "assistant", + "content": None, + "tool_calls": [ + {"id": "call-1", "type": "function", "function": {"name": "get_weather", "arguments": '{"city": "Lisbon"}'}}, + ], + }, + {"role": "tool", "tool_call_id": "call-1", "content": "sunny"}, + ] + + # Only Gemini's: a strict OpenAI-compatible server refuses a named tool message. + assert main._for_provider(conversation, "openai") is conversation + assert main._for_provider(conversation, "anthropic") is conversation + shaped = main._for_provider(conversation, "google") + + assert shaped[0]["content"] == [ + {"inlineData": {"mimeType": "image/png", "data": "AAAA"}}, + {"fileData": {"fileUri": "https://example.com/files/cat.jpg?x=1", "mimeType": "image/jpeg"}}, + {"type": "text", "text": "What is this?"}, + ] + [part] = shaped[1]["raw_tool_call_parts"] + assert part.function_call.name == "get_weather" + assert part.function_call.args == {"city": "Lisbon"} + assert part.thought_signature == main.GEMINI_UNSIGNED_CALL + assert shaped[2] == {**conversation[2], "name": "get_weather"} + assert "raw_tool_call_parts" not in conversation[1] + assert "name" not in conversation[2] + + def test_messages_appended_after_validation_serialize_without_a_warning(): """A live run appends the user message as a dict and CrewAI appends its base message class. From 2e96fbcfd15466f261aab949283b20f383d23131 Mon Sep 17 00:00:00 2001 From: lorenzejay Date: Tue, 1 Dec 2026 10:01:47 -0800 Subject: [PATCH 4/7] CrewAI Bot: hand back every tool, keep the model's words, and carry main's Gemini and reminder rules The conversational Agent now does what the Bot on main did: - A tool whose name CrewAI changes for the model (`showNote`, `askApproval`, `mcp__...`) is handed back under the server's name. The model calls it by `sanitize_tool_name`, and the hand-back looked it up by the server's name, so the turn answered "Handed to the caller to run." - A handed-back call leaves out the `null`s its own schema did not ask for. CrewAI offers tools in strict mode, so every optional field came back as `null`. - A `developer` message is kept as an instruction and left out of CrewAI's session, whose messages have no such role. It refused the whole run. - An empty `OPENAI_BASE_URL` or `ANTHROPIC_BASE_URL` is unset. The providers' own SDKs took `""` as the address, and every OpenAI run failed with `APIConnectionError`. - The model runs on CrewAI's own client for OpenAI, Anthropic and Google, whatever it is called. CrewAI sent a model it has not heard of (Gemini on the model gateway, `qwen/qwen3-8b`) to LiteLLM, which offered it no tools. - The words the model said in a step that called tools are the reply's content. CrewAI keeps that step with none, so a line on a long job never reached the person. From main: Gemini's thought signature goes out on the handed-back call's `encryptedValue` and back to Gemini, with Google's placeholder only for a call the thread has none for (#2397); the progress reminder after five silent steps (#2436, #2443), added to the latest result where CrewAI would take a note in the person's turn for the request; the empty-turn rule (#2449); `google` as `gemini/`. Co-Authored-By: Claude Opus 5.5 --- agent-crewai/src/main.py | 528 +++++++++++++++++-- agent-crewai/tests/test_main.py | 230 ++++++++ agent-crewai/tests/test_progress_reminder.py | 32 +- docs/agent-frameworks.md | 15 + 4 files changed, 742 insertions(+), 63 deletions(-) diff --git a/agent-crewai/src/main.py b/agent-crewai/src/main.py index 5694b263c9..dd9f4433a4 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -28,6 +28,7 @@ from __future__ import annotations +import base64 import hmac import json import mimetypes @@ -44,18 +45,141 @@ # The spec file every language in the box reads: one level above this Bot in the repository, and # one level above /app/src in the image the Dockerfile builds. sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "shared")) -from model_providers import bot_settings +from empty_turns import without_empty_turns +from progress_reminder import with_litellm_reminders +from model_providers import bot_settings, litellm_model_id from run_model_key import RunModelKey +import gemini_signatures + +# A call the thread brings back with no thought signature goes to Gemini 3 with Google's +# placeholder. One it brings back with its signature goes with that (`_signed_calls`). +gemini_signatures.install() + +import httpx # noqa: E402 + + +# --- Gemini's signatures, read off its answers ----------------------------------------------- +# +# Google's OpenAI-compatible endpoint gives each call Gemini makes a thought signature +# (`tool_calls[i].extra_content.google.thought_signature`), and CrewAI's OpenAI client keeps only a +# call's id, type and function, so the signature never reached the turn's messages. It is read here +# off the answer as it passes, at the HTTP request as `gemini_signatures` signs the request, and +# kept by call id for the turn that hands the call back (`_thought_signatures`). Only a Gemini +# model that checks signatures is read, and the answer goes on exactly as it came. +_signatures_by_call: dict[str, str] = {} +_signatures_lock = threading.Lock() +# Calls a process keeps a signature for, oldest dropped first: one turn needs only its own. +SIGNATURES_KEPT = 1024 + + +def _call_signature(call: Any) -> str | None: + extra = call.get("extra_content") if isinstance(call, dict) else None + google = extra.get("google") if isinstance(extra, dict) else None + signature = google.get("thought_signature") if isinstance(google, dict) else None + return signature if isinstance(signature, str) and signature else None + + +def _note_signatures(answer: Any) -> None: + """Each signed call in one Chat Completions answer or streamed chunk, by its id.""" + if not isinstance(answer, dict): + return + for choice in answer.get("choices") or []: + message = (choice.get("delta") or choice.get("message")) if isinstance(choice, dict) else None + for call in (message.get("tool_calls") or []) if isinstance(message, dict) else []: + signature = _call_signature(call) + if signature and isinstance(call.get("id"), str): + with _signatures_lock: + _signatures_by_call[call["id"]] = signature + while len(_signatures_by_call) > SIGNATURES_KEPT: + _signatures_by_call.pop(next(iter(_signatures_by_call))) + + +def _taken_signature(call_id: Any) -> str | None: + with _signatures_lock: + return _signatures_by_call.pop(call_id, None) if isinstance(call_id, str) else None + + +def _asks_gemini(request: httpx.Request) -> bool: + if request.method.upper() != "POST" or not request.url.path.endswith("/chat/completions"): + return False + try: + body = json.loads(request.content) + except Exception: # A streamed or unreadable body, which no model call sends. + return False + return isinstance(body, dict) and gemini_signatures.checks_signatures(body.get("model")) + + +class _SseLines: + """Server-sent events fed in as bytes, each `data:` line's JSON noted as it completes.""" + + def __init__(self) -> None: + self._pending = b"" + + def feed(self, chunk: bytes) -> None: + *lines, self._pending = (self._pending + chunk).split(b"\n") + for line in lines: + line = line.strip() + if line.startswith(b"data:") and line[5:].strip() not in (b"", b"[DONE]"): + try: + _note_signatures(json.loads(line[5:])) + except ValueError: + pass + + +def _observed(request: httpx.Request, response: httpx.Response, stream: bool) -> httpx.Response: + if not _asks_gemini(request): + return response + if not stream: + try: + _note_signatures(response.json()) + except Exception: # Not a JSON answer: an error, which carries no calls. + pass + return response + lines = _SseLines() + iter_bytes, aiter_bytes = response.iter_bytes, response.aiter_bytes + + def observed_iter_bytes(*args: Any, **kwargs: Any) -> Iterator[bytes]: + for chunk in iter_bytes(*args, **kwargs): + lines.feed(chunk) + yield chunk + + async def observed_aiter_bytes(*args: Any, **kwargs: Any): + async for chunk in aiter_bytes(*args, **kwargs): + lines.feed(chunk) + yield chunk + + response.iter_bytes = observed_iter_bytes # type: ignore[method-assign] + response.aiter_bytes = observed_aiter_bytes # type: ignore[method-assign] + return response + + +_sync_send, _async_send = httpx.Client.send, httpx.AsyncClient.send + + +def _send(self, request, *args, **kwargs): + return _observed(request, _sync_send(self, request, *args, **kwargs), kwargs.get("stream", False)) + + +async def _asend(self, request, *args, **kwargs): + response = await _async_send(self, request, *args, **kwargs) + return _observed(request, response, kwargs.get("stream", False)) + + +httpx.Client.send = _send # type: ignore[method-assign] +httpx.AsyncClient.send = _asend # type: ignore[method-assign] import ag_ui_crewai.endpoint as crewai_endpoint from ag_ui.core import Message, Tool from ag_ui_crewai import add_crewai_flow_fastapi_endpoint from crewai import LLM, Agent from crewai.agent.conversation import AgentConversationState +from crewai.events.event_bus import crewai_event_bus +from crewai.events.types.llm_events import LLMStreamChunkEvent from crewai.flow import ConversationConfig, Flow, listen from crewai.flow.conversational import ConversationMessage from crewai.tools import BaseTool from crewai.utilities.pydantic_schema_utils import create_model_from_schema +from crewai.utilities.string_utils import sanitize_tool_name from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from pydantic import ( @@ -101,13 +225,57 @@ def _model() -> str: `openai/openai/gpt-5.6-terra`. Treating a slash as "already a provider" dropped the prefix, and the call then either went to a provider nobody configured or sent only the second half to the endpoint. + + OpenBot calls Google AI Studio `google` and LiteLLM calls it `gemini` (`litellm_model_id`). + CrewAI's own Gemini client takes either, and LiteLLM, which CrewAI calls for a Gemini model its + client does not know, takes only `gemini`. """ settings = bot_settings("agent-crewai") - return f"{settings.provider}/{settings.model}" + return litellm_model_id(settings.provider, settings.model) + + +# OpenBot's providers that CrewAI has a client of its own for, by CrewAI's name for each. +_CREWAI_CLIENTS = {"openai": "openai", "anthropic": "anthropic", "google": "gemini"} def _llm() -> LLM: - return LLM(model=_model()) + """The model, on CrewAI's own client for the provider OpenBot chose, whatever it is called. + + Given `provider/model`, CrewAI uses its own client only for a model it has heard of, and sends + any other to LiteLLM, which does not know it either and says it cannot call functions. CrewAI + then never offers the model a tool: a Gemini model on OpenBot's model gateway, or any model on + an OpenAI-compatible server (`qwen/qwen3-8b`), answered every request for a tool in words. Named + as a provider here, the client is CrewAI's own, and the model is sent exactly as the endpoint + publishes it. A provider CrewAI has no client for still goes through LiteLLM. + """ + settings = bot_settings("agent-crewai") + client = _CREWAI_CLIENTS.get(settings.provider) + if client is None: + return LLM(model=_model()) + return LLM(model=settings.model, provider=client) + + +def _drop_blank_base_urls() -> None: + """Compose exports missing overrides as ""; the SDKs only default an absent URL. + + The model screen writes the endpoint it did not need as empty: `OPENAI_BASE_URL` for a plain + OpenAI key, `ANTHROPIC_BASE_URL` for an Anthropic key. CrewAI calls OpenAI and Anthropic through + their own SDKs, which read the variable themselves, so the empty value reached the SDK as the + address and every run failed with `APIConnectionError`. LiteLLM, which this Bot called before, + treated it as unset. Taking it out lets the SDK use its own endpoint; a real one is left as it + is. The same rule as `_drop_blank_base_urls` in `agent-pydantic-ai`. + """ + for name in ("OPENAI_BASE_URL", "ANTHROPIC_BASE_URL"): + value = os.environ.get(name) + if value is None: + continue + if value.strip(): + os.environ[name] = value.strip() + else: + os.environ.pop(name, None) + + +_drop_blank_base_urls() # --- The run's system messages, kept for the Agent -------------------------------------------- @@ -180,47 +348,164 @@ def record(self, name: str) -> None: with self._lock: self.names.append(name) - def calls(self, messages: list[Any], names: dict[str, str]) -> list[dict[str, Any]]: + def calls(self, messages: list[Any], tools: list[CallerTool]) -> list[dict[str, Any]]: """The calls to hand back, as the model made them: its own ids and arguments. The model's call id, not one made up here, because the next run carries the tool's result - under that id and CrewAI sends it to the model with the call it answers. `names` maps the - name the model was shown to the name the server knows. + under that id and CrewAI sends it to the model with the call it answers. The model calls a + tool by the name it was shown (`CallerTool.name`); the call goes back under the name the + server knows (`caller_name`). """ if not self.names: return [] - asked = next( - ( - message.get("tool_calls") - for message in reversed(messages) - if isinstance(message, dict) - and message.get("role") == "assistant" - and message.get("tool_calls") - ), - None, - ) or [] + step = _calling_step(messages) + by_name = {tool.name: tool for tool in tools} + signatures = _thought_signatures(step) handed_back = [] - for call in asked: + for index, call in enumerate(step.get("tool_calls") or []): function = call.get("function") or {} - name = names.get(function.get("name")) - if name is None: + tool = by_name.get(function.get("name")) + if tool is None: continue - arguments = function.get("arguments") - handed_back.append( - { - "id": call.get("id") or f"call_{uuid4().hex}", - "type": "function", - "function": { - "name": name, - "arguments": arguments - if isinstance(arguments, str) - else json.dumps(arguments or {}), - }, - } - ) + handed = { + "id": call.get("id") or f"call_{uuid4().hex}", + "type": "function", + "function": { + "name": tool.caller_name, + "arguments": tool.arguments_for_caller(function.get("arguments")), + }, + } + if signatures[index]: + # Out with the call and back in the thread, which keeps a call's `encryptedValue`. + handed["encrypted_value"] = signatures[index] + handed_back.append(handed) return handed_back +class StepWords: + """What the model said in each of its calls in one turn, from the words it streamed. + + CrewAI keeps a step that called tools with `content: None`, whatever the model said with the + calls, so a line on a long job ("Ten records read so far") never reached the person, and the + progress reminder counted the step as silent. The words still stream past as the model's chunks, + which CrewAI sends in order, as they arrive (`call_id` tells its calls apart). + """ + + def __init__(self, agent: Agent) -> None: + self._agent_id = str(agent.id) + self._lock = threading.Lock() + self._by_call: dict[str, list[str]] = {} + + def heard(self, source: Any, event: LLMStreamChunkEvent) -> None: + if str(getattr(event, "agent_id", None)) != self._agent_id: + return + if event.tool_call is not None or not event.chunk: + return + with self._lock: + self._by_call.setdefault(event.call_id, []).append(event.chunk) + + def last_said(self) -> str | None: + """The words of the model's latest call that said any, or None.""" + with self._lock: + calls = list(self._by_call.values()) + return "".join(calls[-1]).strip() or None if calls else None + + +@contextmanager +def _listening(agent: Agent) -> Iterator[StepWords]: + words = StepWords(agent) + crewai_event_bus.on(LLMStreamChunkEvent)(words.heard) + try: + yield words + finally: + crewai_event_bus.off(LLMStreamChunkEvent, words.heard) + + +def _calling_step(messages: list[Any]) -> dict[str, Any]: + """The model's last step that called tools, as CrewAI kept it, or an empty one.""" + return next( + ( + message + for message in reversed(messages) + if isinstance(message, dict) + and message.get("role") == "assistant" + and message.get("tool_calls") + ), + None, + ) or {} + + +def _thought_signatures(step: dict[str, Any]) -> list[str | None]: + """The thought signature Gemini gave each call of a step, as text, or None per call. + + Gemini 3 refuses the run that brings a tool's result unless the call comes back with the + signature it gave it. Google's OpenAI-compatible endpoint puts it on the call + (`extra_content.google.thought_signature`, text already), which CrewAI drops and this file + reads off the answer (`_note_signatures`); CrewAI's own Gemini client keeps Gemini's parts + beside the calls (`raw_tool_call_parts`), whose signature is bytes. + """ + calls = step.get("tool_calls") or [] + signatures: list[str | None] = [ + _call_signature(call) or _taken_signature(call.get("id") if isinstance(call, dict) else None) + for call in calls + ] + parts = [ + part + for part in step.get("raw_tool_call_parts") or [] + if getattr(part, "function_call", None) is not None + ] + for index, part in enumerate(parts[: len(calls)]): + signature = getattr(part, "thought_signature", None) + if not signatures[index] and signature and signature != GEMINI_UNSIGNED_CALL: + signatures[index] = base64.b64encode(signature).decode("ascii") + return signatures + + +def _allows_null(schema: Any) -> bool: + """Whether a JSON Schema accepts `null`. One it cannot read is taken to.""" + if not isinstance(schema, dict): + return True + if "enum" in schema: + return None in schema["enum"] + if "const" in schema: + return schema["const"] is None + if schema.get("nullable") is True: + return True + kind = schema.get("type") + if kind is not None: + return kind == "null" or (isinstance(kind, list) and "null" in kind) + alternatives = [*(schema.get("anyOf") or []), *(schema.get("oneOf") or [])] + if alternatives: + return any(_allows_null(alternative) for alternative in alternatives) + return True + + +def _without_unasked_nulls(value: Any, schema: Any) -> Any: + """`value` without the `null`s the tool's own schema did not ask for, at any depth. + + CrewAI offers the model every tool in strict mode, which makes each optional property required + and nullable: the model has to send `"limit": null` for a limit it means to leave out. The tool + is the caller's, and its schema said the property is optional, not that it may be `null`, so a + caller that checks arguments against it refuses the call. Only a property the schema does not + require is dropped; a required one the model left `null` is passed on as it said it. + """ + if not isinstance(schema, dict): + return value + if isinstance(value, dict): + properties = schema.get("properties") or {} + required = set(schema.get("required") or []) + kept = {} + for key, item in value.items(): + item_schema = properties.get(key) + if item is None and key not in required and item_schema is not None and not _allows_null(item_schema): + continue + kept[key] = _without_unasked_nulls(item, item_schema) + return kept + if isinstance(value, list) and isinstance(schema.get("items"), dict): + return [_without_unasked_nulls(item, schema["items"]) for item in value] + return value + + class CallerTool(BaseTool): """An AG-UI tool, as a CrewAI tool that is not run here. @@ -231,17 +516,35 @@ class CallerTool(BaseTool): result_as_answer: bool = True _hand_back: HandBack = PrivateAttr() + # The name the server knows it by. `name` is the one the model is shown and calls it by. caller_name: str + # The tool's own JSON Schema, as the caller gave it. + caller_parameters: dict[str, Any] = Field(default_factory=dict) def __init__(self, *, hand_back: HandBack, **data: Any) -> None: - # The name the server knows it by, whatever CrewAI makes of `name` for the model. - super().__init__(caller_name=data["name"], **data) + super().__init__(**data) self._hand_back = hand_back def _run(self, **arguments: Any) -> str: self._hand_back.record(self.caller_name) return "Handed to the caller to run." + def arguments_for_caller(self, arguments: Any) -> str: + """The model's arguments as the caller's schema asks for them, as JSON text. + + The model's own text when there is nothing to take out of it. + """ + said = arguments if isinstance(arguments, str) else None + if said is not None: + try: + arguments = json.loads(said) if said.strip() else {} + except ValueError: + return said + kept = _without_unasked_nulls(arguments or {}, self.caller_parameters) + if said is not None and kept == arguments: + return said + return json.dumps(kept) + # CrewAI reports every tool it runs, and ag-ui-crewai turns that report into a tool call with its # result. For a caller's tool that is a call already "answered" (by the stand-in above), under an id @@ -272,9 +575,8 @@ def _handing_back(agent: Agent, tools: list[CallerTool]) -> Iterator[None]: """While the Agent's turn runs, its reports of these tools stay here.""" key = str(agent.id) with _caller_tools_lock: - _caller_tools_by_agent[key] = frozenset( - name for tool in tools for name in (tool.name, tool.caller_name) - ) + # CrewAI reports a tool by the name the model called it by, which is `tool.name`. + _caller_tools_by_agent[key] = frozenset(tool.name for tool in tools) try: yield finally: @@ -283,19 +585,36 @@ def _handing_back(agent: Agent, tools: list[CallerTool]) -> Iterator[None]: def _caller_tools(tools: list[dict[str, Any]], hand_back: HandBack) -> list[CallerTool]: + """The run's tools, each under the name CrewAI shows the model. + + CrewAI offers a tool to the model as `sanitize_tool_name(tool.name)` (`showBarChart` as + `show_bar_chart`, `mcp__acme-wiki__search` as `mcp_acme_wiki_search`), and the model calls it by + that. Named so here already, the name the model calls, the name CrewAI reports and the name the + turn hands back by are one name; the server's own stays in `caller_name`. Two tools whose names + come out the same get a number, as CrewAI would number them. + """ built: list[CallerTool] = [] + shown: set[str] = set() for tool in tools: name = tool.get("name") if not isinstance(name, str) or not name: continue + model_name = base = sanitize_tool_name(name) + number = 1 + while model_name in shown: + number += 1 + model_name = f"{base}_{number}" + shown.add(model_name) parameters = tool.get("parameters") or {"type": "object", "properties": {}} built.append( CallerTool( hand_back=hand_back, - name=name, + name=model_name, + caller_name=name, + caller_parameters=parameters, description=tool.get("description") or name, args_schema=create_model_from_schema( - {"title": f"{name}_arguments", **parameters} + {"title": f"{model_name}_arguments", **parameters} ), ) ) @@ -314,6 +633,14 @@ def _caller_tools(tools: list[dict[str, Any]], hand_back: HandBack) -> list[Call "tool": {"role", "content", "name", "tool_call_id"}, } _TOOL_CALL_FIELDS = ("id", "type", "function") +# Where a call's thought signature waits between `_message_dict` and `_signed_calls`. Never sent. +SIGNATURE_KEY = "openbot_thought_signature" + + +def _sealed_value(call: dict[str, Any]) -> str | None: + """The `encryptedValue` a call came back with, under either spelling a dump gives it.""" + sealed = call.get("encrypted_value") or call.get("encryptedValue") + return sealed if isinstance(sealed, str) and sealed else None def _message_dict(message: Any) -> dict[str, Any] | None: @@ -335,7 +662,11 @@ def _message_dict(message: Any) -> dict[str, Any] | None: } if isinstance(kept.get("tool_calls"), list): kept["tool_calls"] = [ - {key: call[key] for key in _TOOL_CALL_FIELDS if key in call} + { + **{key: call[key] for key in _TOOL_CALL_FIELDS if key in call}, + # Gemini's signature, back from the thread; `_signed_calls` sends it or drops it. + **({SIGNATURE_KEY: sealed} if (sealed := _sealed_value(call)) else {}), + } for call in kept["tool_calls"] if isinstance(call, dict) ] @@ -362,6 +693,23 @@ class OpenBotConversationState(AgentConversationState): openbot_instructions: list[str] = Field(default_factory=list) openbot_caller_tools: list[dict[str, Any]] = Field(default_factory=list) + @field_validator("messages", mode="before") + @classmethod + def developer_messages_are_instructions(cls, value: Any) -> Any: + """A `developer` message is the Bot's instructions, which the turn already holds. + + ag-ui-crewai seeds the session with every message but `system`, and CrewAI's session message + has no `developer` role, so one refused the whole run. `_openbot_prepare_crewai_inputs` + keeps it with the system messages, in order, and the Agent is given it from there. + """ + if isinstance(value, list): + return [ + message + for message in value + if not (isinstance(message, dict) and message.get("role") == "developer") + ] + return value + @field_validator("messages", mode="before") @classmethod def content_may_be_empty(cls, value: Any) -> Any: @@ -482,14 +830,26 @@ def _gemini_part(part: Any) -> Any: # Gemini 3 refuses a function call in the history that does not carry the thought signature it was # made with ("Function call is missing a thought_signature"). OpenBot runs each tool between two -# runs, and AG-UI's tool call has no field for a signature, so a call always comes back without -# its own. Keeping the real one would mean holding it between runs, on whichever replica answered -# the first. Google documents this value for a history whose signatures are not available. -GEMINI_UNSIGNED_CALL = b"skip_thought_signature_validator" +# runs, so the signature goes out on the handed-back call as its `encryptedValue` and comes back +# with it in the thread (`HandBack.calls`). A call that comes back without one (a thread from +# before, or a call another provider's model made) goes with the value Google documents for a +# history whose signatures are not available. +GEMINI_UNSIGNED_CALL = gemini_signatures.GEMINI_SKIP_SIGNATURE.encode() + + +def _gemini_signature(call: dict[str, Any]) -> bytes: + """The signature a call came back with, as Gemini's client takes it, or the placeholder.""" + sealed = call.get(SIGNATURE_KEY) + if isinstance(sealed, str) and sealed: + try: + return base64.b64decode(sealed, validate=True) + except ValueError: + pass + return GEMINI_UNSIGNED_CALL def _gemini_tool_call_parts(message: dict[str, Any]) -> list[Any]: - """The assistant's tool calls as Gemini parts, each carrying the unsigned-call signature. + """The assistant's tool calls as Gemini parts, each carrying its signature. CrewAI's Gemini client sends `raw_tool_call_parts` as they are, in place of the parts it would build from `tool_calls` without a signature. @@ -511,7 +871,7 @@ def _gemini_tool_call_parts(message: dict[str, Any]) -> list[Any]: name=str(function.get("name") or ""), args=arguments if isinstance(arguments, dict) else {}, ), - thought_signature=GEMINI_UNSIGNED_CALL, + thought_signature=_gemini_signature(call), ) ) return parts @@ -531,6 +891,54 @@ def _for_provider(conversation: list[dict[str, Any]], provider: str) -> list[dic return shaped +def _with_reminders(conversation: list[dict[str, Any]], model: str) -> list[dict[str, Any]]: + """The conversation with the progress reminder in it, where CrewAI keeps it in place. + + `with_litellm_reminders` places it after the latest results: as a system message for OpenAI's + own models, and otherwise as a note in the person's turn, a user message. CrewAI takes the + newest user message for the turn's request ("Current Task"), so as a user message the note would + become the task and the person's request history. In that form it is added to the result it + follows instead, which Claude reads in the same turn as the results, as LiteLLM sends it. + """ + originals = {id(message) for message in conversation} + sent: list[dict[str, Any]] = [] + for message in with_litellm_reminders(conversation, model): + note = id(message) not in originals and message.get("role") == "user" + if note and sent and sent[-1].get("role") == "tool": + result = sent[-1] + words = result.get("content") + words = words if isinstance(words, str) else _text(words) + sent[-1] = {**result, "content": f"{words}\n\n{message['content']}"} + continue + sent.append(message) + return sent + + +def _signed_calls(conversation: list[dict[str, Any]], model: str) -> list[dict[str, Any]]: + """Each call's thought signature where the model reads one, and on no other request. + + A Gemini model on an OpenAI-compatible endpoint (a Gemini key saved in Settings, OpenBot's + model gateway) reads it as `extra_content.google.thought_signature`; CrewAI's own Gemini client + has it in `raw_tool_call_parts` already (`_for_provider`). Any other provider is sent the call + as it was, since a strict one refuses a field it does not know. + """ + gemini = gemini_signatures.checks_signatures(model) + signed = [] + for message in conversation: + calls = message.get("tool_calls") + if isinstance(calls, list) and any(isinstance(call, dict) and SIGNATURE_KEY in call for call in calls): + sent_calls = [] + for call in calls: + call = dict(call) + sealed = call.pop(SIGNATURE_KEY, None) + if gemini and sealed and not message.get("raw_tool_call_parts"): + call["extra_content"] = {"google": {"thought_signature": sealed}} + sent_calls.append(call) + message = {**message, "tool_calls": sent_calls} + signed.append(message) + return signed + + def _agent(tools: list[CallerTool]) -> Agent: """The Bot, as a CrewAI Agent, for one turn. @@ -579,22 +987,34 @@ async def converse_turn(self): ] if not conversation: raise ValueError("A turn needs at least one message") - conversation = _for_provider( - _with_request_media(conversation), bot_settings("agent-crewai").provider + model = _model() + # Each step with only the words the model said (shared/empty_turns.py), and after five + # silent tool steps in a row a reminder to say a line, in what the model is sent only + # (shared/progress_reminder.py). + conversation = _with_reminders( + without_empty_turns(_with_request_media(conversation)), model + ) + conversation = _signed_calls( + _for_provider(conversation, bot_settings("agent-crewai").provider), model ) hand_back = HandBack() tools = _caller_tools(self.state.openbot_caller_tools, hand_back) agent = _agent(tools) - with self._conversation_streaming_enabled(agent.llm), _handing_back(agent, tools): + with ( + self._conversation_streaming_enabled(agent.llm), + _handing_back(agent, tools), + _listening(agent) as words, + ): # CrewAI keeps every message before the newest user message as history, with its # role, after its own system prompt: the server's instructions lead it. result = await agent.kickoff_async(messages=[*instructions, *conversation]) - calls = hand_back.calls( - result.messages, {tool.name: tool.caller_name for tool in tools} - ) + calls = hand_back.calls(result.messages, tools) if calls: - # The turn's reply asks the caller to run its tools, and the run ends there. - self._reply(None, tool_calls=calls) + # The turn's reply asks the caller to run its tools, and the run ends there. With the + # words the model said in that step, if it said any: a line on a long job is how the + # person hears from it. + said = _text(_calling_step(result.messages).get("content")).strip() or words.last_said() + self._reply(said, tool_calls=calls) return None self._reply(result.raw) return result diff --git a/agent-crewai/tests/test_main.py b/agent-crewai/tests/test_main.py index b4a1374f31..a887411d78 100644 --- a/agent-crewai/tests/test_main.py +++ b/agent-crewai/tests/test_main.py @@ -1,4 +1,5 @@ import argparse +import base64 import ipaddress import json import os @@ -78,6 +79,235 @@ def test_model_normalizes_blank_provider_and_model_before_defaults( assert main._model() == expected +def test_blank_base_urls_are_dropped_and_real_ones_kept(monkeypatch): + monkeypatch.setenv("OPENAI_BASE_URL", "") + monkeypatch.setenv("ANTHROPIC_BASE_URL", " https://gateway.example/anthropic ") + + main._drop_blank_base_urls() + + assert "OPENAI_BASE_URL" not in os.environ + assert os.environ["ANTHROPIC_BASE_URL"] == "https://gateway.example/anthropic" + + +@pytest.mark.parametrize( + ("provider", "model", "client", "sent_as"), + [ + # Models CrewAI has not heard of: it used to send these to LiteLLM, which offered no tools. + ("openai", "gemini-3.8-flash", "OpenAICompletion", "gemini-3.8-flash"), + ("openai", "qwen/qwen3-8b", "OpenAICompletion", "qwen/qwen3-8b"), + ("openai", "gpt-5.5", "OpenAICompletion", "gpt-5.5"), + ("anthropic", "claude-sonnet-5-5", "AnthropicCompletion", "claude-sonnet-5-5"), + ("google", "gemini-3.8-flash", "GeminiCompletion", "gemini-3.8-flash"), + ], +) +def test_the_model_runs_on_crewais_own_client_and_is_offered_tools( + monkeypatch, provider, model, client, sent_as +): + monkeypatch.setenv("BOT_PROVIDER", provider) + monkeypatch.setenv("BOT_MODEL", model) + for key in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GOOGLE_API_KEY"): + monkeypatch.setenv(key, "test-key") + + llm = main._llm() + + assert type(llm).__name__ == client + assert llm.model == sent_as + assert llm.supports_function_calling() + + +def test_a_tool_whose_name_crewai_changes_is_handed_back_under_the_servers_name(): + """CrewAI shows the model `showNote` as `show_note`, and the model calls it by that.""" + hand_back = main.HandBack() + tools = main._caller_tools( + [ + {"name": "showNote", "description": "Show a note.", "parameters": {"type": "object", "properties": {}}}, + {"name": "mcp__acme-wiki__search_pages", "parameters": {"type": "object", "properties": {}}}, + {"name": "show-note", "parameters": {"type": "object", "properties": {}}}, + ], + hand_back, + ) + assert [tool.name for tool in tools] == ["show_note", "mcp_acme_wiki_search_pages", "show_note_2"] + assert [tool.caller_name for tool in tools] == ["showNote", "mcp__acme-wiki__search_pages", "show-note"] + + tools[0]._run() + step = { + "role": "assistant", + "content": None, + "tool_calls": [ + {"id": "call-1", "type": "function", "function": {"name": "show_note", "arguments": "{}"}}, + {"id": "call-2", "type": "function", "function": {"name": "mcp_acme_wiki_search_pages", "arguments": "{}"}}, + {"id": "call-3", "type": "function", "function": {"name": "show_note_2", "arguments": "{}"}}, + ], + } + + calls = hand_back.calls([{"role": "user", "content": "Hi"}, step], tools) + + assert [(call["id"], call["function"]["name"]) for call in calls] == [ + ("call-1", "showNote"), + ("call-2", "mcp__acme-wiki__search_pages"), + ("call-3", "show-note"), + ] + + +def test_crewais_report_of_a_renamed_caller_tool_is_not_passed_on(): + """CrewAI reports a tool by the name the model called; a caller's tool is never reported.""" + from types import SimpleNamespace + + tools = main._caller_tools( + [{"name": "showNote", "parameters": {"type": "object", "properties": {}}}], main.HandBack() + ) + agent = main._agent(tools) + report = SimpleNamespace(agent_id=agent.id, tool_name="show_note") + + with main._handing_back(agent, tools): + assert main._is_caller_tool_event(report) + assert not main._is_caller_tool_event(report) + + +def test_handed_back_arguments_leave_out_the_nulls_the_tool_did_not_ask_for(): + """CrewAI sends tools in strict mode, so the model writes `null` for every optional field.""" + [tool] = main._caller_tools( + [ + { + "name": "search", + "parameters": { + "type": "object", + "properties": { + "query": {"type": "string"}, + "limit": {"type": "integer"}, + "cursor": {"type": ["string", "null"]}, + "filter": { + "type": "object", + "properties": {"tag": {"type": "string"}, "since": {"type": "string"}}, + "required": ["tag"], + }, + "owner": {"anyOf": [{"type": "string"}, {"type": "null"}]}, + "note": {"type": "string"}, + }, + "required": ["query", "note"], + }, + } + ], + main.HandBack(), + ) + + arguments = tool.arguments_for_caller( + '{"query": "q", "limit": null, "cursor": null, "filter": {"tag": "t", "since": null},' + ' "owner": null, "note": null}' + ) + + # Optional and not nullable: left out. Nullable, or required: as the model said. + assert json.loads(arguments) == { + "query": "q", + "cursor": None, + "filter": {"tag": "t"}, + "owner": None, + "note": None, + } + # Nothing to leave out: the model's own text, as it wrote it. + assert tool.arguments_for_caller('{"query":"q","note":"n"}') == '{"query":"q","note":"n"}' + + +def test_a_developer_message_is_an_instruction_and_not_a_turn_of_the_session(): + """CrewAI's session message has no `developer` role, and seeding one refused the whole run.""" + from ag_ui.core import DeveloperMessage, UserMessage + + inputs = main.crewai_endpoint.crewai_prepare_inputs( + state={}, + messages=[ + DeveloperMessage(id="d1", role="developer", content="Answer in French."), + UserMessage(id="u1", role="user", content="Hello"), + ], + tools=[], + context=[], + forwarded_props={}, + ) + state = main.OpenBotConversationState.model_validate( + { + "messages": [ + {"id": "d1", "role": "developer", "content": "Answer in French."}, + {"id": "u1", "role": "user", "content": "Hello"}, + ] + } + ) + + assert inputs[main.INSTRUCTIONS_KEY] == ["Answer in French."] + assert [message.role for message in state.messages] == ["user"] + + +def test_the_model_s_words_in_a_step_that_called_tools_are_kept(): + """CrewAI keeps such a step with no content; its streamed words are what the person hears.""" + from types import SimpleNamespace + + from crewai.events.types.llm_events import LLMStreamChunkEvent + + tools = main._caller_tools([{"name": "read_record", "parameters": {"type": "object"}}], main.HandBack()) + agent = main._agent(tools) + + def chunk(text, call_id, agent_id=agent.id, tool_call=None): + return SimpleNamespace(agent_id=agent_id, call_id=call_id, chunk=text, tool_call=tool_call) + + words = main.StepWords(agent) + for event in [ + chunk("Thinking", "call-a"), + chunk("Ten records read", "call-b"), + chunk("; two are overdue.", "call-b"), + chunk('{"id"', "call-b", tool_call=object()), + chunk("Not this Agent's.", "call-c", agent_id="another"), + ]: + words.heard(None, event) + + assert words.last_said() == "Ten records read; two are overdue." + assert main.StepWords(agent).last_said() is None + # What the words are told apart by, on the event CrewAI sends. + assert {"call_id", "chunk", "tool_call", "agent_id"} <= set(LLMStreamChunkEvent.model_fields) + + +def test_gemini_s_own_signature_goes_out_on_the_call_and_comes_back_with_it(): + """CrewAI's Gemini client keeps Gemini's parts, signature included, beside the calls.""" + from google.genai import types + + signature = b"gemini-signature-1" + step = { + "role": "assistant", + "content": None, + "tool_calls": [ + {"id": "call-1", "type": "function", "function": {"name": "look_up_order", "arguments": "{}"}}, + ], + "raw_tool_call_parts": [ + types.Part( + function_call=types.FunctionCall(name="look_up_order", args={}), + thought_signature=signature, + ) + ], + } + [sealed] = main._thought_signatures(step) + assert sealed == base64.b64encode(signature).decode() + + # Back in the thread as the call's `encryptedValue`: Gemini gets its own signature, and a call + # with none (or one that is not base64) gets Google's placeholder. + back = main._message_dict( + { + "role": "assistant", + "content": None, + "tool_calls": [ + {**step["tool_calls"][0], "encrypted_value": sealed}, + {"id": "call-2", "type": "function", "function": {"name": "look_up_order", "arguments": "{}"}}, + {"id": "call-3", "type": "function", "function": {"name": "x", "arguments": "{}"}, "encryptedValue": "%%"}, + ], + } + ) + [shaped] = main._for_provider([back], "google") + assert [part.thought_signature for part in shaped["raw_tool_call_parts"]] == [ + signature, + main.GEMINI_UNSIGNED_CALL, + main.GEMINI_UNSIGNED_CALL, + ] + # Never sent as a field of its own, to Gemini or to anyone else. + for sent in (main._signed_calls([shaped], "gemini/gemini-3.8-flash"), main._signed_calls([back], "openai/gpt-5.5")): + assert all(main.SIGNATURE_KEY not in call for call in sent[0]["tool_calls"]) + + def test_session_messages_are_projected_to_provider_fields_without_mutating_state(): """What the Agent is given is what a strict provider accepts; the session keeps the rest.""" original_messages = [ diff --git a/agent-crewai/tests/test_progress_reminder.py b/agent-crewai/tests/test_progress_reminder.py index 6c5d0ee1cd..d17746c76e 100644 --- a/agent-crewai/tests/test_progress_reminder.py +++ b/agent-crewai/tests/test_progress_reminder.py @@ -210,7 +210,10 @@ def run_job(monkeypatch, provider, model, steps, lines=(), earlier=()): events = _events(response.text) assert not [event for event in events if event["type"] == "RUN_ERROR"], events streams.append(response.text) - thread = _thread_after(events, messages) + # The server drops its own instructions from the thread that comes back and writes them + # anew on every run; the conversational CrewAI Bot's snapshots leave them out already. + own = [m for m in messages if m["id"].startswith("standing-role:")] + thread = [*own, *(m for m in _thread_after(events, messages) if m not in own)] answered = {m.get("toolCallId") for m in thread if m["role"] == "tool"} pending = [ call for m in thread[len(messages):] if m["role"] == "assistant" @@ -233,7 +236,12 @@ def run_job(monkeypatch, provider, model, steps, lines=(), earlier=()): def _words(content): if isinstance(content, str): return content - return "".join(part.get("text") or "" for part in content or [] if isinstance(part, dict)) + # A text part's words, or an Anthropic tool result's, where this Bot puts the note. + return "".join( + part.get("text") or _words(part.get("content")) if part.get("type") == "tool_result" else part.get("text") or "" + for part in content or [] + if isinstance(part, dict) + ) def reminders_in(request): @@ -242,12 +250,18 @@ def reminders_in(request): def _follows(request, at, call_id): - """Whether the reminder at `at` comes right after call `call_id`'s result.""" + """Whether the reminder at `at` comes right after call `call_id`'s result. + + In the person's turn, CrewAI would take a note of its own for the turn's request, so this Bot + adds it to the latest result: in the turn that holds it, after its words. + """ message = request["messages"][at] if isinstance(message.get("content"), list): # Anthropic: the result and the note in one turn blocks = message["content"] results = [b for b in blocks if b.get("type") == "tool_result"] return results and results[-1]["tool_use_id"] == call_id and REMINDER in _words(blocks[-1:]) + if message.get("role") == "tool": # the note added to the result + return message.get("tool_call_id") == call_id previous = request["messages"][at - 1] return previous.get("role") == "tool" and previous.get("tool_call_id") == call_id @@ -318,12 +332,12 @@ def test_every_model_is_reminded_in_the_form_it_takes(monkeypatch, provider, mod assert len(reminders_in(request)) == 1 [at] = reminders_in(requests[5]) assert _follows(requests[5], at, "call_5") - expected = ( - {"role": "system", "content": REMINDER} - if form == "system" - else {"role": "user", "content": REMINDER_IN_TURN} - ) - assert requests[5]["messages"][at] == expected + if form == "system": + assert requests[5]["messages"][at] == {"role": "system", "content": REMINDER} + else: + # After the result's own words, in the result it follows. + message = requests[5]["messages"][at] + assert message["role"] == "tool" and message["content"].endswith("\n\n" + REMINDER_IN_TURN) assert_never_shown(streams) diff --git a/docs/agent-frameworks.md b/docs/agent-frameworks.md index 0bc0126366..ead0db5daf 100644 --- a/docs/agent-frameworks.md +++ b/docs/agent-frameworks.md @@ -293,6 +293,21 @@ messages for the Agent and turns OpenBot's tools into tools that hand the call b each message's id. Start from that file and give the Agent your own role, goal and tools. Tools you add run in your process as usual. +Handing a call back needs a few more things that the file also does: + +- **The tool's name.** CrewAI shows the model `sanitize_tool_name(name)`, so `showBarChart` reaches + it as `show_bar_chart`, and the model calls it by that. The call goes back under the server's name. +- **Its arguments.** CrewAI offers tools in strict mode, where every optional property is required + and nullable. The `null`s the tool's own schema did not allow are taken out of the handed-back call. +- **The words with it.** CrewAI keeps a step that called tools with no content. The words the model + streamed in that step are the reply's content, so a line on a long job reaches the person. +- **The client.** Name the provider (`LLM(model=..., provider="openai")`). Given `openai/`, + CrewAI sends a model it has not heard of (a Gemini model on a gateway, `qwen/qwen3-8b` on a local + server) to LiteLLM, which offers it no tools at all. + +A `developer` message is an instruction too: ag-ui-crewai seeds it into the session, whose messages +have no such role, so the state's validator leaves it out there. + ## Claude Agent SDK `ag-ui-claude-sdk` sends Claude only the last message of a run, so the system messages never reach From 3e4df57cf6bb25e5a2a8ec8e4600d779f6d085fb Mon Sep 17 00:00:00 2001 From: lorenzejay Date: Wed, 2 Dec 2026 09:34:29 -0800 Subject: [PATCH 5/7] CrewAI Bot: offer the caller's tools as written, pin CrewAI and ag-ui-crewai Review on #2636: - Tools are offered with the caller's own schema and strict mode off, as the Bot on main does. Strict mode closed every open-ended object, so an artifact's content and a patch's value could only be sent {}. Unsupported formats are left out and tuple-style items become one schema. - No Pydantic model is built from a caller's schema, so a format: email field (manage_people) or tuple-style items no longer fails every run. - crewai==1.15.47 and ag-ui-crewai==1.0.0, pinned; a test checks the private parts the Bot relies on are still there. - A call CrewAI matched by its sanitized name is handed back, and a turn that ran a caller's tool never replies with the stand-in's text. - Numbered tool names stay within 64 characters. - System messages from the middle of a thread stay in place. - The httpx hook reads a body only when the chosen model is a Gemini model that checks signatures. - CrewAI's console panels are quiet; errors and the trace link still log. - A Responses-only model (gpt-5.3-codex) moves to the Responses API with OpenAI's current 404 wording. - docs: read main.py as a reference, not a file to start from. --- agent-crewai/requirements.txt | 17 +- agent-crewai/src/main.py | 243 +++++++++++++++++++--- agent-crewai/tests/test_main.py | 345 +++++++++++++++++++++++++++++++- docs/agent-frameworks.md | 18 +- 4 files changed, 577 insertions(+), 46 deletions(-) diff --git a/agent-crewai/requirements.txt b/agent-crewai/requirements.txt index 58e75df500..7d20e55b68 100644 --- a/agent-crewai/requirements.txt +++ b/agent-crewai/requirements.txt @@ -1,12 +1,17 @@ -# The Bot is a conversational CrewAI Agent (`Agent(conversational=True)`'s Flow session), which -# CrewAI shipped in 1.15.45, and ag-ui-crewai serves it with `conversational=True`, which 1.0.0 has. -# Floors, not pins: CI installs these the way the image does, so a new release upstream is tested -# before it ships. +# The Bot is a conversational CrewAI Agent (`Agent(conversational=True)`'s Flow session), served by +# ag-ui-crewai's `conversational=True`. Pinned, not floors: `src/main.py` relies on parts of both +# that neither publishes (the Flow session's `_conversation_streaming_enabled`, +# `_emit_conversation_message_added`, `_assistant_reply_appended`, `_standalone_agent` and +# `_skip_auto_memory`; how CrewAI builds and sends tool schemas, and when it moves a model to the +# Responses API; ag-ui-crewai's `crewai_prepare_inputs` and `is_backend_tool_event`). A rename +# upstream would post a reply twice or start CrewAI's memory, which embeds with OpenAI by default. +# An upgrade is a change to this file, so CI runs it (`tests/test_main.py` checks each of those +# parts is still there) before it ships. # # The extras are CrewAI's own clients for the providers OpenBot offers. CrewAI calls a model it # knows through the provider's SDK and refuses to start without it, even with LiteLLM installed. -crewai[anthropic,google-genai]>=1.15.45 -ag-ui-crewai>=1.0.0 +crewai[anthropic,google-genai]==1.15.47 +ag-ui-crewai==1.0.0 uvicorn[standard] # litellm 1.106.0 imports `CacheableResult` from `mcp.types`, which exists only in mcp 2.x, while # ag-ui-crewai 1.0.0 requires mcp<2. The two cannot both be satisfied, so every CrewAI run failed diff --git a/agent-crewai/src/main.py b/agent-crewai/src/main.py index dd9f4433a4..f219a89f6f 100644 --- a/agent-crewai/src/main.py +++ b/agent-crewai/src/main.py @@ -12,7 +12,8 @@ - THE BOT'S ROLE. The server sends its instructions as system messages, and the conversational path drops system messages before the Flow sees them. They are kept aside here and given to the - Agent as system messages, right after CrewAI's own system prompt. + Agent as system messages where they were in the thread: the role right after CrewAI's own system + prompt, a note from the middle of the thread after the turn it followed. - THE WHOLE THREAD, EVERY RUN. A CrewAI session keeps its history in memory; OpenBot's server sends the whole thread on every run, and a fresh process must answer from it. ag-ui-crewai seeds the session from the run's messages, and the Agent is built anew for each turn, so nothing @@ -102,6 +103,9 @@ def _taken_signature(call_id: Any) -> str | None: def _asks_gemini(request: httpx.Request) -> bool: if request.method.upper() != "POST" or not request.url.path.endswith("/chat/completions"): return False + # The model OpenBot chose first, so a Bot on any other model never has a request body read. + if not gemini_signatures.checks_signatures(_model()): + return False try: body = json.loads(request.content) except Exception: # A streamed or unreadable body, which no model call sends. @@ -174,23 +178,33 @@ async def _asend(self, request, *args, **kwargs): from crewai import LLM, Agent from crewai.agent.conversation import AgentConversationState from crewai.events.event_bus import crewai_event_bus +from crewai.events.event_listener import event_listener from crewai.events.types.llm_events import LLMStreamChunkEvent from crewai.flow import ConversationConfig, Flow, listen from crewai.flow.conversational import ConversationMessage +from crewai.llms.providers.openai.completion import OpenAICompletion from crewai.tools import BaseTool -from crewai.utilities.pydantic_schema_utils import create_model_from_schema +from crewai.utilities import agent_utils +from crewai.utilities.pydantic_schema_utils import strip_unsupported_formats from crewai.utilities.string_utils import sanitize_tool_name from fastapi import FastAPI, Request from fastapi.responses import JSONResponse from pydantic import ( BaseModel, + ConfigDict, Field, PrivateAttr, SerializerFunctionWrapHandler, + create_model, field_serializer, field_validator, ) +# CrewAI draws a console panel for every Flow and Agent it starts and finishes, which here is every +# run: the Bot's log was those panels and little else. Their console is quiet. Errors are logged, +# not drawn, and the trace link (with tracing on) is written on its own, so both still reach it. +event_listener.formatter.console.quiet = True + # The one header OpenBot's server sends when it calls a managed Bot. Same name the TypeScript Bots # check, because a Bot is a Bot whatever it is written in. TOKEN_HEADER = "x-openbot-agent-token" @@ -308,7 +322,8 @@ def _openbot_prepare_crewai_inputs( The conversational path seeds the session with the run's messages less every system message, and the server's are the Bot's role and the guidance for the tools it holds. They are kept - under a key of their own here, in order, and the turn hands them to the Agent. + under a key of their own here, in order, each with the id of the turn it came after (`None` + for those ahead of the first), and the turn puts each back where it was (`_with_instructions`). """ inputs = _prepare_crewai_inputs( state=state, @@ -317,12 +332,14 @@ def _openbot_prepare_crewai_inputs( context=context, forwarded_props=forwarded_props, ) - inputs[INSTRUCTIONS_KEY] = [ - text - for message in messages - if getattr(message, "role", None) in ("system", "developer") - and (text := _text(getattr(message, "content", None)).strip()) - ] + instructions: list[dict[str, Any]] = [] + after: str | None = None + for message in messages: + if getattr(message, "role", None) not in ("system", "developer"): + after = getattr(message, "id", None) + elif text := _text(getattr(message, "content", None)).strip(): + instructions.append({"after": after, "content": text}) + inputs[INSTRUCTIONS_KEY] = instructions inputs[CALLER_TOOLS_KEY] = [tool.model_dump() for tool in tools] return inputs @@ -364,7 +381,9 @@ def calls(self, messages: list[Any], tools: list[CallerTool]) -> list[dict[str, handed_back = [] for index, call in enumerate(step.get("tool_calls") or []): function = call.get("function") or {} - tool = by_name.get(function.get("name")) + name = function.get("name") + # CrewAI finds the tool a model calls `showNote` by its sanitized name, and runs it. + tool = by_name.get(name) or (by_name.get(sanitize_tool_name(name)) if isinstance(name, str) else None) if tool is None: continue handed = { @@ -483,8 +502,8 @@ def _allows_null(schema: Any) -> bool: def _without_unasked_nulls(value: Any, schema: Any) -> Any: """`value` without the `null`s the tool's own schema did not ask for, at any depth. - CrewAI offers the model every tool in strict mode, which makes each optional property required - and nullable: the model has to send `"limit": null` for a limit it means to leave out. The tool + A model that learned strict mode's habit, or a provider that still applies it, sends + `"limit": null` for a limit it means to leave out. The tool is the caller's, and its schema said the property is optional, not that it may be `null`, so a caller that checks arguments against it refuses the call. Only a property the schema does not require is dropped; a required one the model left `null` is passed on as it said it. @@ -506,6 +525,35 @@ def _without_unasked_nulls(value: Any, schema: Any) -> Any: return value +def _offered_schema(schema: Any) -> Any: + """`schema` with every tuple-style `items` (a list) as one schema, at any depth. + + JSON Schema's 2020 form of a tuple is `prefixItems`; the older list form is refused by the + providers that read the newer one. The array keeps its length, and each item is any of the + schemas given for a place, which the caller still checks the call against. + """ + if isinstance(schema, list): + return [_offered_schema(item) for item in schema] + if not isinstance(schema, dict): + return schema + offered = {key: _offered_schema(value) for key, value in schema.items()} + items = offered.get("items") + if isinstance(items, list): + places = [item for item in items if isinstance(item, dict)] + distinct = [place for index, place in enumerate(places) if place not in places[:index]] + offered["items"] = distinct[0] if len(distinct) == 1 else {"anyOf": distinct} if distinct else {} + offered.setdefault("minItems", len(items)) + if offered.get("additionalItems") is False: + offered.setdefault("maxItems", len(items)) + offered.pop("additionalItems", None) + return offered + + +# What the stand-in "runs" a caller's tool to. Never the person's reply: a turn whose tools were +# handed back replies with the calls (`OpenBotAgentFlow.converse_turn`). +HANDED_BACK = "Handed to the caller to run." + + class CallerTool(BaseTool): """An AG-UI tool, as a CrewAI tool that is not run here. @@ -527,7 +575,19 @@ def __init__(self, *, hand_back: HandBack, **data: Any) -> None: def _run(self, **arguments: Any) -> str: self._hand_back.record(self.caller_name) - return "Handed to the caller to run." + return HANDED_BACK + + def offered_parameters(self) -> dict[str, Any]: + """The schema the model is offered: the caller's own, in what every provider reads. + + Not CrewAI's strict form of it. Strict mode closes every object, so an open-ended one (an + artifact's `content`, a patch's `value`, a map of headers) could only ever be sent `{}`. + Like the Bot before it, this one offers the schema as the caller wrote it, with two changes + a provider would otherwise refuse: a `format` other than a date or time (`email`, `uri`) + is left out, and an array's `items` given as a list, one schema per place, is one schema + any of them matches. + """ + return _offered_schema(strip_unsupported_formats(deepcopy(self.caller_parameters))) def arguments_for_caller(self, arguments: Any) -> str: """The model's arguments as the caller's schema asks for them, as JSON text. @@ -546,6 +606,95 @@ def arguments_for_caller(self, arguments: Any) -> str: return json.dumps(kept) +# What CrewAI checks a caller's tool's arguments against before the stand-in runs: nothing. The +# caller checks them, against its own schema, when it runs the tool. Building a model from that +# schema instead (`create_model_from_schema`) failed the whole run on a `format: email` field, which +# needs a package the image does not install, and on tuple-style `items`. +_ANY_ARGUMENTS = ConfigDict(extra="allow") + + +def _offered_as_written( + tools: list[dict[str, Any]], tool_name_mapping: dict[str, Any] +) -> list[dict[str, Any]]: + """CrewAI's tool schemas, with each caller's tool offered as written and not in strict mode.""" + for offered in tools: + function = offered.get("function") or {} + tool = tool_name_mapping.get(function.get("name")) + if isinstance(tool, CallerTool): + function["parameters"] = tool.offered_parameters() + function["strict"] = False + return tools + + +# CrewAI turns an Agent's tools into the schemas it sends (`convert_tools_to_openai_schema`), each +# in strict mode, and every provider client reads them from there. Anthropic's and LiteLLM's keep a +# tool's `strict: False`, and Gemini's sends the schema as it is given. OpenAI's own client sets +# strict mode again on Chat Completions and leaves it to the API's default, which is strict, on the +# Responses API; for a tool offered with `strict: False` both send it as it was offered. +_convert_tools = agent_utils.convert_tools_to_openai_schema + + +def _convert_tools_offering_callers_as_written(tools: Any) -> Any: + schemas, functions, tool_name_mapping = _convert_tools(tools) + return _offered_as_written(schemas, tool_name_mapping), functions, tool_name_mapping + + +agent_utils.convert_tools_to_openai_schema = _convert_tools_offering_callers_as_written + +_openai_chat_tools = OpenAICompletion._convert_tools_for_interference +_openai_responses_tools = OpenAICompletion._convert_tools_for_responses + + +def _not_strict(given: dict[str, Any]) -> dict[str, Any] | None: + """The function of a tool CrewAI was given with `strict: False`, or None.""" + function = given.get("function") if isinstance(given, dict) else None + return function if isinstance(function, dict) and function.get("strict") is False else None + + +def _chat_tools(self: OpenAICompletion, tools: list[dict[str, Any]]) -> list[dict[str, Any]]: + sent = _openai_chat_tools(self, tools) + for given, tool in zip(tools, sent): + if (function := _not_strict(given)) is not None: + tool["function"]["strict"] = False + tool["function"]["parameters"] = deepcopy(function.get("parameters") or {}) + return sent + + +def _responses_tools(self: OpenAICompletion, tools: list[dict[str, Any]]) -> list[dict[str, Any]]: + sent = _openai_responses_tools(self, tools) + for given, tool in zip(tools, sent): + if _not_strict(given) is not None: + tool["strict"] = False + return sent + + +OpenAICompletion._convert_tools_for_interference = _chat_tools # type: ignore[method-assign] +OpenAICompletion._convert_tools_for_responses = _responses_tools # type: ignore[method-assign] + + +# A model OpenAI serves only on the Responses API (`gpt-5.3-codex`) is refused on Chat Completions +# with a 404, and CrewAI then sends it to the Responses API, but only when the refusal reads "only +# supported in v1/responses". OpenAI now words it "not supported in the v1/chat/completions +# endpoint. Use the v1/responses endpoint instead.", so every run on such a model failed. A 404 +# that names the Responses API counts too; one that says the model does not exist still does not. +_responses_only_error = OpenAICompletion._is_responses_only_error + + +def _names_the_responses_api(error: BaseException) -> bool: + if _responses_only_error(error): + return True + from openai import NotFoundError + + body = getattr(error, "body", None) + inner = body.get("error") if isinstance(body, dict) else None + if not isinstance(error, NotFoundError) or (isinstance(inner, dict) and inner.get("code") == "model_not_found"): + return False + return "use the v1/responses endpoint" in str(getattr(error, "message", "") or error).lower() + + +OpenAICompletion._is_responses_only_error = staticmethod(_names_the_responses_api) # type: ignore[method-assign] + + # CrewAI reports every tool it runs, and ag-ui-crewai turns that report into a tool call with its # result. For a caller's tool that is a call already "answered" (by the stand-in above), under an id # the model never made, next to the real one the turn hands back: the server would store a phantom @@ -591,7 +740,8 @@ def _caller_tools(tools: list[dict[str, Any]], hand_back: HandBack) -> list[Call `show_bar_chart`, `mcp__acme-wiki__search` as `mcp_acme_wiki_search`), and the model calls it by that. Named so here already, the name the model calls, the name CrewAI reports and the name the turn hands back by are one name; the server's own stays in `caller_name`. Two tools whose names - come out the same get a number, as CrewAI would number them. + come out the same get a number, as CrewAI would number them, within the 64 characters a + provider takes. """ built: list[CallerTool] = [] shown: set[str] = set() @@ -603,7 +753,7 @@ def _caller_tools(tools: list[dict[str, Any]], hand_back: HandBack) -> list[Call number = 1 while model_name in shown: number += 1 - model_name = f"{base}_{number}" + model_name = sanitize_tool_name(f"{base}_{number}") shown.add(model_name) parameters = tool.get("parameters") or {"type": "object", "properties": {}} built.append( @@ -613,9 +763,7 @@ def _caller_tools(tools: list[dict[str, Any]], hand_back: HandBack) -> list[Call caller_name=name, caller_parameters=parameters, description=tool.get("description") or name, - args_schema=create_model_from_schema( - {"title": f"{model_name}_arguments", **parameters} - ), + args_schema=create_model(f"{model_name}_arguments", __config__=_ANY_ARGUMENTS), ) ) return built @@ -690,7 +838,9 @@ class OpenBotConversationMessage(ConversationMessage): class OpenBotConversationState(AgentConversationState): messages: list[OpenBotConversationMessage] = Field(default_factory=list) - openbot_instructions: list[str] = Field(default_factory=list) + # Each system or developer message of the run: {"after": the id of the turn before it, or None, + # "content": its text}. + openbot_instructions: list[dict[str, Any]] = Field(default_factory=list) openbot_caller_tools: list[dict[str, Any]] = Field(default_factory=list) @field_validator("messages", mode="before") @@ -939,6 +1089,38 @@ def _signed_calls(conversation: list[dict[str, Any]], model: str) -> list[dict[s return signed +def _with_instructions( + messages: list[Any], instructions: list[dict[str, Any]] +) -> list[dict[str, Any]]: + """The session's turns as CrewAI's `kickoff` takes them, each instruction back in its place. + + The run's system and developer messages wait beside the session (`INSTRUCTIONS_KEY`), each + with the id of the turn it came after. One that led the thread leads it again; one from its + middle, a note the server added between two turns, follows the turn it followed, not the role. + One whose turn the session does not have (the turn CrewAI added without an id) follows the + last of the instructions that lead, as before. + """ + system = lambda instruction: {"role": "system", "content": instruction["content"]} # noqa: E731 + by_turn: dict[str, list[dict[str, Any]]] = {} + for instruction in instructions: + if instruction.get("after"): + by_turn.setdefault(instruction["after"], []).append(instruction) + placed: list[dict[str, Any]] = [] + for message in messages: + turn = _message_dict(message) + if turn is not None: + placed.append(turn) + turn_id = message.get("id") if isinstance(message, dict) else getattr(message, "id", None) + placed.extend(system(instruction) for instruction in by_turn.pop(turn_id, []) if turn_id) + unplaced = {id(instruction) for waiting in by_turn.values() for instruction in waiting} + leading = [ + system(instruction) + for instruction in instructions + if not instruction.get("after") or id(instruction) in unplaced + ] + return [*leading, *placed] + + def _agent(tools: list[CallerTool]) -> Agent: """The Bot, as a CrewAI Agent, for one turn. @@ -977,15 +1159,8 @@ def route_turn(self, context: dict[str, Any]) -> str: @listen("converse") async def converse_turn(self): - instructions = [ - {"role": "system", "content": text} for text in self.state.openbot_instructions - ] - conversation = [ - message - for message in map(_message_dict, self.state.messages) - if message is not None - ] - if not conversation: + conversation = _with_instructions(self.state.messages, self.state.openbot_instructions) + if not any(message.get("role") != "system" for message in conversation): raise ValueError("A turn needs at least one message") model = _model() # Each step with only the words the model said (shared/empty_turns.py), and after five @@ -1005,9 +1180,9 @@ async def converse_turn(self): _handing_back(agent, tools), _listening(agent) as words, ): - # CrewAI keeps every message before the newest user message as history, with its - # role, after its own system prompt: the server's instructions lead it. - result = await agent.kickoff_async(messages=[*instructions, *conversation]) + # CrewAI keeps every message but the newest user message as history, with its role and + # in its place, after its own system prompt: the server's instructions lead it. + result = await agent.kickoff_async(messages=conversation) calls = hand_back.calls(result.messages, tools) if calls: # The turn's reply asks the caller to run its tools, and the run ends there. With the @@ -1016,6 +1191,12 @@ async def converse_turn(self): said = _text(_calling_step(result.messages).get("content")).strip() or words.last_said() self._reply(said, tool_calls=calls) return None + if hand_back.names: + # A caller's tool ran, so the turn's answer is the stand-in's, and no call it made could + # be matched to a tool to hand back. The run fails rather than tell the person that. + raise RuntimeError( + f"The model called {', '.join(hand_back.names)}, and the call could not be handed back" + ) self._reply(result.raw) return result diff --git a/agent-crewai/tests/test_main.py b/agent-crewai/tests/test_main.py index a887411d78..0c19b48e95 100644 --- a/agent-crewai/tests/test_main.py +++ b/agent-crewai/tests/test_main.py @@ -149,6 +149,264 @@ def test_a_tool_whose_name_crewai_changes_is_handed_back_under_the_servers_name( ] +# The schemas OpenBot's own tools are sent with (zod's `toJSONSchema`, descriptions shortened): +# an artifact's `content` and a patch's `value` take any JSON, and an email field is marked so. +ARTIFACT_CREATE = { + "name": "artifact_create", + "description": "Make an artifact.", + "parameters": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "kind": {"type": "string", "enum": ["document", "slides", "dashboard"]}, + "title": {"type": "string", "minLength": 1, "maxLength": 200}, + "content": { + "type": "object", + "propertyNames": {"type": "string"}, + "additionalProperties": {}, + "description": "The artifact's content, as its kind's own JSON document.", + }, + }, + "required": ["kind", "title", "content"], + }, +} +ARTIFACT_PATCH = { + "name": "artifact_patch", + "description": "Change values inside an artifact with JSON Patch.", + "parameters": { + "$schema": "https://json-schema.org/draft/2020-12/schema", + "type": "object", + "properties": { + "id": {"type": "string", "minLength": 1, "maxLength": 64}, + "if_version": {"type": "integer", "minimum": 1}, + "operations": { + "minItems": 1, + "type": "array", + "items": { + "type": "object", + "properties": { + "op": {"type": "string", "enum": ["add", "remove", "replace"]}, + "path": {"type": "string"}, + "value": {"description": "For add, replace and test, the value."}, + }, + "required": ["op", "path"], + }, + }, + }, + "required": ["id", "if_version", "operations"], + }, +} +MANAGE_PEOPLE = { + "name": "manage_people", + "description": "Invite or remove a person.", + "parameters": { + "type": "object", + "properties": { + "action": {"type": "string", "enum": ["invite", "remove"]}, + "email": {"type": "string", "format": "email"}, + }, + "required": ["action", "email"], + }, +} +PLACE_PIN = { + "name": "place_pin", + "description": "Pin a place on the map.", + "parameters": { + "type": "object", + "properties": { + "point": {"type": "array", "items": [{"type": "number"}, {"type": "number"}], "additionalItems": False}, + "headers": {"type": "object", "additionalProperties": {"type": "string"}}, + }, + "required": ["point"], + }, +} +CALLER_SCHEMA_TOOLS = [ARTIFACT_CREATE, ARTIFACT_PATCH, MANAGE_PEOPLE, PLACE_PIN] + + +def assert_offered_as_written(by_name): + """What the model is offered for each tool: open where the caller left it open, and readable.""" + content = by_name["artifact_create"]["properties"]["content"] + assert content.get("additionalProperties") != False and "properties" not in content + operation = by_name["artifact_patch"]["properties"]["operations"]["items"] + assert operation["properties"]["value"] == {"description": "For add, replace and test, the value."} + assert operation["required"] == ["op", "path"] + assert by_name["manage_people"]["properties"]["email"] == {"type": "string"} + point = by_name["place_pin"]["properties"]["point"] + assert point == {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2} + assert by_name["place_pin"]["properties"]["headers"]["additionalProperties"] == {"type": "string"} + + +@pytest.mark.parametrize( + ("provider", "model", "api"), + [ + ("openai", "gpt-5.5", "completions"), + # A Responses-only model (`o3-pro`, the `-pro` models): CrewAI moves to the Responses API + # when Chat Completions refuses the model. + ("openai", "o3-pro", "responses"), + ("anthropic", "claude-sonnet-5-5", None), + ("google", "gemini-3.8-flash", None), + ], +) +def test_a_callers_tools_are_offered_as_written_and_not_in_strict_mode(monkeypatch, provider, model, api): + """Strict mode closes every object: an artifact's content could only ever be `{}`.""" + from crewai.utilities.agent_utils import setup_native_tools + + monkeypatch.setenv("BOT_PROVIDER", provider) + monkeypatch.setenv("BOT_MODEL", model) + for key in ("OPENAI_API_KEY", "ANTHROPIC_API_KEY", "GOOGLE_API_KEY"): + monkeypatch.setenv(key, "test-key") + # Building the tools no longer fails on `format: email` (a package the image lacks) or a list + # of `items`. + tools = main._caller_tools(CALLER_SCHEMA_TOOLS, main.HandBack()) + schemas, _, _ = setup_native_tools(tools) + llm = main._llm() + + if api == "responses": + sent = llm._convert_tools_for_responses(schemas) + assert all(tool["strict"] is False for tool in sent) + offered = {tool["name"]: tool["parameters"] for tool in sent} + elif provider == "openai": + sent = llm._convert_tools_for_interference(schemas) + assert all(tool["function"]["strict"] is False for tool in sent) + offered = {tool["function"]["name"]: tool["function"]["parameters"] for tool in sent} + elif provider == "anthropic": + sent = llm._convert_tools_for_interference(schemas) + assert all("strict" not in tool for tool in sent) + offered = {tool["name"]: tool["input_schema"] for tool in sent} + else: + sent = llm._convert_tools_for_interference(schemas) + offered = { + tool.function_declarations[0].name: tool.function_declarations[0].parameters_json_schema + for tool in sent + } + assert_offered_as_written(offered) + + +@pytest.mark.parametrize( + ("message", "code", "moves"), + [ + # OpenAI's wording now, for `gpt-5.3-codex`. + ( + "This model is not supported in the v1/chat/completions endpoint. Use the v1/responses endpoint instead.", + None, + True, + ), + # The wording CrewAI already knew. + ("This model is only supported in v1/responses and not in v1/chat/completions.", None, True), + # A model that does not exist stays an error. + ("The model `gpt-9` does not exist. Use the v1/responses endpoint instead.", "model_not_found", False), + ], +) +def test_a_model_openai_serves_only_on_the_responses_api_is_moved_there(message, code, moves): + from openai import NotFoundError + + request = httpx.Request("POST", "https://api.openai.com/v1/chat/completions") + error = NotFoundError( + message, + response=httpx.Response(404, request=request), + body={"error": {"message": message, "type": "invalid_request_error", "param": "model", "code": code}}, + ) + + assert main.OpenAICompletion._is_responses_only_error(error) is moves + + +def test_crewais_own_tools_keep_strict_mode(): + """Only a caller's tool is offered as written; a tool a person adds to this file is not.""" + from crewai.tools import BaseTool + from crewai.utilities.agent_utils import setup_native_tools + + class LookUp(BaseTool): + name: str = "look_up" + description: str = "Look a word up." + + def _run(self, word: str) -> str: + return word + + [schema], _, _ = setup_native_tools([LookUp()]) + assert schema["function"]["strict"] is True + assert schema["function"]["parameters"]["additionalProperties"] is False + + +def test_numbered_tool_names_stay_within_what_a_provider_takes(): + """Two long names that come out the same: the second's number keeps it under 64 characters.""" + long = "mcp__" + "a" * 70 + tools = main._caller_tools( + [{"name": long}, {"name": long.replace("__", "--")}, {"name": long + "!"}], main.HandBack() + ) + names = [tool.name for tool in tools] + assert len(set(names)) == 3 + assert all(len(name) <= 64 for name in names) + + +def test_a_call_crewai_matched_by_its_sanitized_name_is_still_handed_back(): + """The model may call `showNote` by the server's name; CrewAI runs `show_note` for it.""" + hand_back = main.HandBack() + tools = main._caller_tools([{"name": "showNote"}], hand_back) + tools[0]._run() + step = { + "role": "assistant", + "content": None, + "tool_calls": [{"id": "call-1", "type": "function", "function": {"name": "showNote", "arguments": "{}"}}], + } + + [call] = hand_back.calls([step], tools) + + assert (call["id"], call["function"]["name"]) == ("call-1", "showNote") + + +def test_a_turn_that_ran_a_callers_tool_never_replies_with_the_stand_in(monkeypatch): + """When no call can be matched, the run fails rather than say "Handed to the caller to run.".""" + import asyncio + from types import SimpleNamespace + + monkeypatch.setenv("OPENAI_API_KEY", "test-key") + flow = main.OpenBotAgentFlow() + flow.state.messages.append(main.OpenBotConversationMessage(id="u1", role="user", content="Hi")) + flow.state.openbot_caller_tools = [{"name": "showNote"}] + replies = [] + monkeypatch.setattr(flow, "_reply", lambda content, **fields: replies.append(content)) + + async def kickoff_async(self, messages): + for tool in self.tools: + tool._run() + step = {"role": "assistant", "content": None, "tool_calls": [ + {"id": "call-1", "type": "function", "function": {"name": "unknown_tool", "arguments": "{}"}} + ]} + return SimpleNamespace(messages=[step], raw=main.HANDED_BACK) + + monkeypatch.setattr(main.Agent, "kickoff_async", kickoff_async) + + with pytest.raises(RuntimeError, match="could not be handed back"): + asyncio.run(flow.converse_turn()) + assert replies == [] + + +def test_the_parts_of_crewai_and_ag_ui_crewai_this_bot_relies_on_are_there(): + """They are not published, so an upgrade that renames one fails here, not in a live run.""" + import inspect + + import crewai.events.event_listener as event_listener + import crewai.flow.conversational_mixin as conversational_mixin + import crewai.flow.runtime as flow_runtime + from crewai.utilities import agent_utils + + for name in ("_conversation_streaming_enabled", "_emit_conversation_message_added"): + assert callable(getattr(main.OpenBotAgentFlow, name, None)), name + # Each flag, where CrewAI reads it: a reply already appended, a standalone Agent's events, and + # no memory for a Flow that sets it. + for module, name in ( + (conversational_mixin, "self._assistant_reply_appended"), + (event_listener, 'getattr(source, "_standalone_agent", False)'), + (flow_runtime, 'getattr(self, "_skip_auto_memory", False)'), + ): + assert name in inspect.getsource(module), name + # CrewAI still builds an Agent's tool schemas through the module's own name, which main replaces. + assert "convert_tools_to_openai_schema" in agent_utils.setup_native_tools.__code__.co_names + assert agent_utils.convert_tools_to_openai_schema.__name__ == "_convert_tools_offering_callers_as_written" + for name in ("crewai_prepare_inputs", "is_backend_tool_event"): + assert hasattr(main.crewai_endpoint, name), name + + def test_crewais_report_of_a_renamed_caller_tool_is_not_passed_on(): """CrewAI reports a tool by the name the model called; a caller's tool is never reported.""" from types import SimpleNamespace @@ -231,7 +489,7 @@ def test_a_developer_message_is_an_instruction_and_not_a_turn_of_the_session(): } ) - assert inputs[main.INSTRUCTIONS_KEY] == ["Answer in French."] + assert inputs[main.INSTRUCTIONS_KEY] == [{"after": None, "content": "Answer in French."}] assert [message.role for message in state.messages] == ["user"] @@ -395,16 +653,50 @@ def test_every_system_message_of_the_run_is_kept_for_the_agent(): SystemMessage(id="standing-role:bot", role="system", content="You are Ada."), SystemMessage(id="granted-tools:bot", role="system", content="You hold: notes."), UserMessage(id="u1", role="user", content="Hello"), + SystemMessage(id="note-1", role="system", content="The person is away until Monday."), + UserMessage(id="u2", role="user", content="Any news?"), ], tools=[], context=[], forwarded_props={}, ) - assert inputs[main.INSTRUCTIONS_KEY] == ["You are Ada.", "You hold: notes."] + assert inputs[main.INSTRUCTIONS_KEY] == [ + {"after": None, "content": "You are Ada."}, + {"after": None, "content": "You hold: notes."}, + {"after": "u1", "content": "The person is away until Monday."}, + ] assert inputs[main.CALLER_TOOLS_KEY] == [] +def test_a_system_message_from_the_middle_of_the_thread_stays_where_it_was(): + """The role leads; a note the server added between two turns follows the turn it followed.""" + messages = [ + {"id": "u1", "role": "user", "content": "Hello"}, + {"id": "a1", "role": "assistant", "content": "Hi."}, + {"id": "u2", "role": "user", "content": "Any news?"}, + # The turn CrewAI appends itself carries no id. + {"role": "user", "content": "And the plan?"}, + ] + instructions = [ + {"after": None, "content": "You are Ada."}, + {"after": "a1", "content": "The person is away until Monday."}, + {"after": "not-in-the-session", "content": "You hold: notes."}, + ] + + placed = main._with_instructions(messages, instructions) + + assert [(m["role"], m["content"]) for m in placed] == [ + ("system", "You are Ada."), + ("system", "You hold: notes."), + ("user", "Hello"), + ("assistant", "Hi."), + ("system", "The person is away until Monday."), + ("user", "Any news?"), + ("user", "And the plan?"), + ] + + def test_tool_results_name_the_tool_they_answer(): """Gemini refuses a function response without the function's name; AG-UI sends only the id.""" conversation = [ @@ -777,6 +1069,8 @@ def run_loopback_proof(proof_case, output): "blank-model": ("openai", " ", "openai/gpt-5.5", "gpt-5.5"), "strict-projection": ("openai", "gpt-4o", "openai/gpt-4o", "gpt-4o"), "caller-tool": ("openai", "gpt-4o", "openai/gpt-4o", "gpt-4o"), + "caller-schemas": ("openai", "gpt-4o", "openai/gpt-4o", "gpt-4o"), + "system-in-place": ("openai", "gpt-4o", "openai/gpt-4o", "gpt-4o"), "namespaced-model": ( "openai", "qwen/qwen3-8b", @@ -809,9 +1103,15 @@ def run_loopback_proof(proof_case, output): **run_input( strict_projection_messages() if proof_case == "strict-projection" + else mid_thread_system_messages() + if proof_case == "system-in-place" else basic_messages() ), - "tools": [show_note_agui_tool()] if proof_case == "caller-tool" else [], + "tools": [show_note_agui_tool()] + if proof_case == "caller-tool" + else CALLER_SCHEMA_TOOLS + if proof_case == "caller-schemas" + else [], }, ) if proof_case == "caller-tool": @@ -942,6 +1242,22 @@ def run_loopback_proof(proof_case, output): }, ], result assert result["messagesSnapshots"][-1][-1]["toolCalls"][0]["id"] == "call_show_note_1" + elif proof_case == "caller-schemas": + # The run answers (before, building the tools failed it), and each tool is offered as the + # caller wrote it, not in strict mode. + assert all(tool["function"]["strict"] is False for tool in records[0]["tools"]), result + assert_offered_as_written( + {tool["function"]["name"]: tool["function"]["parameters"] for tool in records[0]["tools"]} + ) + elif proof_case == "system-in-place": + assert [(m["role"], m.get("content")) for m in records[0]["messages"][1:]] == [ + ("system", "You are Ada, a Bot-specific finance analyst."), + ("user", "What should I review first?"), + ("assistant", "The ledger."), + ("system", "The ledger was closed at noon."), + # The newest, as CrewAI makes it the turn's request. + ("user", "\nCurrent Task: And after that?\n\nProvide your complete response:"), + ], result elif proof_case == "strict-projection": assert_provider_messages_are_projected(records[0]["messages"]) # The picture reaches the model, just before the question CrewAI makes the request. @@ -1027,6 +1343,15 @@ def basic_messages(): ] +def mid_thread_system_messages(): + return [ + *basic_messages(), + {"id": "assistant-1", "role": "assistant", "content": "The ledger."}, + {"id": "note-1", "role": "system", "content": "The ledger was closed at noon."}, + {"id": "user-2", "role": "user", "content": "And after that?"}, + ] + + def strict_projection_messages(): return [ basic_messages()[0], @@ -1099,7 +1424,15 @@ def assert_provider_messages_are_projected(messages): @pytest.mark.parametrize( "proof_case", - ["blank-provider", "blank-model", "strict-projection", "namespaced-model", "gateway-model"], + [ + "blank-provider", + "blank-model", + "strict-projection", + "namespaced-model", + "gateway-model", + "caller-schemas", + "system-in-place", + ], ) def test_crewai_endpoint_uses_normalized_model_with_real_provider_loopback( tmp_path, proof_case @@ -1119,6 +1452,8 @@ def test_crewai_endpoint_uses_normalized_model_with_real_provider_loopback( timeout=90, ) assert completed.returncode == 0, completed.stdout + completed.stderr + # No console panel for every Flow and Agent a run starts: the Bot's log is its own again. + assert "Flow Execution" not in completed.stdout + completed.stderr def test_crewai_endpoint_forwards_caller_tools_and_accepts_tool_result_continuation( @@ -1152,6 +1487,8 @@ def test_crewai_endpoint_forwards_caller_tools_and_accepts_tool_result_continuat "blank-model", "strict-projection", "caller-tool", + "caller-schemas", + "system-in-place", "namespaced-model", "gateway-model", ], diff --git a/docs/agent-frameworks.md b/docs/agent-frameworks.md index ead0db5daf..142cac380c 100644 --- a/docs/agent-frameworks.md +++ b/docs/agent-frameworks.md @@ -289,16 +289,24 @@ new id in its snapshots, so the app shows the conversation twice. OpenBot's own CrewAI Bot is built this way, and [`agent-crewai/src/main.py`](../agent-crewai/src/main.py) handles all three. It keeps the run's system -messages for the Agent and turns OpenBot's tools into tools that hand the call back. It also keeps -each message's id. Start from that file and give the Agent your own role, goal and tools. Tools you -add run in your process as usual. +messages for the Agent, each where it was in the thread, and turns OpenBot's tools into tools that +hand the call back. It also keeps each message's id. Read it as a reference rather than copying it +whole: it imports modules from OpenBot's `shared/` folder (the model settings, the run's model key, +Gemini's signatures and the progress reminder) that your server does not have. It also relies on +parts of CrewAI and ag-ui-crewai that neither publishes, so pin both to exact versions, as +`agent-crewai/requirements.txt` does. Tools you add to your Agent run in your process as usual. Handing a call back needs a few more things that the file also does: - **The tool's name.** CrewAI shows the model `sanitize_tool_name(name)`, so `showBarChart` reaches it as `show_bar_chart`, and the model calls it by that. The call goes back under the server's name. -- **Its arguments.** CrewAI offers tools in strict mode, where every optional property is required - and nullable. The `null`s the tool's own schema did not allow are taken out of the handed-back call. +- **Its schema.** CrewAI offers tools in strict mode, which closes every object, so an open-ended one + (an artifact's `content`, a patch's `value`) could only ever be sent `{}`. Offer OpenBot's tools + with their own schema and `strict` off, as the Bot did before. Don't build a Pydantic model from + the schema either: CrewAI's `create_model_from_schema` fails the run on a `format: email` field + unless `email-validator` is installed, and on tuple-style `items`. +- **Its arguments.** A model may still send `null` for an optional property it means to leave out. + The `null`s the tool's own schema did not allow are taken out of the handed-back call. - **The words with it.** CrewAI keeps a step that called tools with no content. The words the model streamed in that step are the reply's content, so a line on a long job reaches the person. - **The client.** Name the provider (`LLM(model=..., provider="openai")`). Given `openai/`, From 20139488e1d044eeb5efe09a0405af5d599f7b69 Mon Sep 17 00:00:00 2001 From: lorenzejay Date: Wed, 2 Dec 2026 09:34:44 -0800 Subject: [PATCH 6/7] CHANGELOG.md is the release's: the CrewAI Bot's note moves to the pull request's description --- CHANGELOG.md | 9 --------- 1 file changed, 9 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index aaeb0770aa..8998635947 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -159,15 +159,6 @@ Newest first. `Unreleased` is what is on `main` and not yet tagged. once the conversation is free, the turn is carried on with the call answered as it would have been. -**Bots.** - -- **The CrewAI Bot is a CrewAI Agent.** A Bot on the CrewAI engine now answers through CrewAI's - conversational Agent (`Agent(conversational=True)`, new in CrewAI 1.15.45), served by - ag-ui-crewai's conversational mode. Before, it called the model directly from a one-step CrewAI - Flow. The Bot's role, the whole thread and OpenBot's tools reach it as they did, and its replies - still arrive whole rather than word by word. CrewAI now calls OpenAI, Anthropic and Google models - through their own SDKs, and calls any other model through LiteLLM as before. - ## 1.2.5 **Before upgrading.** From a9f20e0ce27714324caed3a473f22f2e57d8b461 Mon Sep 17 00:00:00 2001 From: lorenzejay Date: Thu, 3 Dec 2026 13:15:19 -0800 Subject: [PATCH 7/7] CrewAI Bot: pin crewai 1.15.41, the newest release at least two weeks old It is the version shared/model-lock.json records for agent-crewai. The harness suite and the live tool round trips pass on it as they did on 1.15.47. --- agent-crewai/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/agent-crewai/requirements.txt b/agent-crewai/requirements.txt index 7d20e55b68..694d706a1d 100644 --- a/agent-crewai/requirements.txt +++ b/agent-crewai/requirements.txt @@ -10,7 +10,7 @@ # # The extras are CrewAI's own clients for the providers OpenBot offers. CrewAI calls a model it # knows through the provider's SDK and refuses to start without it, even with LiteLLM installed. -crewai[anthropic,google-genai]==1.15.47 +crewai[anthropic,google-genai]==1.15.41 ag-ui-crewai==1.0.0 uvicorn[standard] # litellm 1.106.0 imports `CacheableResult` from `mcp.types`, which exists only in mcp 2.x, while