Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
199 changes: 144 additions & 55 deletions src/bub/core/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
from contextlib import AsyncExitStack, aclosing, asynccontextmanager
from dataclasses import asdict, replace
from datetime import UTC, datetime
from json import JSONDecodeError
from typing import Any, TypeVar

import republic
Expand Down Expand Up @@ -49,6 +48,9 @@

MAX_AUTO_HANDOFF_RETRIES = 1

INVALID_ARGUMENTS_EXCERPT = 500
"""Characters kept from each end of undecodable tool call arguments in the error the model sees."""

FIRST_CHUNK_KINDS = frozenset({"text", "reasoning"})
"""Stream events that carry a token the model emitted, marking where decode starts.

Expand Down Expand Up @@ -413,55 +415,108 @@ async def run_once(
)

tool_calls = response.tool_calls
if tool_calls:
tool_map = {tool_item.name: tool_item for tool_item in tools}
if any(tool_call.name not in tool_map for tool_call in tool_calls):
tool_map = {tool_item.name: tool_item for tool_item in await self.prepare_tools(tape, None)} | tool_map
serialized_tool_calls = [asdict(tool_call) for tool_call in tool_calls]
tool_invocations = [_tool_invocation(tool_call, tool_map) for tool_call in tool_calls]
yield StreamEvent("tool_call", {"tool_calls": serialized_tool_calls})
turn_state["_runtime_tool_names"] = tuple(tool_map)
context = ToolContext(
tape=tape, run_id=run_id, state=turn_state, events=self.events, step_messages=new_messages
)
execution = await ToolExecutor(events=self.events, max_concurrency=self.max_tool_concurrency).execute_many(
tool_invocations,
context=context,
call_ids=[call.id for call in tool_calls],
)
tool_results = execution.tool_results
else:
serialized_tool_calls, tool_results = [], None
assistant_fields = {
key: value
for key, value in {
"reasoning": response.reasoning,
"provider_data": [
asdict(part) for part in response.message.parts if isinstance(part, republic.ProviderData)
],
}.items()
if value
serialized_tool_calls: list[dict[str, Any]] = []
tool_results: list[Any] | None = None
finished: dict[str, Any] = {
"run_id": run_id,
"model": request.model,
"system_prompt": system_prompt,
"new_messages": new_messages,
"usage": state.usage,
"provider": provider,
"finish_reason": response.finish_reason,
"assistant_fields": {
key: value
for key, value in {
"reasoning": response.reasoning,
"provider_data": [
asdict(part) for part in response.message.parts if isinstance(part, republic.ProviderData)
],
}.items()
if value
},
}
if tool_calls:
try:
tool_map, resolved = await self._resolve_tool_calls(tape, tools, response)
# Undecodable arguments are recorded as ``{}`` so the call can be sent back to any provider.
serialized_tool_calls = [
asdict(tool_call) | ({} if valid else {"arguments": "{}"})
for tool_call, (_, _, valid) in zip(tool_calls, resolved, strict=True)
]
yield StreamEvent("tool_call", {"tool_calls": serialized_tool_calls})
turn_state["_runtime_tool_names"] = tuple(tool_map)
context = ToolContext(
tape=tape, run_id=run_id, state=turn_state, events=self.events, step_messages=new_messages
)
executor = ToolExecutor(events=self.events, max_concurrency=self.max_tool_concurrency)
execution = await executor.execute_many(
[(tool_obj, arguments) for tool_obj, arguments, _ in resolved],
context=context,
call_ids=[call.id for call in tool_calls],
)
tool_results = execution.tool_results
except Exception as exc:
await self._record_failed_step(tape, exc, text, serialized_tool_calls, finished)
raise
await self._emit(
ChatFinished,
tape,
run_id=run_id,
model=request.model,
system_prompt=system_prompt,
new_messages=new_messages,
response_text=(text or None) if tool_calls else text,
tool_calls=serialized_tool_calls,
tool_results=tool_results,
usage=state.usage,
provider=provider,
assistant_fields=assistant_fields,
**finished,
)
if tool_calls:
yield StreamEvent("tool_result", {"tool_results": tool_results})
yield StreamEvent("final", {"ok": True, "tool_calls": serialized_tool_calls, "tool_results": tool_results})
else:
yield StreamEvent("final", {"ok": True, "text": text})

async def _record_failed_step(
self,
tape: Tape,
exc: Exception,
text: str,
tool_calls: list[dict[str, Any]],
finished: dict[str, Any],
) -> None:
"""Record a step that failed after the model answered, with its usage; ``exc`` stays the step's error."""
error = exc if isinstance(exc, BubError) else BubError(ErrorKind.UNKNOWN, f"{exc!s}")
# Every recorded call needs a result for the tape to replay, but which calls ran is not known.
unknown = BubError(
ErrorKind.UNKNOWN,
"The outcome of this call is unknown: the step failed before tool results were recorded "
f"({error.message}). The tool may or may not have run.",
)
try:
await self._emit(
ChatFinished,
tape,
response_text=text or None,
tool_calls=tool_calls,
tool_results=[unknown] * len(tool_calls) if tool_calls else None,
error=error,
**finished,
)
except Exception:
logger.exception("chat.record.error tape={}", tape.name)

async def _resolve_tool_calls(
self, tape: Tape, tools: list[Tool], response: republic.Response
) -> tuple[dict[str, Tool], list[tuple[Tool, dict[str, Any], bool]]]:
"""Resolve a response's tool calls against the run's tools, and the agent's current ones if needed."""
tool_map = {tool_item.name: tool_item for tool_item in tools}
calls = response.tool_calls
if any(tool_call.name not in tool_map for tool_call in calls):
tool_map = {tool_item.name: tool_item for tool_item in await self.prepare_tools(tape, None)} | tool_map
# A response that stopped at the output token limit was cut off inside its last call.
truncated = response.finish_reason == "length"
return tool_map, [
_tool_invocation(call, tool_map, truncated=truncated and index == len(calls) - 1)
for index, call in enumerate(calls)
]

def _model_client(self, model: Model | None) -> ModelClient:
if model is None:
model = self.model
Expand Down Expand Up @@ -832,28 +887,62 @@ async def _stream_events(
})


def _tool_invocation(tool_call: republic.ToolCall, tool_map: dict[str, Tool]) -> tuple[Tool, dict[str, Any]]:
"""Resolve a model tool call to (runtime tool, arguments).
def _tool_invocation(
tool_call: republic.ToolCall, tool_map: dict[str, Tool], *, truncated: bool = False
) -> tuple[Tool, dict[str, Any], bool]:
"""Resolve a model tool call to (runtime tool, arguments, whether its arguments decoded).

An unknown tool name is not treated as a fatal error: it is surfaced as a
placeholder ``Tool`` so the invocation flows through ``ToolExecutor`` and
``ToolCallStarted`` handlers can recover it into a guidance
``tool_result`` instead of interrupting the turn. If no hook replaces the
call, the placeholder raises a clear tool error rather than succeeding with
an empty result.
Neither an unknown tool name nor undecodable arguments is treated as a fatal error:
each is surfaced as a placeholder ``Tool`` that raises, so the invocation flows
through ``ToolExecutor`` and comes back to the model as a failed ``tool_result`` it
can correct, instead of interrupting the turn. ``ToolCallStarted`` handlers may
recover an unknown tool into guidance; if none replaces the call, the placeholder
raises a clear tool error rather than succeeding with an empty result.

``truncated`` says the response stopped at the output token limit inside this call.
"""
tool_name = tool_call.name
try:
arguments = tool_call.args
except JSONDecodeError as exc:
raise BubError(ErrorKind.INVALID_INPUT, "Expected a function tool call with JSON object arguments.") from exc
if not isinstance(arguments, dict):
raise BubError(ErrorKind.INVALID_INPUT, "Expected a function tool call with JSON object arguments.")
arguments = _decode_arguments(tool_call, truncated)
except BubError as exc:
return Tool.failing(tool_name, exc), {}, False
tool_obj = tool_map.get(tool_name)
if tool_obj is None:

def raise_unknown_tool(**_: Any) -> None:
raise BubError(ErrorKind.TOOL, f"Unknown tool name: {tool_name}.")

return Tool(name=tool_name, handler=raise_unknown_tool), arguments
return tool_obj, arguments
unknown = BubError(ErrorKind.TOOL, f"Unknown tool name: {tool_name}.")
return Tool.failing(tool_name, unknown), arguments, True
return tool_obj, arguments, True


def _decode_arguments(tool_call: republic.ToolCall, truncated: bool) -> dict[str, Any]:
"""Return a tool call's arguments, or raise the error the model should see when they cannot be used."""
raw = tool_call.arguments
reason = None
# Arguments cut off before their first character arrive as an empty object.
if truncated and raw.strip() in {"", "{}"}:
reason = "they are empty"
else:
try:
arguments = tool_call.args
except (ValueError, RecursionError) as exc:
reason = f"they are not valid JSON ({exc})"
else:
if isinstance(arguments, dict):
return arguments
reason = "they are not a JSON object"
if truncated:
message = (
f"The arguments of this '{tool_call.name}' call were cut off because the response reached the "
"output token limit (max_tokens), so the tool did not run. Call it again with shorter arguments, "
"for example by splitting long content across several calls."
)
else:
message = (
f"The arguments of this '{tool_call.name}' call could not be used because {reason}, so the tool "
"did not run. Call it again with a JSON object of arguments."
)
if len(raw) > 2 * INVALID_ARGUMENTS_EXCERPT:
excerpt = f"{raw[:INVALID_ARGUMENTS_EXCERPT]}…{raw[-INVALID_ARGUMENTS_EXCERPT:]}"
else:
excerpt = raw
details = {"arguments": excerpt, "arguments_length": len(raw), "truncated": truncated}
raise BubError(ErrorKind.INVALID_INPUT, message, details=details)
6 changes: 4 additions & 2 deletions src/bub/core/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -284,8 +284,8 @@ class ToolCallFinished(AgentEvent):
class ChatFinished(TapeEvent):
"""One model step's exchange is complete and ready to be recorded.

Also emitted when the step fails before calling the model (``context_error``) or a
``before_llm_call`` decision finishes it.
Also emitted when the step fails before calling the model (``context_error``), when it
fails after the model answered (``error``), or when a ``before_llm_call`` decision finishes it.
"""

run_id: str
Expand All @@ -297,6 +297,8 @@ class ChatFinished(TapeEvent):
tool_results: list[Any] | None = None
usage: dict[str, Any] | None = None
provider: str | None = None
finish_reason: str | None = None
"""Why the model stopped, such as ``length`` when it reached the output token limit."""
assistant_fields: dict[str, Any] = field(default_factory=dict)
error: BubError | None = None
context_error: BubError | None = None
Expand Down
1 change: 1 addition & 0 deletions src/bub/core/recorder.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ async def on_chat_finished(self, event: ChatFinished) -> None:
provider=event.provider,
model=event.model,
usage=event.usage,
finish_reason=event.finish_reason,
)


Expand Down
3 changes: 3 additions & 0 deletions src/bub/core/tape.py
Original file line number Diff line number Diff line change
Expand Up @@ -465,6 +465,7 @@ async def record_chat( # noqa: C901
provider: str | None = None,
model: str | None = None,
usage: dict[str, Any] | None = None,
finish_reason: str | None = None,
assistant_fields: dict[str, Any] | None = None,
) -> None:
tape_name = self.name
Expand Down Expand Up @@ -496,6 +497,8 @@ async def record_chat( # noqa: C901
data["provider"] = provider
if model:
data["model"] = model
if finish_reason:
data["finish_reason"] = finish_reason
await self.store.append(tape_name, TapeEntry.event("run", data, **meta))

@staticmethod
Expand Down
13 changes: 13 additions & 0 deletions src/bub/core/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,19 @@ def to_schema(self) -> dict[str, Any]:
"""Build a function tool schema for hooks and diagnostics."""
return {"name": self.name, "description": self.description, "parameters": self.parameters}

@classmethod
def failing(cls, name: str, error: BubError) -> Tool:
"""Return a placeholder tool named ``name`` whose every call fails with ``error``.

It stands in for a call that cannot run, so the call still flows through
``ToolExecutor`` and ``error`` becomes its result.
"""

def fail(**_: Any) -> None:
raise error

return cls(name=name, handler=fail)

@classmethod
def from_callable(
cls,
Expand Down
Loading
Loading