Skip to content

Drop in a screenshot and convert it to clean code (HTML/Tailwind/React/Vue)

Python

Refactor agent streaming provider

Abi Raja58c94b68628d
diff --git a/backend/agentic/runner.py b/backend/agent/runner.py
similarity index 98%
rename from backend/agentic/runner.py
rename to backend/agent/runner.py
index af8e95d0..faaf491c 100644
--- a/backend/agentic/runner.py
+++ b/backend/agent/runner.py
@@ -15,8 +15,8 @@ from llm import (
Llm,
)
-from agentic.state import AgentFileState, seed_file_state_from_messages
-from agentic.streaming import (
+from agent.state import AgentFileState, seed_file_state_from_messages
+from agent.streaming import (
AnthropicAdapter,
ExecutedToolCall,
GeminiAdapter,
@@ -24,7 +24,7 @@ from agentic.streaming import (
ProviderAdapter,
StreamEvent,
)
-from agentic.tools import (
+from agent.tools import (
AgentToolbox,
canonical_tool_definitions,
extract_content_from_args,
diff --git a/backend/agentic/state.py b/backend/agent/state.py
similarity index 100%
rename from backend/agentic/state.py
rename to backend/agent/state.py
diff --git a/backend/agent/streaming/__init__.py b/backend/agent/streaming/__init__.py
new file mode 100644
index 00000000..21346bbe
--- /dev/null
+++ b/backend/agent/streaming/__init__.py
@@ -0,0 +1,16 @@
+from agent.streaming.providers.anthropic import AnthropicAdapter
+from agent.streaming.base import ProviderAdapter
+from agent.streaming.providers.gemini import GeminiAdapter
+from agent.streaming.providers.openai import OpenAIResponsesAdapter
+from agent.streaming.types import EventSink, ExecutedToolCall, StepResult, StreamEvent
+
+__all__ = [
+ "AnthropicAdapter",
+ "ProviderAdapter",
+ "GeminiAdapter",
+ "OpenAIResponsesAdapter",
+ "EventSink",
+ "ExecutedToolCall",
+ "StepResult",
+ "StreamEvent",
+]
diff --git a/backend/agentic/streaming/base.py b/backend/agent/streaming/base.py
similarity index 79%
rename from backend/agentic/streaming/base.py
rename to backend/agent/streaming/base.py
index 4ec373ab..b6f5b04d 100644
--- a/backend/agentic/streaming/base.py
+++ b/backend/agent/streaming/base.py
@@ -1,6 +1,6 @@
from typing import Protocol
-from agentic.streaming.types import EventSink, ExecutedToolCall, StepResult
+from agent.streaming.types import EventSink, ExecutedToolCall, StepResult
class ProviderAdapter(Protocol):
diff --git a/backend/agentic/streaming/providers/__init__.py b/backend/agent/streaming/providers/__init__.py
similarity index 100%
rename from backend/agentic/streaming/providers/__init__.py
rename to backend/agent/streaming/providers/__init__.py
diff --git a/backend/agent/streaming/providers/anthropic/__init__.py b/backend/agent/streaming/providers/anthropic/__init__.py
new file mode 100644
index 00000000..25bc5b21
--- /dev/null
+++ b/backend/agent/streaming/providers/anthropic/__init__.py
@@ -0,0 +1,6 @@
+from agent.streaming.providers.anthropic.adapter import AnthropicAdapter
+from agent.streaming.providers.anthropic.transform import (
+ convert_openai_messages_to_claude,
+)
+
+__all__ = ["AnthropicAdapter", "convert_openai_messages_to_claude"]
diff --git a/backend/agent/streaming/providers/anthropic/adapter.py b/backend/agent/streaming/providers/anthropic/adapter.py
new file mode 100644
index 00000000..c0a90193
--- /dev/null
+++ b/backend/agent/streaming/providers/anthropic/adapter.py
@@ -0,0 +1,85 @@
+import json
+from typing import Any, Dict, List
+
+from anthropic import AsyncAnthropic
+from openai.types.chat import ChatCompletionMessageParam
+
+from agent.streaming.providers.anthropic.parser import (
+ AnthropicParseState,
+ extract_tool_calls,
+ parse_stream_event,
+)
+from agent.streaming.providers.anthropic.stream import create_stream_context
+from agent.streaming.providers.anthropic.transform import (
+ convert_openai_messages_to_claude,
+)
+from agent.streaming.types import EventSink, ExecutedToolCall, StepResult
+from llm import Llm
+
+
+class AnthropicAdapter:
+ def __init__(
+ self,
+ client: AsyncAnthropic,
+ model: Llm,
+ prompt_messages: List[ChatCompletionMessageParam],
+ tools: List[Dict[str, Any]],
+ ):
+ self._client = client
+ self._model = model
+ self._tools = tools
+ system_prompt, claude_messages = convert_openai_messages_to_claude(prompt_messages)
+ self._system_prompt = system_prompt
+ self._messages = claude_messages
+
+ async def run_step(self, on_event: EventSink) -> StepResult:
+ state = AnthropicParseState()
+ stream_ctx = create_stream_context(
+ client=self._client,
+ model=self._model,
+ system_prompt=self._system_prompt,
+ messages=self._messages,
+ tools=self._tools,
+ )
+
+ async with stream_ctx as stream:
+ async for event in stream:
+ await parse_stream_event(event, state, on_event)
+ final_message = await stream.get_final_message()
+
+ tool_calls = extract_tool_calls(final_message)
+ return StepResult(assistant_text=state.assistant_text, tool_calls=tool_calls)
+
+ def apply_tool_results(
+ self,
+ step_result: StepResult,
+ executed_tool_calls: list[ExecutedToolCall],
+ ) -> None:
+ assistant_blocks: List[Dict[str, Any]] = []
+ if step_result.assistant_text:
+ assistant_blocks.append({"type": "text", "text": step_result.assistant_text})
+
+ for call in step_result.tool_calls:
+ assistant_blocks.append(
+ {
+ "type": "tool_use",
+ "id": call.id,
+ "name": call.name,
+ "input": call.arguments,
+ }
+ )
+
+ self._messages.append({"role": "assistant", "content": assistant_blocks})
+
+ tool_result_blocks: List[Dict[str, Any]] = []
+ for executed in executed_tool_calls:
+ tool_result_blocks.append(
+ {
+ "type": "tool_result",
+ "tool_use_id": executed.tool_call.id,
+ "content": json.dumps(executed.result.result),
+ "is_error": not executed.result.ok,
+ }
+ )
+
+ self._messages.append({"role": "user", "content": tool_result_blocks})
diff --git a/backend/agent/streaming/providers/anthropic/parser.py b/backend/agent/streaming/providers/anthropic/parser.py
new file mode 100644
index 00000000..711911eb
--- /dev/null
+++ b/backend/agent/streaming/providers/anthropic/parser.py
@@ -0,0 +1,93 @@
+import uuid
+from dataclasses import dataclass, field
+from typing import Any, Dict, List
+
+from agent.streaming.types import EventSink, StreamEvent
+from agent.tools import ToolCall
+
+
+@dataclass
+class AnthropicParseState:
+ assistant_text: str = ""
+ tool_blocks: Dict[int, Dict[str, Any]] = field(default_factory=dict)
+ tool_json_buffers: Dict[int, str] = field(default_factory=dict)
+
+
+async def parse_stream_event(
+ event: Any,
+ state: AnthropicParseState,
+ on_event: EventSink,
+) -> None:
+ if event.type == "content_block_start":
+ block = event.content_block
+ if getattr(block, "type", None) != "tool_use":
+ return
+
+ tool_id = getattr(block, "id", None) or f"tool-{uuid.uuid4().hex[:6]}"
+ tool_name = getattr(block, "name", None) or "unknown_tool"
+ args = getattr(block, "input", None)
+ state.tool_blocks[event.index] = {
+ "id": tool_id,
+ "name": tool_name,
+ }
+ state.tool_json_buffers[event.index] = ""
+ if args:
+ await on_event(
+ StreamEvent(
+ type="tool_call_delta",
+ tool_call_id=tool_id,
+ tool_name=tool_name,
+ tool_arguments=args,
+ )
+ )
+ return
+
+ if event.type != "content_block_delta":
+ return
+
+ if event.delta.type == "thinking_delta":
+ await on_event(StreamEvent(type="thinking_delta", text=event.delta.thinking))
+ return
+
+ if event.delta.type == "text_delta":
+ state.assistant_text += event.delta.text
+ await on_event(StreamEvent(type="assistant_delta", text=event.delta.text))
+ return
+
+ if event.delta.type != "input_json_delta":
+ return
+
+ partial_json = getattr(event.delta, "partial_json", None) or ""
+ if not partial_json:
+ return
+
+ buffer = state.tool_json_buffers.get(event.index, "") + partial_json
+ state.tool_json_buffers[event.index] = buffer
+ meta = state.tool_blocks.get(event.index)
+ if not meta:
+ return
+
+ await on_event(
+ StreamEvent(
+ type="tool_call_delta",
+ tool_call_id=meta.get("id"),
+ tool_name=meta.get("name"),
+ tool_arguments=buffer,
+ )
+ )
+
+
+def extract_tool_calls(final_message: Any) -> List[ToolCall]:
+ tool_calls: List[ToolCall] = []
+ if final_message and final_message.content:
+ for block in final_message.content:
+ if block.type != "tool_use":
+ continue
+ tool_calls.append(
+ ToolCall(
+ id=block.id,
+ name=block.name,
+ arguments=block.input,
+ )
+ )
+ return tool_calls
diff --git a/backend/agent/streaming/providers/anthropic/stream.py b/backend/agent/streaming/providers/anthropic/stream.py
new file mode 100644
index 00000000..99072128
--- /dev/null
+++ b/backend/agent/streaming/providers/anthropic/stream.py
@@ -0,0 +1,47 @@
+from typing import Any, Dict, List
+
+from anthropic import AsyncAnthropic
+
+from llm import Llm
+
+
+THINKING_MODELS = {
+ Llm.CLAUDE_4_5_SONNET_2025_09_29.value,
+ Llm.CLAUDE_4_5_OPUS_2025_11_01.value,
+}
+
+
+def create_stream_context(
+ client: AsyncAnthropic,
+ model: Llm,
+ system_prompt: str,
+ messages: List[Dict[str, Any]],
+ tools: List[Dict[str, Any]],
+) -> Any:
+ stream_kwargs: Dict[str, Any] = {
+ "model": model.value,
+ "max_tokens": 30000,
+ "system": system_prompt,
+ "messages": messages,
+ "tools": tools,
+ }
+
+ if model.value in THINKING_MODELS:
+ stream_kwargs["thinking"] = {
+ "type": "enabled",
+ "budget_tokens": 10000,
+ }
+ else:
+ stream_kwargs["temperature"] = 0.0
+
+ if hasattr(client, "beta") and hasattr(client.beta, "messages"):
+ stream_client = client.beta.messages
+ else:
+ stream_client = client.messages
+
+ try:
+ stream_kwargs_with_betas = dict(stream_kwargs)
+ stream_kwargs_with_betas["betas"] = ["fine-grained-tool-streaming-2025-05-14"]
+ return stream_client.stream(**stream_kwargs_with_betas)
+ except TypeError:
+ return stream_client.stream(**stream_kwargs)
diff --git a/backend/agentic/streaming/providers/anthropic/transform.py b/backend/agent/streaming/providers/anthropic/transform.py
similarity index 100%
rename from backend/agentic/streaming/providers/anthropic/transform.py
rename to backend/agent/streaming/providers/anthropic/transform.py
diff --git a/backend/agentic/streaming/providers/gemini/__init__.py b/backend/agent/streaming/providers/gemini/__init__.py
similarity index 61%
rename from backend/agentic/streaming/providers/gemini/__init__.py
rename to backend/agent/streaming/providers/gemini/__init__.py
index 484668e8..097b7e81 100644
--- a/backend/agentic/streaming/providers/gemini/__init__.py
+++ b/backend/agent/streaming/providers/gemini/__init__.py
@@ -1,10 +1,12 @@
-from agentic.streaming.providers.gemini.transform import (
+from agent.streaming.providers.gemini.adapter import GeminiAdapter
+from agent.streaming.providers.gemini.transform import (
convert_message_to_gemini_content,
get_gemini_api_model_name,
get_thinking_level_for_model,
)
__all__ = [
+ "GeminiAdapter",
"convert_message_to_gemini_content",
"get_gemini_api_model_name",
"get_thinking_level_for_model",
diff --git a/backend/agent/streaming/providers/gemini/adapter.py b/backend/agent/streaming/providers/gemini/adapter.py
new file mode 100644
index 00000000..c75fb852
--- /dev/null
+++ b/backend/agent/streaming/providers/gemini/adapter.py
@@ -0,0 +1,84 @@
+# pyright: reportUnknownVariableType=false
+from typing import Any, Dict, List, cast
+
+from google import genai
+from google.genai import types
+from openai.types.chat import ChatCompletionMessageParam
+
+from agent.streaming.providers.gemini.parser import (
+ GeminiParseState,
+ build_step_result,
+ parse_chunk,
+)
+from agent.streaming.providers.gemini.stream import (
+ create_generate_config,
+ create_stream,
+)
+from agent.streaming.providers.gemini.transform import convert_message_to_gemini_content
+from agent.streaming.types import EventSink, ExecutedToolCall, StepResult
+from llm import Llm
+
+
+class GeminiAdapter:
+ def __init__(
+ self,
+ client: genai.Client,
+ model: Llm,
+ prompt_messages: List[ChatCompletionMessageParam],
+ tools: List[types.Tool],
+ ):
+ self._client = client
+ self._model = model
+ self._tools = tools
+
+ self._system_prompt = str(prompt_messages[0].get("content", ""))
+ self._contents: List[types.Content] = [
+ convert_message_to_gemini_content(msg) for msg in prompt_messages[1:]
+ ]
+
+ async def run_step(self, on_event: EventSink) -> StepResult:
+ state = GeminiParseState()
+ config = create_generate_config(
+ model=self._model,
+ system_prompt=self._system_prompt,
+ tools=self._tools,
+ )
+ stream = await create_stream(
+ client=self._client,
+ model=self._model,
+ contents=self._contents,
+ config=config,
+ )
+
+ async for chunk in stream:
+ await parse_chunk(chunk, state, on_event)
+
+ return build_step_result(state)
+
+ def apply_tool_results(
+ self,
+ step_result: StepResult,
+ executed_tool_calls: list[ExecutedToolCall],
+ ) -> None:
+ function_call_parts = cast(
+ List[types.Part],
+ ((step_result.provider_state or {}).get("function_call_parts") or []),
+ )
+
+ model_parts: List[Any] = []
+ if step_result.assistant_text:
+ model_parts.append({"text": step_result.assistant_text}) # type: ignore
+ model_parts.extend(function_call_parts)
+
+ self._contents.append(types.Content(role="model", parts=model_parts))
+
+ tool_result_parts: List[types.Part] = []
+ for executed in executed_tool_calls:
+ tool_result_parts.append(
+ types.Part.from_function_response(
+ name=executed.tool_call.name,
+ response=executed.result.result,
+ )
+ )
+
+ self._contents.append(types.Content(role="tool", parts=tool_result_parts))
diff --git a/backend/agent/streaming/providers/gemini/parser.py b/backend/agent/streaming/providers/gemini/parser.py
new file mode 100644
index 00000000..66685b91
--- /dev/null
+++ b/backend/agent/streaming/providers/gemini/parser.py
@@ -0,0 +1,69 @@
+import uuid
+from dataclasses import dataclass, field
+from typing import List
+
+from google.genai import types
+
+from agent.streaming.types import EventSink, StepResult, StreamEvent
+from agent.tools import ToolCall
+
+
+@dataclass
+class GeminiParseState:
+ assistant_text: str = ""
+ tool_calls: List[ToolCall] = field(default_factory=list)
+ function_call_parts: List[types.Part] = field(default_factory=list)
+
+
+async def parse_chunk(
+ chunk: types.GenerateContentResponse,
+ state: GeminiParseState,
+ on_event: EventSink,
+) -> None:
+ if not chunk.candidates:
+ return
+
+ candidate_content = chunk.candidates[0].content
+ if not candidate_content or not candidate_content.parts:
+ return
+
+ for part in candidate_content.parts:
+ if getattr(part, "thought", False) and part.text:
+ await on_event(StreamEvent(type="thinking_delta", text=part.text))
+ continue
+
+ if part.function_call:
+ state.function_call_parts.append(part)
+ args = part.function_call.args or {}
+ tool_id = part.function_call.id or f"tool-{uuid.uuid4().hex[:6]}"
+ tool_name = part.function_call.name or "unknown_tool"
+
+ await on_event(
+ StreamEvent(
+ type="tool_call_delta",
+ tool_call_id=tool_id,
+ tool_name=tool_name,
+ tool_arguments=args,
+ )
+ )
+
+ state.tool_calls.append(
+ ToolCall(
+ id=tool_id,
+ name=tool_name,
+ arguments=args,
+ )
+ )
+ continue
+
+ if part.text:
+ state.assistant_text += part.text
+ await on_event(StreamEvent(type="assistant_delta", text=part.text))
+
+
+def build_step_result(state: GeminiParseState) -> StepResult:
+ return StepResult(
+ assistant_text=state.assistant_text,
+ tool_calls=state.tool_calls,
+ provider_state={"function_call_parts": state.function_call_parts},
+ )
diff --git a/backend/agent/streaming/providers/gemini/stream.py b/backend/agent/streaming/providers/gemini/stream.py
new file mode 100644
index 00000000..d085ce1f
--- /dev/null
+++ b/backend/agent/streaming/providers/gemini/stream.py
@@ -0,0 +1,38 @@
+from typing import Any, List, cast
+
+from google import genai
+from google.genai import types
+
+from llm import Llm
+from agent.streaming.providers.gemini.transform import (
+ get_gemini_api_model_name,
+ get_thinking_level_for_model,
+)
+
+
+def create_generate_config(model: Llm, system_prompt: str, tools: List[types.Tool]) -> Any:
+ thinking_level = get_thinking_level_for_model(model)
+ return types.GenerateContentConfig(
+ temperature=0,
+ max_output_tokens=30000,
+ system_instruction=system_prompt,
+ thinking_config=types.ThinkingConfig(
+ thinking_level=cast(Any, thinking_level),
+ include_thoughts=True,
+ ),
+ tools=tools,
+ )
+
+
+async def create_stream(
+ client: genai.Client,
+ model: Llm,
+ contents: List[types.Content],
+ config: Any,
+) -> Any:
+ api_model_name = get_gemini_api_model_name(model)
+ return await client.aio.models.generate_content_stream(
+ model=api_model_name,
+ contents=cast(Any, contents),
+ config=config,
+ )
diff --git a/backend/agentic/streaming/providers/gemini/transform.py b/backend/agent/streaming/providers/gemini/transform.py
similarity index 100%
rename from backend/agentic/streaming/providers/gemini/transform.py
rename to backend/agent/streaming/providers/gemini/transform.py
diff --git a/backend/agent/streaming/providers/openai/__init__.py b/backend/agent/streaming/providers/openai/__init__.py
new file mode 100644
index 00000000..a33cec4f
--- /dev/null
+++ b/backend/agent/streaming/providers/openai/__init__.py
@@ -0,0 +1,3 @@
+from agent.streaming.providers.openai.adapter import OpenAIResponsesAdapter
+
+__all__ = ["OpenAIResponsesAdapter"]
diff --git a/backend/agent/streaming/providers/openai/adapter.py b/backend/agent/streaming/providers/openai/adapter.py
new file mode 100644
index 00000000..3b143930
--- /dev/null
+++ b/backend/agent/streaming/providers/openai/adapter.py
@@ -0,0 +1,67 @@
+# pyright: reportUnknownVariableType=false
+import json
+from typing import Any, Dict, List
+
+from openai import AsyncOpenAI
+from openai.types.chat import ChatCompletionMessageParam
+
+from agent.streaming.providers.openai.parser import (
+ OpenAIResponsesParseState,
+ build_step_result,
+ parse_event,
+)
+from agent.streaming.providers.openai.stream import create_responses_stream
+from agent.streaming.providers.openai.transform import (
+ convert_message_to_responses_input,
+)
+from agent.streaming.types import EventSink, ExecutedToolCall, StepResult
+from llm import Llm
+
+
+class OpenAIResponsesAdapter:
+ def __init__(
+ self,
+ client: AsyncOpenAI,
+ model: Llm,
+ prompt_messages: List[ChatCompletionMessageParam],
+ tools: List[Dict[str, Any]],
+ ):
+ self._client = client
+ self._model = model
+ self._tools = tools
+ self._input_items: List[Dict[str, Any]] = [
+ convert_message_to_responses_input(m) for m in prompt_messages
+ ]
+
+ async def run_step(self, on_event: EventSink) -> StepResult:
+ state = OpenAIResponsesParseState()
+ stream = await create_responses_stream(
+ client=self._client,
+ model=self._model,
+ input_items=self._input_items,
+ tools=self._tools,
+ )
+ async for event in stream: # type: ignore
+ await parse_event(event, state, on_event)
+ return build_step_result(state)
+
+ def apply_tool_results(
+ self,
+ step_result: StepResult,
+ executed_tool_calls: list[ExecutedToolCall],
+ ) -> None:
+ provider_state = step_result.provider_state or {}
+ output_items = provider_state.get("output_items") or []
+
+ tool_output_items: List[Dict[str, Any]] = []
+ for executed in executed_tool_calls:
+ tool_output_items.append(
+ {
+ "type": "function_call_output",
+ "call_id": executed.tool_call.id,
+ "output": json.dumps(executed.result.result),
+ }
+ )
+
+ self._input_items.extend(output_items)
+ self._input_items.extend(tool_output_items)
diff --git a/backend/agent/streaming/providers/openai/parser.py b/backend/agent/streaming/providers/openai/parser.py
new file mode 100644
index 00000000..c1f7b7bc
--- /dev/null
+++ b/backend/agent/streaming/providers/openai/parser.py
@@ -0,0 +1,255 @@
+import uuid
+from dataclasses import dataclass, field
+from typing import Any, Dict, List
+
+from agent.state import ensure_str
+from agent.streaming.types import EventSink, StepResult, StreamEvent
+from agent.tools import ToolCall, parse_json_arguments
+from agent.streaming.providers.openai.transform import get_event_attr
+
+
+@dataclass
+class OpenAIResponsesParseState:
+ assistant_text: str = ""
+ tool_calls: Dict[str, Dict[str, Any]] = field(default_factory=dict)
+ item_to_call_id: Dict[str, str] = field(default_factory=dict)
+ output_items_by_index: Dict[int, Dict[str, Any]] = field(default_factory=dict)
+
+
+async def parse_event(
+ event: Any,
+ state: OpenAIResponsesParseState,
+ on_event: EventSink,
+) -> None:
+ event_type = get_event_attr(event, "type")
+ if event_type in (
+ "response.created",
+ "response.completed",
+ "response.done",
+ "response.output_item.done",
+ ):
+ if event_type == "response.output_item.done":
+ output_index = get_event_attr(event, "output_index")
+ item = get_event_attr(event, "item")
+ if isinstance(output_index, int) and item:
+ state.output_items_by_index[output_index] = item
+ return
+
+ if event_type == "response.output_text.delta":
+ delta = get_event_attr(event, "delta", "")
+ if delta:
+ state.assistant_text += delta
+ await on_event(StreamEvent(type="assistant_delta", text=delta))
+ return
+
+ if event_type in (
+ "response.reasoning_text.delta",
+ "response.reasoning_summary_text.delta",
+ ):
+ delta = get_event_attr(event, "delta", "")
+ if delta:
+ await on_event(StreamEvent(type="thinking_delta", text=delta))
+ return
+
+ if event_type in (
+ "response.reasoning_summary_part.added",
+ "response.reasoning_summary_part.done",
+ ):
+ part = get_event_attr(event, "part") or {}
+ text = get_event_attr(part, "text", "")
+ if text:
+ await on_event(StreamEvent(type="thinking_delta", text=text))
+ return
+
+ if event_type == "response.output_item.added":
+ item = get_event_attr(event, "item")
+ item_type = get_event_attr(item, "type") if item else None
+ output_index = get_event_attr(event, "output_index")
+ if isinstance(output_index, int) and item:
+ state.output_items_by_index.setdefault(output_index, item)
+
+ if item and item_type in ("function_call", "custom_tool_call"):
+ item_id = get_event_attr(item, "id")
+ call_id = get_event_attr(item, "call_id") or item_id
+ if item_id and call_id:
+ state.item_to_call_id[item_id] = call_id
+ if call_id:
+ if item_id and item_id in state.tool_calls and item_id != call_id:
+ existing = state.tool_calls.pop(item_id)
+ state.tool_calls[call_id] = {
+ **existing,
+ "id": call_id,
+ }
+ args_value = get_event_attr(item, "arguments")
+ if args_value is None and item_type == "custom_tool_call":
+ args_value = get_event_attr(item, "input")
+ state.tool_calls.setdefault(
+ call_id,
+ {
+ "id": call_id,
+ "name": get_event_attr(item, "name"),
+ "arguments": args_value or "",
+ },
+ )
+ if args_value:
+ await on_event(
+ StreamEvent(
+ type="tool_call_delta",
+ tool_call_id=call_id,
+ tool_name=get_event_attr(item, "name"),
+ tool_arguments=args_value,
+ )
+ )
+ return
+
+ if event_type in (
+ "response.function_call_arguments.delta",
+ "response.mcp_call_arguments.delta",
+ "response.custom_tool_call_input.delta",
+ ):
+ item_id = get_event_attr(event, "item_id")
+ call_id = get_event_attr(event, "call_id")
+ if call_id and item_id:
+ state.item_to_call_id[item_id] = call_id
+ if not call_id:
+ call_id = state.item_to_call_id.get(item_id) if item_id else None
+ if not call_id and item_id:
+ call_id = item_id
+ if not call_id:
+ return
+
+ entry = state.tool_calls.setdefault(
+ call_id,
+ {
+ "id": call_id,
+ "name": get_event_attr(event, "name"),
+ "arguments": "",
+ },
+ )
+ delta_value = get_event_attr(event, "delta")
+ if delta_value is None:
+ delta_value = get_event_attr(event, "input")
+ entry["arguments"] += ensure_str(delta_value)
+
+ await on_event(
+ StreamEvent(
+ type="tool_call_delta",
+ tool_call_id=call_id,
+ tool_name=entry.get("name"),
+ tool_arguments=entry.get("arguments"),
+ )
+ )
+ return
+
+ if event_type not in (
+ "response.function_call_arguments.done",
+ "response.mcp_call_arguments.done",
+ "response.custom_tool_call_input.done",
+ ):
+ return
+
+ item_id = get_event_attr(event, "item_id")
+ call_id = get_event_attr(event, "call_id")
+ if call_id and item_id:
+ state.item_to_call_id[item_id] = call_id
+ if not call_id:
+ call_id = state.item_to_call_id.get(item_id) if item_id else None
+ if not call_id and item_id:
+ call_id = item_id
+ if not call_id:
+ return
+
+ entry = state.tool_calls.setdefault(
+ call_id,
+ {
+ "id": call_id,
+ "name": get_event_attr(event, "name"),
+ "arguments": "",
+ },
+ )
+ final_value = get_event_attr(event, "arguments")
+ if final_value is None:
+ final_value = get_event_attr(event, "input")
+ if final_value is None:
+ final_value = entry["arguments"]
+ entry["arguments"] = final_value
+ if get_event_attr(event, "name"):
+ entry["name"] = get_event_attr(event, "name")
+
+ await on_event(
+ StreamEvent(
+ type="tool_call_delta",
+ tool_call_id=call_id,
+ tool_name=entry.get("name"),
+ tool_arguments=entry.get("arguments"),
+ )
+ )
+
+ output_index = get_event_attr(event, "output_index")
+ if (
+ item_id
+ and isinstance(output_index, int)
+ and isinstance(state.output_items_by_index.get(output_index), dict)
+ ):
+ state.output_items_by_index[output_index] = {
+ **state.output_items_by_index[output_index],
+ "arguments": entry["arguments"],
+ "call_id": call_id,
+ "name": entry.get("name"),
+ }
+
+
+def build_step_result(state: OpenAIResponsesParseState) -> StepResult:
+ output_items = [
+ state.output_items_by_index[idx]
+ for idx in sorted(state.output_items_by_index.keys())
+ if state.output_items_by_index.get(idx)
+ ]
+
+ tool_items = [
+ item
+ for item in output_items
+ if isinstance(item, dict)
+ and item.get("type") in ("function_call", "custom_tool_call")
+ ]
+
+ tool_call_list: List[ToolCall] = []
+ if tool_items:
+ for item in tool_items:
+ raw_args = item.get("arguments")
+ if raw_args is None and item.get("type") == "custom_tool_call":
+ raw_args = item.get("input")
+ args, error = parse_json_arguments(raw_args)
+ if error:
+ args = {"_raw": raw_args}
+ call_id = item.get("call_id") or item.get("id")
+ tool_call_list.append(
+ ToolCall(
+ id=call_id or f"call-{uuid.uuid4().hex[:6]}",
+ name=item.get("name") or "unknown_tool",
+ arguments=args,
+ )
+ )
+ else:
+ for entry in state.tool_calls.values():
+ args, error = parse_json_arguments(entry.get("arguments"))
+ if error:
+ args = {"_raw": entry.get("arguments")}
+ call_id = entry.get("id") or entry.get("call_id")
+ tool_call_list.append(
+ ToolCall(
+ id=call_id or f"call-{uuid.uuid4().hex[:6]}",
+ name=entry.get("name") or "unknown_tool",
+ arguments=args,
+ )
+ )
+
+ provider_state = None
+ if tool_call_list:
+ provider_state = {"output_items": output_items}
+
+ return StepResult(
+ assistant_text=state.assistant_text,
+ tool_calls=tool_call_list,
+ provider_state=provider_state,
+ )
diff --git a/backend/agent/streaming/providers/openai/stream.py b/backend/agent/streaming/providers/openai/stream.py
new file mode 100644
index 00000000..c90ae951
--- /dev/null
+++ b/backend/agent/streaming/providers/openai/stream.py
@@ -0,0 +1,33 @@
+from typing import Any, Dict, List
+
+from openai import AsyncOpenAI
+
+from llm import Llm, get_openai_api_name, get_openai_reasoning_effort
+
+
+async def create_responses_stream(
+ client: AsyncOpenAI,
+ model: Llm,
+ input_items: List[Dict[str, Any]],
+ tools: List[Dict[str, Any]],
+) -> Any:
+ params: Dict[str, Any] = {
+ "model": get_openai_api_name(model),
+ "input": input_items,
+ "tools": tools,
+ "tool_choice": "auto",
+ "stream": True,
+ "max_output_tokens": 30000,
+ }
+
+ reasoning_effort = get_openai_reasoning_effort(model)
+ if reasoning_effort:
+ params["reasoning"] = {"effort": reasoning_effort}
+
+ responses_client = getattr(client, "responses", None)
+ if responses_client is None:
+ raise Exception(
+ "OpenAI SDK is too old for GPT-5.2 Codex. Please upgrade the 'openai' package to a version that supports the Responses API."
+ )
+
+ return await responses_client.create(**params) # type: ignore
diff --git a/backend/agent/streaming/providers/openai/transform.py b/backend/agent/streaming/providers/openai/transform.py
new file mode 100644
index 00000000..e5b5a45e
--- /dev/null
+++ b/backend/agent/streaming/providers/openai/transform.py
@@ -0,0 +1,40 @@
+from typing import Any, Dict, List
+
+from openai.types.chat import ChatCompletionMessageParam
+
+
+def convert_message_to_responses_input(
+ message: ChatCompletionMessageParam,
+) -> Dict[str, Any]:
+ role = message.get("role", "user")
+ content = message.get("content", "")
+
+ if isinstance(content, str):
+ return {"role": role, "content": content}
+
+ parts: List[Dict[str, Any]] = []
+ if isinstance(content, list):
+ for part in content:
+ if not isinstance(part, dict):
+ continue
+ if part.get("type") == "text":
+ parts.append({"type": "input_text", "text": part.get("text", "")})
+ elif part.get("type") == "image_url":
+ image_url = part.get("image_url", {})
+ parts.append(
+ {
+ "type": "input_image",
+ "image_url": image_url.get("url", ""),
+ "detail": image_url.get("detail", "auto"),
+ }
+ )
+
+ return {"role": role, "content": parts}
+
+
+def get_event_attr(event: Any, key: str, default: Any = None) -> Any:
+ if hasattr(event, key):
+ return getattr(event, key)
+ if isinstance(event, dict):
+ return event.get(key, default)
+ return default
diff --git a/backend/agentic/streaming/types.py b/backend/agent/streaming/types.py
similarity index 92%
rename from backend/agentic/streaming/types.py
rename to backend/agent/streaming/types.py
index 0dacf133..e3f7723c 100644
--- a/backend/agentic/streaming/types.py
+++ b/backend/agent/streaming/types.py
@@ -1,7 +1,7 @@
from dataclasses import dataclass
from typing import Any, Awaitable, Callable, List, Literal, Optional
-from agentic.tools import ToolCall, ToolExecutionResult
+from agent.tools import ToolCall, ToolExecutionResult
StreamEventType = Literal[
diff --git a/backend/agentic/tools.py b/backend/agent/tools.py
similarity index 99%
rename from backend/agentic/tools.py
rename to backend/agent/tools.py
index cfede107..5269cc1a 100644
--- a/backend/agentic/tools.py
+++ b/backend/agent/tools.py
@@ -11,7 +11,7 @@ from config import REPLICATE_API_KEY
from image_generation.core import process_tasks
from image_generation.replicate import remove_background
-from agentic.state import AgentFileState, ensure_str
+from agent.state import AgentFileState, ensure_str
@dataclass(frozen=True)
diff --git a/backend/agentic/streaming/__init__.py b/backend/agentic/streaming/__init__.py
deleted file mode 100644
index 755a2ce1..00000000
--- a/backend/agentic/streaming/__init__.py
+++ /dev/null
@@ -1,16 +0,0 @@
-from agentic.streaming.anthropic import AnthropicAdapter
-from agentic.streaming.base import ProviderAdapter
-from agentic.streaming.gemini import GeminiAdapter
-from agentic.streaming.openai_responses import OpenAIResponsesAdapter
-from agentic.streaming.types import EventSink, ExecutedToolCall, StepResult, StreamEvent
-
-__all__ = [
- "AnthropicAdapter",
- "ProviderAdapter",
- "GeminiAdapter",
- "OpenAIResponsesAdapter",
- "EventSink",
- "ExecutedToolCall",
- "StepResult",
- "StreamEvent",
-]
diff --git a/backend/agentic/streaming/anthropic.py b/backend/agentic/streaming/anthropic.py
deleted file mode 100644
index cc951aa4..00000000
--- a/backend/agentic/streaming/anthropic.py
+++ /dev/null
@@ -1,173 +0,0 @@
-import json
-import uuid
-from typing import Any, Dict, List
-
-from anthropic import AsyncAnthropic
-from openai.types.chat import ChatCompletionMessageParam
-
-from agentic.streaming.types import EventSink, ExecutedToolCall, StepResult, StreamEvent
-from agentic.tools import ToolCall
-from llm import Llm
-from agentic.streaming.providers.anthropic.transform import (
- convert_openai_messages_to_claude,
-)
-
-
-THINKING_MODELS = {
- Llm.CLAUDE_4_5_SONNET_2025_09_29.value,
- Llm.CLAUDE_4_5_OPUS_2025_11_01.value,
-}
-
-
-class AnthropicAdapter:
- def __init__(
- self,
- client: AsyncAnthropic,
- model: Llm,
- prompt_messages: List[ChatCompletionMessageParam],
- tools: List[Dict[str, Any]],
- ):
- self._client = client
- self._model = model
- self._tools = tools
- system_prompt, claude_messages = convert_openai_messages_to_claude(prompt_messages)
- self._system_prompt = system_prompt
- self._messages = claude_messages
-
- async def run_step(self, on_event: EventSink) -> StepResult:
- assistant_text = ""
- tool_blocks: Dict[int, Dict[str, Any]] = {}
- tool_json_buffers: Dict[int, str] = {}
-
- stream_kwargs: Dict[str, Any] = {
- "model": self._model.value,
- "max_tokens": 30000,
- "system": self._system_prompt,
- "messages": self._messages,
- "tools": self._tools,
- }
-
- if self._model.value in THINKING_MODELS:
- stream_kwargs["thinking"] = {
- "type": "enabled",
- "budget_tokens": 10000,
- }
- else:
- stream_kwargs["temperature"] = 0.0
-
- if hasattr(self._client, "beta") and hasattr(self._client.beta, "messages"):
- stream_client = self._client.beta.messages
- else:
- stream_client = self._client.messages
-
- try:
- stream_kwargs_with_betas = dict(stream_kwargs)
- stream_kwargs_with_betas["betas"] = ["fine-grained-tool-streaming-2025-05-14"]
- stream_ctx = stream_client.stream(**stream_kwargs_with_betas)
- except TypeError:
- stream_ctx = stream_client.stream(**stream_kwargs)
-
- async with stream_ctx as stream:
- async for event in stream:
- if event.type == "content_block_start":
- block = event.content_block
- if getattr(block, "type", None) == "tool_use":
- tool_id = getattr(block, "id", None) or f"tool-{uuid.uuid4().hex[:6]}"
- tool_name = getattr(block, "name", None) or "unknown_tool"
- args = getattr(block, "input", None)
- tool_blocks[event.index] = {
- "id": tool_id,
- "name": tool_name,
- }
- tool_json_buffers[event.index] = ""
- if args:
- await on_event(
- StreamEvent(
- type="tool_call_delta",
- tool_call_id=tool_id,
- tool_name=tool_name,
- tool_arguments=args,
- )
- )
- continue
-
- if event.type != "content_block_delta":
- continue
-
- if event.delta.type == "thinking_delta":
- await on_event(
- StreamEvent(type="thinking_delta", text=event.delta.thinking)
- )
- elif event.delta.type == "text_delta":
- assistant_text += event.delta.text
- await on_event(
- StreamEvent(type="assistant_delta", text=event.delta.text)
- )
- elif event.delta.type == "input_json_delta":
- partial_json = getattr(event.delta, "partial_json", None) or ""
- if not partial_json:
- continue
- buffer = tool_json_buffers.get(event.index, "") + partial_json
- tool_json_buffers[event.index] = buffer
- meta = tool_blocks.get(event.index)
- if not meta:
- continue
- await on_event(
- StreamEvent(
- type="tool_call_delta",
- tool_call_id=meta.get("id"),
- tool_name=meta.get("name"),
- tool_arguments=buffer,
- )
- )
-
- final_message = await stream.get_final_message()
-
- tool_calls: List[ToolCall] = []
- if final_message and final_message.content:
- for block in final_message.content:
- if block.type != "tool_use":
- continue
- tool_calls.append(
- ToolCall(
- id=block.id,
- name=block.name,
- arguments=block.input,
- )
- )
-
- return StepResult(assistant_text=assistant_text, tool_calls=tool_calls)
-
- def apply_tool_results(
- self,
- step_result: StepResult,
- executed_tool_calls: list[ExecutedToolCall],
- ) -> None:
- assistant_blocks: List[Dict[str, Any]] = []
- if step_result.assistant_text:
- assistant_blocks.append({"type": "text", "text": step_result.assistant_text})
-
- for call in step_result.tool_calls:
- assistant_blocks.append(
- {
- "type": "tool_use",
- "id": call.id,
- "name": call.name,
- "input": call.arguments,
- }
- )
-
- self._messages.append({"role": "assistant", "content": assistant_blocks})
-
- tool_result_blocks: List[Dict[str, Any]] = []
- for executed in executed_tool_calls:
- tool_result_blocks.append(
- {
- "type": "tool_result",
- "tool_use_id": executed.tool_call.id,
- "content": json.dumps(executed.result.result),
- "is_error": not executed.result.ok,
- }
- )
-
- self._messages.append({"role": "user", "content": tool_result_blocks})
diff --git a/backend/agentic/streaming/gemini.py b/backend/agentic/streaming/gemini.py
deleted file mode 100644
index ac4f5245..00000000
--- a/backend/agentic/streaming/gemini.py
+++ /dev/null
@@ -1,132 +0,0 @@
-# pyright: reportUnknownVariableType=false
-import uuid
-from typing import Any, Dict, List, cast
-
-from google import genai
-from google.genai import types
-from openai.types.chat import ChatCompletionMessageParam
-
-from agentic.streaming.types import EventSink, ExecutedToolCall, StepResult, StreamEvent
-from agentic.tools import ToolCall
-from llm import Llm
-from agentic.streaming.providers.gemini.transform import (
- convert_message_to_gemini_content,
- get_gemini_api_model_name,
- get_thinking_level_for_model,
-)
-
-
-class GeminiAdapter:
- def __init__(
- self,
- client: genai.Client,
- model: Llm,
- prompt_messages: List[ChatCompletionMessageParam],
- tools: List[types.Tool],
- ):
- self._client = client
- self._model = model
- self._tools = tools
-
- self._system_prompt = str(prompt_messages[0].get("content", ""))
- self._contents: List[types.Content] = [
- convert_message_to_gemini_content(msg) for msg in prompt_messages[1:]
- ]
-
- async def run_step(self, on_event: EventSink) -> StepResult:
- assistant_text = ""
- tool_calls: List[ToolCall] = []
- function_call_parts: List[types.Part] = []
-
- thinking_level = get_thinking_level_for_model(self._model)
- config = types.GenerateContentConfig(
- temperature=0,
- max_output_tokens=30000,
- system_instruction=self._system_prompt,
- thinking_config=types.ThinkingConfig(
- thinking_level=cast(Any, thinking_level),
- include_thoughts=True,
- ),
- tools=self._tools,
- )
-
- api_model_name = get_gemini_api_model_name(self._model)
-
- async for chunk in await self._client.aio.models.generate_content_stream(
- model=api_model_name,
- contents=cast(Any, self._contents),
- config=config,
- ):
- if not chunk.candidates:
- continue
-
- candidate_content = chunk.candidates[0].content
- if not candidate_content or not candidate_content.parts:
- continue
-
- for part in candidate_content.parts:
- if getattr(part, "thought", False) and part.text:
- await on_event(StreamEvent(type="thinking_delta", text=part.text))
- continue
-
- if part.function_call:
- function_call_parts.append(part)
- args = part.function_call.args or {}
- tool_id = part.function_call.id or f"tool-{uuid.uuid4().hex[:6]}"
- tool_name = part.function_call.name or "unknown_tool"
-
- await on_event(
- StreamEvent(
- type="tool_call_delta",
- tool_call_id=tool_id,
- tool_name=tool_name,
- tool_arguments=args,
- )
- )
-
- tool_calls.append(
- ToolCall(
- id=tool_id,
- name=tool_name,
- arguments=args,
- )
- )
- continue
-
- if part.text:
- assistant_text += part.text
- await on_event(StreamEvent(type="assistant_delta", text=part.text))
-
- return StepResult(
- assistant_text=assistant_text,
- tool_calls=tool_calls,
- provider_state={"function_call_parts": function_call_parts},
- )
-
- def apply_tool_results(
- self,
- step_result: StepResult,
- executed_tool_calls: list[ExecutedToolCall],
- ) -> None:
- function_call_parts = cast(
- List[types.Part],
- ((step_result.provider_state or {}).get("function_call_parts") or []),
- )
-
- model_parts: List[Any] = []
- if step_result.assistant_text:
- model_parts.append({"text": step_result.assistant_text}) # type: ignore
- model_parts.extend(function_call_parts)
-
- self._contents.append(types.Content(role="model", parts=model_parts))
-
- tool_result_parts: List[types.Part] = []
- for executed in executed_tool_calls:
- tool_result_parts.append(
- types.Part.from_function_response(
- name=executed.tool_call.name,
- response=executed.result.result,
- )
- )
-
- self._contents.append(types.Content(role="tool", parts=tool_result_parts))
diff --git a/backend/agentic/streaming/openai_responses.py b/backend/agentic/streaming/openai_responses.py
deleted file mode 100644
index 53f4e9e0..00000000
--- a/backend/agentic/streaming/openai_responses.py
+++ /dev/null
@@ -1,345 +0,0 @@
-# pyright: reportUnknownVariableType=false
-import json
-import uuid
-from typing import Any, Dict, List
-
-from openai import AsyncOpenAI
-from openai.types.chat import ChatCompletionMessageParam
-
-from agentic.state import ensure_str
-from agentic.streaming.types import EventSink, ExecutedToolCall, StepResult, StreamEvent
-from agentic.tools import ToolCall, parse_json_arguments
-from llm import Llm, get_openai_api_name, get_openai_reasoning_effort
-
-
-def _convert_message_to_responses_input(
- message: ChatCompletionMessageParam,
-) -> Dict[str, Any]:
- role = message.get("role", "user")
- content = message.get("content", "")
-
- if isinstance(content, str):
- return {"role": role, "content": content}
-
- parts: List[Dict[str, Any]] = []
- if isinstance(content, list):
- for part in content:
- if not isinstance(part, dict):
- continue
- if part.get("type") == "text":
- parts.append({"type": "input_text", "text": part.get("text", "")})
- elif part.get("type") == "image_url":
- image_url = part.get("image_url", {})
- parts.append(
- {
- "type": "input_image",
- "image_url": image_url.get("url", ""),
- "detail": image_url.get("detail", "auto"),
- }
- )
-
- return {"role": role, "content": parts}
-
-
-def _get_event_attr(event: Any, key: str, default: Any = None) -> Any:
- if hasattr(event, key):
- return getattr(event, key)
- if isinstance(event, dict):
- return event.get(key, default)
- return default
-
-
-class OpenAIResponsesAdapter:
- def __init__(
- self,
- client: AsyncOpenAI,
- model: Llm,
- prompt_messages: List[ChatCompletionMessageParam],
- tools: List[Dict[str, Any]],
- ):
- self._client = client
- self._model = model
- self._tools = tools
- self._input_items: List[Dict[str, Any]] = [
- _convert_message_to_responses_input(m) for m in prompt_messages
- ]
-
- async def run_step(self, on_event: EventSink) -> StepResult:
- assistant_text = ""
- tool_calls: Dict[str, Dict[str, Any]] = {}
- item_to_call_id: Dict[str, str] = {}
- output_items_by_index: Dict[int, Dict[str, Any]] = {}
-
- params: Dict[str, Any] = {
- "model": get_openai_api_name(self._model),
- "input": self._input_items,
- "tools": self._tools,
- "tool_choice": "auto",
- "stream": True,
- "max_output_tokens": 30000,
- }
-
- reasoning_effort = get_openai_reasoning_effort(self._model)
- if reasoning_effort:
- params["reasoning"] = {"effort": reasoning_effort}
-
- responses_client = getattr(self._client, "responses", None)
- if responses_client is None:
- raise Exception(
- "OpenAI SDK is too old for GPT-5.2 Codex. Please upgrade the 'openai' package to a version that supports the Responses API."
- )
-
- stream = await responses_client.create(**params) # type: ignore
-
- async for event in stream: # type: ignore
- event_type = _get_event_attr(event, "type")
- if event_type in (
- "response.created",
- "response.completed",
- "response.done",
- "response.output_item.done",
- ):
- if event_type == "response.output_item.done":
- output_index = _get_event_attr(event, "output_index")
- item = _get_event_attr(event, "item")
- if isinstance(output_index, int) and item:
- output_items_by_index[output_index] = item
- continue
-
- if event_type == "response.output_text.delta":
- delta = _get_event_attr(event, "delta", "")
- if delta:
- assistant_text += delta
- await on_event(StreamEvent(type="assistant_delta", text=delta))
- continue
-
- if event_type in (
- "response.reasoning_text.delta",
- "response.reasoning_summary_text.delta",
- ):
- delta = _get_event_attr(event, "delta", "")
- if delta:
- await on_event(StreamEvent(type="thinking_delta", text=delta))
- continue
-
- if event_type in (
- "response.reasoning_summary_part.added",
- "response.reasoning_summary_part.done",
- ):
- part = _get_event_attr(event, "part") or {}
- text = _get_event_attr(part, "text", "")
- if text:
- await on_event(StreamEvent(type="thinking_delta", text=text))
- continue
-
- if event_type == "response.output_item.added":
- item = _get_event_attr(event, "item")
- item_type = _get_event_attr(item, "type") if item else None
- output_index = _get_event_attr(event, "output_index")
- if isinstance(output_index, int) and item:
- output_items_by_index.setdefault(output_index, item)
-
- if item and item_type in ("function_call", "custom_tool_call"):
- item_id = _get_event_attr(item, "id")
- call_id = _get_event_attr(item, "call_id") or item_id
- if item_id and call_id:
- item_to_call_id[item_id] = call_id
- if call_id:
- if item_id and item_id in tool_calls and item_id != call_id:
- existing = tool_calls.pop(item_id)
- tool_calls[call_id] = {
- **existing,
- "id": call_id,
- }
- args_value = _get_event_attr(item, "arguments")
- if args_value is None and item_type == "custom_tool_call":
- args_value = _get_event_attr(item, "input")
- tool_calls.setdefault(
- call_id,
- {
- "id": call_id,
- "name": _get_event_attr(item, "name"),
- "arguments": args_value or "",
- },
- )
- if args_value:
- await on_event(
- StreamEvent(
- type="tool_call_delta",
- tool_call_id=call_id,
- tool_name=_get_event_attr(item, "name"),
- tool_arguments=args_value,
- )
- )
- continue
-
- if event_type in (
- "response.function_call_arguments.delta",
- "response.mcp_call_arguments.delta",
- "response.custom_tool_call_input.delta",
- ):
- item_id = _get_event_attr(event, "item_id")
- call_id = _get_event_attr(event, "call_id")
- if call_id and item_id:
- item_to_call_id[item_id] = call_id
- if not call_id:
- call_id = item_to_call_id.get(item_id) if item_id else None
- if not call_id and item_id:
- call_id = item_id
- if not call_id:
- continue
-
- entry = tool_calls.setdefault(
- call_id,
- {
- "id": call_id,
- "name": _get_event_attr(event, "name"),
- "arguments": "",
- },
- )
- delta_value = _get_event_attr(event, "delta")
- if delta_value is None:
- delta_value = _get_event_attr(event, "input")
- entry["arguments"] += ensure_str(delta_value)
-
- await on_event(
- StreamEvent(
- type="tool_call_delta",
- tool_call_id=call_id,
- tool_name=entry.get("name"),
- tool_arguments=entry.get("arguments"),
- )
- )
- continue
-
- if event_type in (
- "response.function_call_arguments.done",
- "response.mcp_call_arguments.done",
- "response.custom_tool_call_input.done",
- ):
- item_id = _get_event_attr(event, "item_id")
- call_id = _get_event_attr(event, "call_id")
- if call_id and item_id:
- item_to_call_id[item_id] = call_id
- if not call_id:
- call_id = item_to_call_id.get(item_id) if item_id else None
- if not call_id and item_id:
- call_id = item_id
- if not call_id:
- continue
-
- entry = tool_calls.setdefault(
- call_id,
- {
- "id": call_id,
- "name": _get_event_attr(event, "name"),
- "arguments": "",
- },
- )
- final_value = _get_event_attr(event, "arguments")
- if final_value is None:
- final_value = _get_event_attr(event, "input")
- if final_value is None:
- final_value = entry["arguments"]
- entry["arguments"] = final_value
- if _get_event_attr(event, "name"):
- entry["name"] = _get_event_attr(event, "name")
-
- await on_event(
- StreamEvent(
- type="tool_call_delta",
- tool_call_id=call_id,
- tool_name=entry.get("name"),
- tool_arguments=entry.get("arguments"),
- )
- )
-
- output_index = _get_event_attr(event, "output_index")
- if (
- item_id
- and isinstance(output_index, int)
- and isinstance(output_items_by_index.get(output_index), dict)
- ):
- output_items_by_index[output_index] = {
- **output_items_by_index[output_index],
- "arguments": entry["arguments"],
- "call_id": call_id,
- "name": entry.get("name"),
- }
-
- output_items = [
- output_items_by_index[idx]
- for idx in sorted(output_items_by_index.keys())
- if output_items_by_index.get(idx)
- ]
-
- tool_items = [
- item
- for item in output_items
- if isinstance(item, dict)
- and item.get("type") in ("function_call", "custom_tool_call")
- ]
-
- tool_call_list: List[ToolCall] = []
- if tool_items:
- for item in tool_items:
- raw_args = item.get("arguments")
- if raw_args is None and item.get("type") == "custom_tool_call":
- raw_args = item.get("input")
- args, error = parse_json_arguments(raw_args)
- if error:
- args = {"_raw": raw_args}
- call_id = item.get("call_id") or item.get("id")
- tool_call_list.append(
- ToolCall(
- id=call_id or f"call-{uuid.uuid4().hex[:6]}",
- name=item.get("name") or "unknown_tool",
- arguments=args,
- )
- )
- else:
- for entry in tool_calls.values():
- args, error = parse_json_arguments(entry.get("arguments"))
- if error:
- args = {"_raw": entry.get("arguments")}
- call_id = entry.get("id") or entry.get("call_id")
- tool_call_list.append(
- ToolCall(
- id=call_id or f"call-{uuid.uuid4().hex[:6]}",
- name=entry.get("name") or "unknown_tool",
- arguments=args,
- )
- )
-
- provider_state = None
- if tool_call_list:
- provider_state = {
- "output_items": output_items,
- }
-
- return StepResult(
- assistant_text=assistant_text,
- tool_calls=tool_call_list,
- provider_state=provider_state,
- )
-
- def apply_tool_results(
- self,
- step_result: StepResult,
- executed_tool_calls: list[ExecutedToolCall],
- ) -> None:
- provider_state = step_result.provider_state or {}
- output_items = provider_state.get("output_items") or []
-
- tool_output_items: List[Dict[str, Any]] = []
- for executed in executed_tool_calls:
- tool_output_items.append(
- {
- "type": "function_call_output",
- "call_id": executed.tool_call.id,
- "output": json.dumps(executed.result.result),
- }
- )
-
- self._input_items.extend(output_items)
- self._input_items.extend(tool_output_items)
diff --git a/backend/agentic/streaming/providers/anthropic/__init__.py b/backend/agentic/streaming/providers/anthropic/__init__.py
deleted file mode 100644
index d3c93a69..00000000
--- a/backend/agentic/streaming/providers/anthropic/__init__.py
+++ /dev/null
@@ -1,5 +0,0 @@
-from agentic.streaming.providers.anthropic.transform import (
- convert_openai_messages_to_claude,
-)
-
-__all__ = ["convert_openai_messages_to_claude"]
diff --git a/backend/evals/core.py b/backend/evals/core.py
index 0f0e0668..efd3e8b1 100644
--- a/backend/evals/core.py
+++ b/backend/evals/core.py
@@ -5,7 +5,7 @@ from config import (
OPENAI_BASE_URL,
)
from llm import Llm, OPENAI_MODELS, ANTHROPIC_MODELS, GEMINI_MODELS
-from agentic.runner import AgenticRunner
+from agent.runner import AgenticRunner
from prompts import assemble_prompt
from prompts.agentic_instructions import apply_tool_instructions
from prompts.types import Stack
@@ -46,7 +46,7 @@ async def generate_code_core(
if model in OPENAI_MODELS and not OPENAI_API_KEY:
raise Exception("OpenAI API key not found")
- print(f"[EVALS] Using agentic runner for model: {model.value}")
+ print(f"[EVALS] Using agent runner for model: {model.value}")
runner = AgenticRunner(
send_message=send_message,
diff --git a/backend/routes/generate_code.py b/backend/routes/generate_code.py
index 0bbf931a..4db9fc85 100644
--- a/backend/routes/generate_code.py
+++ b/backend/routes/generate_code.py
@@ -56,7 +56,7 @@ MessageType = Literal[
from prompts import create_prompt
from prompts.agentic_instructions import apply_tool_instructions
from prompts.types import Stack, PromptContent
-from agentic.runner import AgenticRunner
+from agent.runner import AgenticRunner
# from utils import pprint_prompt
from ws.constants import APP_ERROR_WEB_SOCKET_CODE # type: ignore
@@ -306,7 +306,7 @@ class ParameterExtractionStage:
# Extract imported code flag
is_imported_from_code = bool(params.get("isImportedFromCode", False))
- # Extract file state for agentic edits
+ # Extract file state for agent edits
raw_file_state = params.get("fileState")
file_state: Dict[str, str] | None = None
if isinstance(raw_file_state, dict):
@@ -563,7 +563,7 @@ class PostProcessingStage:
class AgenticGenerationStage:
- """Handles agentic tool-calling generation for each variant."""
+ """Handles agent tool-calling generation for each variant."""
def __init__(
self,
diff --git a/backend/tests/test_prompts.py b/backend/tests/test_prompts.py
index c417d29b..f009182b 100644
--- a/backend/tests/test_prompts.py
+++ b/backend/tests/test_prompts.py
@@ -323,7 +323,7 @@ class TestCreatePrompt:
For video mode with generation_type="create", we now assemble
a regular system+user prompt so video generation can run through
- the agentic runner path.
+ the agent runner path.
"""
# Setup test data
video_data_url: str = "data:video/mp4;base64,test_video_data"
diff --git a/design-docs/agentic-runner-refactor.md b/design-docs/agentic-runner-refactor.md
index cb173452..eb737d8b 100644
--- a/design-docs/agentic-runner-refactor.md
+++ b/design-docs/agentic-runner-refactor.md
@@ -3,7 +3,7 @@
## Goals
- Reduce duplicated streaming logic across OpenAI/Anthropic/Gemini runners.
- Centralize tool schemas and telemetry formatting.
-- Make the agentic pipeline easier to test, extend, and reason about.
+- Make the agent pipeline easier to test, extend, and reason about.
## Decision: Unified Stream Loop + Provider Adapters
- Introduce a provider-agnostic stream loop that consumes normalized events
@@ -23,7 +23,7 @@
## Planned Removals
### Image Cache
-- Remove prompt-to-URL image caching in the agentic tool layer.
+- Remove prompt-to-URL image caching in the agent tool layer.
- Rationale: simplify state, reduce hidden cross-variant coupling.
- Follow-up: ensure image generation remains deterministic per request when needed
(e.g., pass explicit seeds or expose caching at a higher layer if required).
@@ -34,19 +34,19 @@
- Update model lists and runtime checks to eliminate the ChatCompletion branch.
### Non-Agentic Generation Paths (e.g., Video)
-Keep video generation, but route it through the agentic runner:
-- Replace video-specific streaming helpers with agentic runner support for video inputs.
-- Remove conditional branches that bypass the agentic path for video create/update.
+Keep video generation, but route it through the agent runner:
+- Replace video-specific streaming helpers with agent runner support for video inputs.
+- Remove conditional branches that bypass the agent path for video create/update.
- Preserve video-specific prompt and media handling, but integrate it into the
- agentic tool/stream pipeline.
-- Update tests and docs to reflect a single agentic generation path that
+ agent tool/stream pipeline.
+- Update tests and docs to reflect a single agent generation path that
supports video inputs.
## File/Module Split
-- `agentic/runner.py`: orchestration + shared stream loop.
-- `agentic/streaming/`: provider adapters (openai, responses, anthropic, gemini).
-- `agentic/tools.py`: tool definitions, serialization, and execution.
-- `agentic/state.py`: file state + seeding utilities.
+- `agent/runner.py`: orchestration + shared stream loop.
+- `agent/streaming/`: provider adapters (openai, responses, anthropic, gemini).
+- `agent/tools.py`: tool definitions, serialization, and execution.
+- `agent/state.py`: file state + seeding utilities.
## Non-Goals
- No functional UX changes beyond the removal items above.