lite-agent 0.3.0__py3-none-any.whl → 0.4.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of lite-agent might be problematic. Click here for more details.
- lite_agent/__init__.py +2 -2
- lite_agent/agent.py +178 -68
- lite_agent/chat_display.py +779 -0
- lite_agent/client.py +36 -1
- lite_agent/message_transfers.py +9 -1
- lite_agent/processors/__init__.py +3 -2
- lite_agent/processors/completion_event_processor.py +306 -0
- lite_agent/processors/response_event_processor.py +205 -0
- lite_agent/runner.py +413 -230
- lite_agent/stream_handlers/__init__.py +3 -2
- lite_agent/stream_handlers/litellm.py +37 -68
- lite_agent/types/__init__.py +77 -23
- lite_agent/types/events.py +119 -0
- lite_agent/types/messages.py +256 -48
- {lite_agent-0.3.0.dist-info → lite_agent-0.4.0.dist-info}/METADATA +2 -2
- lite_agent-0.4.0.dist-info/RECORD +23 -0
- lite_agent/processors/stream_chunk_processor.py +0 -106
- lite_agent/rich_helpers.py +0 -503
- lite_agent/types/chunks.py +0 -89
- lite_agent-0.3.0.dist-info/RECORD +0 -22
- {lite_agent-0.3.0.dist-info → lite_agent-0.4.0.dist-info}/WHEEL +0 -0
lite_agent/runner.py
CHANGED
|
@@ -1,45 +1,115 @@
|
|
|
1
1
|
import json
|
|
2
2
|
from collections.abc import AsyncGenerator, Sequence
|
|
3
|
+
from datetime import datetime, timedelta, timezone
|
|
3
4
|
from os import PathLike
|
|
4
5
|
from pathlib import Path
|
|
5
|
-
from typing import
|
|
6
|
+
from typing import Any, Literal
|
|
6
7
|
|
|
7
8
|
from lite_agent.agent import Agent
|
|
8
9
|
from lite_agent.loggers import logger
|
|
9
10
|
from lite_agent.types import (
|
|
10
|
-
AgentAssistantMessage,
|
|
11
11
|
AgentChunk,
|
|
12
12
|
AgentChunkType,
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
13
|
+
AssistantMessageContent,
|
|
14
|
+
AssistantMessageMeta,
|
|
15
|
+
AssistantTextContent,
|
|
16
|
+
AssistantToolCall,
|
|
17
|
+
AssistantToolCallResult,
|
|
17
18
|
FlexibleRunnerMessage,
|
|
18
19
|
MessageDict,
|
|
19
|
-
|
|
20
|
+
MessageUsage,
|
|
21
|
+
NewAssistantMessage,
|
|
22
|
+
NewMessage,
|
|
23
|
+
NewSystemMessage,
|
|
24
|
+
# New structured message types
|
|
25
|
+
NewUserMessage,
|
|
20
26
|
ToolCall,
|
|
21
27
|
ToolCallFunction,
|
|
28
|
+
UserImageContent,
|
|
22
29
|
UserInput,
|
|
30
|
+
UserMessageContent,
|
|
31
|
+
UserTextContent,
|
|
23
32
|
)
|
|
24
33
|
|
|
25
|
-
if TYPE_CHECKING:
|
|
26
|
-
from lite_agent.types import AssistantMessage
|
|
27
|
-
|
|
28
34
|
DEFAULT_INCLUDES: tuple[AgentChunkType, ...] = (
|
|
29
35
|
"completion_raw",
|
|
30
36
|
"usage",
|
|
31
|
-
"
|
|
32
|
-
"
|
|
33
|
-
"tool_call_result",
|
|
37
|
+
"function_call",
|
|
38
|
+
"function_call_output",
|
|
34
39
|
"content_delta",
|
|
35
|
-
"
|
|
40
|
+
"function_call_delta",
|
|
41
|
+
"assistant_message",
|
|
36
42
|
)
|
|
37
43
|
|
|
38
44
|
|
|
39
45
|
class Runner:
|
|
40
|
-
def __init__(self, agent: Agent) -> None:
|
|
46
|
+
def __init__(self, agent: Agent, api: Literal["completion", "responses"] = "responses") -> None:
|
|
41
47
|
self.agent = agent
|
|
42
|
-
self.messages: list[
|
|
48
|
+
self.messages: list[NewMessage] = []
|
|
49
|
+
self.api = api
|
|
50
|
+
self._current_assistant_message: NewAssistantMessage | None = None
|
|
51
|
+
|
|
52
|
+
@property
|
|
53
|
+
def legacy_messages(self) -> list[NewMessage]:
|
|
54
|
+
"""Return messages in new format (legacy_messages is now an alias)."""
|
|
55
|
+
return self.messages
|
|
56
|
+
|
|
57
|
+
def _start_assistant_message(self, content: str = "", meta: AssistantMessageMeta | None = None) -> None:
|
|
58
|
+
"""Start a new assistant message."""
|
|
59
|
+
if meta is None:
|
|
60
|
+
meta = AssistantMessageMeta()
|
|
61
|
+
|
|
62
|
+
# Always add text content, even if empty (we can update it later)
|
|
63
|
+
assistant_content_items: list[AssistantMessageContent] = [AssistantTextContent(text=content)]
|
|
64
|
+
self._current_assistant_message = NewAssistantMessage(
|
|
65
|
+
content=assistant_content_items,
|
|
66
|
+
meta=meta,
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
def _add_to_current_assistant_message(self, content_item: AssistantTextContent | AssistantToolCall | AssistantToolCallResult) -> None:
|
|
70
|
+
"""Add content to the current assistant message."""
|
|
71
|
+
if self._current_assistant_message is None:
|
|
72
|
+
self._start_assistant_message()
|
|
73
|
+
|
|
74
|
+
if self._current_assistant_message is not None:
|
|
75
|
+
self._current_assistant_message.content.append(content_item)
|
|
76
|
+
|
|
77
|
+
def _add_text_content_to_current_assistant_message(self, delta: str) -> None:
|
|
78
|
+
"""Add text delta to the current assistant message's text content."""
|
|
79
|
+
if self._current_assistant_message is None:
|
|
80
|
+
self._start_assistant_message()
|
|
81
|
+
|
|
82
|
+
if self._current_assistant_message is not None:
|
|
83
|
+
# Find the first text content item and append the delta
|
|
84
|
+
for content_item in self._current_assistant_message.content:
|
|
85
|
+
if content_item.type == "text":
|
|
86
|
+
content_item.text += delta
|
|
87
|
+
return
|
|
88
|
+
# If no text content found, add new text content
|
|
89
|
+
new_content = AssistantTextContent(text=delta)
|
|
90
|
+
self._current_assistant_message.content.append(new_content)
|
|
91
|
+
|
|
92
|
+
def _finalize_assistant_message(self) -> None:
|
|
93
|
+
"""Finalize the current assistant message and add it to messages."""
|
|
94
|
+
if self._current_assistant_message is not None:
|
|
95
|
+
self.messages.append(self._current_assistant_message)
|
|
96
|
+
self._current_assistant_message = None
|
|
97
|
+
|
|
98
|
+
def _add_tool_call_result(self, call_id: str, output: str, execution_time_ms: int | None = None) -> None:
|
|
99
|
+
"""Add a tool call result to the last assistant message, or create a new one if needed."""
|
|
100
|
+
result = AssistantToolCallResult(
|
|
101
|
+
call_id=call_id,
|
|
102
|
+
output=output,
|
|
103
|
+
execution_time_ms=execution_time_ms,
|
|
104
|
+
)
|
|
105
|
+
|
|
106
|
+
if self.messages and isinstance(self.messages[-1], NewAssistantMessage):
|
|
107
|
+
# Add to existing assistant message
|
|
108
|
+
self.messages[-1].content.append(result)
|
|
109
|
+
else:
|
|
110
|
+
# Create new assistant message with just the tool result
|
|
111
|
+
assistant_message = NewAssistantMessage(content=[result])
|
|
112
|
+
self.messages.append(assistant_message)
|
|
43
113
|
|
|
44
114
|
def _normalize_includes(self, includes: Sequence[AgentChunkType] | None) -> Sequence[AgentChunkType]:
|
|
45
115
|
"""Normalize includes parameter to default if None."""
|
|
@@ -49,7 +119,7 @@ class Runner:
|
|
|
49
119
|
"""Normalize record_to parameter to Path object if provided."""
|
|
50
120
|
return Path(record_to) if record_to else None
|
|
51
121
|
|
|
52
|
-
async def _handle_tool_calls(self, tool_calls: "Sequence[ToolCall] | None", includes: Sequence[AgentChunkType], context: "Any | None" = None) -> AsyncGenerator[AgentChunk, None]: # noqa: ANN401
|
|
122
|
+
async def _handle_tool_calls(self, tool_calls: "Sequence[ToolCall] | None", includes: Sequence[AgentChunkType], context: "Any | None" = None) -> AsyncGenerator[AgentChunk, None]: # noqa: ANN401
|
|
53
123
|
"""Handle tool calls and yield appropriate chunks."""
|
|
54
124
|
if not tool_calls:
|
|
55
125
|
return
|
|
@@ -64,12 +134,9 @@ class Runner:
|
|
|
64
134
|
await self._handle_agent_transfer(tool_call, includes)
|
|
65
135
|
else:
|
|
66
136
|
# Add response for additional transfer calls without executing them
|
|
67
|
-
self.
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
call_id=tool_call.id,
|
|
71
|
-
output="Transfer already executed by previous call",
|
|
72
|
-
),
|
|
137
|
+
self._add_tool_call_result(
|
|
138
|
+
call_id=tool_call.id,
|
|
139
|
+
output="Transfer already executed by previous call",
|
|
73
140
|
)
|
|
74
141
|
return # Stop processing other tool calls after transfer
|
|
75
142
|
|
|
@@ -82,29 +149,26 @@ class Runner:
|
|
|
82
149
|
await self._handle_parent_transfer(tool_call, includes)
|
|
83
150
|
else:
|
|
84
151
|
# Add response for additional transfer calls without executing them
|
|
85
|
-
self.
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
call_id=tool_call.id,
|
|
89
|
-
output="Transfer already executed by previous call",
|
|
90
|
-
),
|
|
152
|
+
self._add_tool_call_result(
|
|
153
|
+
call_id=tool_call.id,
|
|
154
|
+
output="Transfer already executed by previous call",
|
|
91
155
|
)
|
|
92
156
|
return # Stop processing other tool calls after transfer
|
|
93
157
|
|
|
94
158
|
async for tool_call_chunk in self.agent.handle_tool_calls(tool_calls, context=context):
|
|
95
|
-
if tool_call_chunk.type == "
|
|
96
|
-
|
|
97
|
-
if tool_call_chunk.type == "
|
|
159
|
+
# if tool_call_chunk.type == "function_call" and tool_call_chunk.type in includes:
|
|
160
|
+
# yield tool_call_chunk
|
|
161
|
+
if tool_call_chunk.type == "function_call_output":
|
|
98
162
|
if tool_call_chunk.type in includes:
|
|
99
163
|
yield tool_call_chunk
|
|
100
|
-
#
|
|
101
|
-
self.messages.
|
|
102
|
-
|
|
103
|
-
type="function_call_output",
|
|
164
|
+
# Add tool result to the last assistant message
|
|
165
|
+
if self.messages and isinstance(self.messages[-1], NewAssistantMessage):
|
|
166
|
+
tool_result = AssistantToolCallResult(
|
|
104
167
|
call_id=tool_call_chunk.tool_call_id,
|
|
105
168
|
output=tool_call_chunk.content,
|
|
106
|
-
|
|
107
|
-
|
|
169
|
+
execution_time_ms=tool_call_chunk.execution_time_ms,
|
|
170
|
+
)
|
|
171
|
+
self.messages[-1].content.append(tool_result)
|
|
108
172
|
|
|
109
173
|
async def _collect_all_chunks(self, stream: AsyncGenerator[AgentChunk, None]) -> list[AgentChunk]:
|
|
110
174
|
"""Collect all chunks from an async generator into a list."""
|
|
@@ -121,7 +185,8 @@ class Runner:
|
|
|
121
185
|
"""Run the agent and return a RunResponse object that can be asynchronously iterated for each chunk."""
|
|
122
186
|
includes = self._normalize_includes(includes)
|
|
123
187
|
if isinstance(user_input, str):
|
|
124
|
-
|
|
188
|
+
user_message = NewUserMessage(content=[UserTextContent(text=user_input)])
|
|
189
|
+
self.messages.append(user_message)
|
|
125
190
|
elif isinstance(user_input, (list, tuple)):
|
|
126
191
|
# Handle sequence of messages
|
|
127
192
|
for message in user_input:
|
|
@@ -132,7 +197,7 @@ class Runner:
|
|
|
132
197
|
self.append_message(user_input) # type: ignore[arg-type]
|
|
133
198
|
return self._run(max_steps, includes, self._normalize_record_path(record_to), context=context)
|
|
134
199
|
|
|
135
|
-
async def _run(self, max_steps: int, includes: Sequence[AgentChunkType], record_to: Path | None = None, context:
|
|
200
|
+
async def _run(self, max_steps: int, includes: Sequence[AgentChunkType], record_to: Path | None = None, context: Any | None = None) -> AsyncGenerator[AgentChunk, None]: # noqa: ANN401
|
|
136
201
|
"""Run the agent and return a RunResponse object that can be asynchronously iterated for each chunk."""
|
|
137
202
|
logger.debug(f"Running agent with messages: {self.messages}")
|
|
138
203
|
steps = 0
|
|
@@ -143,34 +208,111 @@ class Runner:
|
|
|
143
208
|
|
|
144
209
|
def is_finish() -> bool:
|
|
145
210
|
if completion_condition == "call":
|
|
146
|
-
|
|
147
|
-
|
|
211
|
+
# Check if wait_for_user was called in the last assistant message
|
|
212
|
+
if self.messages and isinstance(self.messages[-1], NewAssistantMessage):
|
|
213
|
+
for content_item in self.messages[-1].content:
|
|
214
|
+
if content_item.type == "tool_call_result" and self._get_tool_call_name_by_id(content_item.call_id) == "wait_for_user":
|
|
215
|
+
return True
|
|
216
|
+
return False
|
|
148
217
|
return finish_reason == "stop"
|
|
149
218
|
|
|
150
219
|
while not is_finish() and steps < max_steps:
|
|
151
|
-
|
|
220
|
+
logger.debug(f"Step {steps}: finish_reason={finish_reason}, is_finish()={is_finish()}")
|
|
221
|
+
# Convert to legacy format only when needed for LLM communication
|
|
222
|
+
# This allows us to keep the new format internally but ensures compatibility
|
|
223
|
+
match self.api:
|
|
224
|
+
case "completion":
|
|
225
|
+
resp = await self.agent.completion(self.messages, record_to_file=record_to)
|
|
226
|
+
case "responses":
|
|
227
|
+
resp = await self.agent.responses(self.messages, record_to_file=record_to)
|
|
228
|
+
case _:
|
|
229
|
+
msg = f"Unknown API type: {self.api}"
|
|
230
|
+
raise ValueError(msg)
|
|
152
231
|
async for chunk in resp:
|
|
153
232
|
if chunk.type in includes:
|
|
154
233
|
yield chunk
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
234
|
+
if chunk.type == "assistant_message":
|
|
235
|
+
# Start or update assistant message in new format
|
|
236
|
+
meta = AssistantMessageMeta(
|
|
237
|
+
sent_at=chunk.message.meta.sent_at,
|
|
238
|
+
latency_ms=getattr(chunk.message.meta, "latency_ms", None),
|
|
239
|
+
total_time_ms=getattr(chunk.message.meta, "output_time_ms", None),
|
|
240
|
+
)
|
|
241
|
+
# If we already have a current assistant message, just update its metadata
|
|
242
|
+
if self._current_assistant_message is not None:
|
|
243
|
+
self._current_assistant_message.meta = meta
|
|
244
|
+
else:
|
|
245
|
+
# Extract text content from the new message format
|
|
246
|
+
text_content = ""
|
|
247
|
+
if chunk.message.content:
|
|
248
|
+
for item in chunk.message.content:
|
|
249
|
+
if hasattr(item, "type") and item.type == "text":
|
|
250
|
+
text_content = item.text
|
|
251
|
+
break
|
|
252
|
+
self._start_assistant_message(text_content, meta)
|
|
253
|
+
if chunk.type == "content_delta":
|
|
254
|
+
# Accumulate text content to current assistant message
|
|
255
|
+
self._add_text_content_to_current_assistant_message(chunk.delta)
|
|
256
|
+
if chunk.type == "function_call":
|
|
257
|
+
# Add tool call to current assistant message
|
|
258
|
+
# Keep arguments as string for compatibility with funcall library
|
|
259
|
+
tool_call = AssistantToolCall(
|
|
260
|
+
call_id=chunk.call_id,
|
|
261
|
+
name=chunk.name,
|
|
262
|
+
arguments=chunk.arguments or "{}",
|
|
263
|
+
)
|
|
264
|
+
self._add_to_current_assistant_message(tool_call)
|
|
265
|
+
if chunk.type == "usage":
|
|
266
|
+
# Update the last assistant message with usage data and output_time_ms
|
|
267
|
+
usage_time = datetime.now(timezone.utc)
|
|
268
|
+
for i in range(len(self.messages) - 1, -1, -1):
|
|
269
|
+
current_message = self.messages[i]
|
|
270
|
+
if isinstance(current_message, NewAssistantMessage):
|
|
271
|
+
# Update usage information
|
|
272
|
+
if current_message.meta.usage is None:
|
|
273
|
+
current_message.meta.usage = MessageUsage()
|
|
274
|
+
current_message.meta.usage.input_tokens = chunk.usage.input_tokens
|
|
275
|
+
current_message.meta.usage.output_tokens = chunk.usage.output_tokens
|
|
276
|
+
current_message.meta.usage.total_tokens = (chunk.usage.input_tokens or 0) + (chunk.usage.output_tokens or 0)
|
|
277
|
+
|
|
278
|
+
# Calculate output_time_ms if latency_ms is available
|
|
279
|
+
if current_message.meta.latency_ms is not None:
|
|
280
|
+
# We need to calculate from first output to usage time
|
|
281
|
+
# We'll calculate: usage_time - (sent_at - latency_ms)
|
|
282
|
+
# This gives us the time from first output to usage completion
|
|
283
|
+
# sent_at is when the message was completed, so sent_at - latency_ms approximates first output time
|
|
284
|
+
first_output_time_approx = current_message.meta.sent_at - timedelta(milliseconds=current_message.meta.latency_ms)
|
|
285
|
+
output_time_ms = int((usage_time - first_output_time_approx).total_seconds() * 1000)
|
|
286
|
+
current_message.meta.total_time_ms = max(0, output_time_ms)
|
|
287
|
+
break
|
|
288
|
+
|
|
289
|
+
# Finalize assistant message so it can be found in pending function calls
|
|
290
|
+
self._finalize_assistant_message()
|
|
291
|
+
|
|
292
|
+
# Check for pending tool calls after processing current assistant message
|
|
293
|
+
pending_tool_calls = self._find_pending_tool_calls()
|
|
294
|
+
logger.debug(f"Found {len(pending_tool_calls)} pending tool calls")
|
|
295
|
+
if pending_tool_calls:
|
|
296
|
+
# Convert to ToolCall format for existing handler
|
|
297
|
+
tool_calls = self._convert_tool_calls_to_tool_calls(pending_tool_calls)
|
|
298
|
+
require_confirm_tools = await self.agent.list_require_confirm_tools(tool_calls)
|
|
299
|
+
if require_confirm_tools:
|
|
300
|
+
return
|
|
301
|
+
async for tool_chunk in self._handle_tool_calls(tool_calls, includes, context=context):
|
|
302
|
+
yield tool_chunk
|
|
303
|
+
finish_reason = "tool_calls"
|
|
304
|
+
else:
|
|
305
|
+
finish_reason = "stop"
|
|
172
306
|
steps += 1
|
|
173
307
|
|
|
308
|
+
async def has_require_confirm_tools(self):
|
|
309
|
+
pending_tool_calls = self._find_pending_tool_calls()
|
|
310
|
+
if not pending_tool_calls:
|
|
311
|
+
return False
|
|
312
|
+
tool_calls = self._convert_tool_calls_to_tool_calls(pending_tool_calls)
|
|
313
|
+
require_confirm_tools = await self.agent.list_require_confirm_tools(tool_calls)
|
|
314
|
+
return bool(require_confirm_tools)
|
|
315
|
+
|
|
174
316
|
async def run_continue_until_complete(
|
|
175
317
|
self,
|
|
176
318
|
max_steps: int = 20,
|
|
@@ -199,11 +341,11 @@ class Runner:
|
|
|
199
341
|
"""Continue running the agent and return a RunResponse object that can be asynchronously iterated for each chunk."""
|
|
200
342
|
includes = self._normalize_includes(includes)
|
|
201
343
|
|
|
202
|
-
# Find pending
|
|
203
|
-
|
|
204
|
-
if
|
|
344
|
+
# Find pending tool calls in responses format
|
|
345
|
+
pending_tool_calls = self._find_pending_tool_calls()
|
|
346
|
+
if pending_tool_calls:
|
|
205
347
|
# Convert to ToolCall format for existing handler
|
|
206
|
-
tool_calls = self.
|
|
348
|
+
tool_calls = self._convert_tool_calls_to_tool_calls(pending_tool_calls)
|
|
207
349
|
async for tool_chunk in self._handle_tool_calls(tool_calls, includes, context=context):
|
|
208
350
|
yield tool_chunk
|
|
209
351
|
async for chunk in self._run(max_steps, includes, self._normalize_record_path(record_to)):
|
|
@@ -216,7 +358,7 @@ class Runner:
|
|
|
216
358
|
raise ValueError(msg)
|
|
217
359
|
|
|
218
360
|
last_message = self.messages[-1]
|
|
219
|
-
if not (isinstance(last_message,
|
|
361
|
+
if not (isinstance(last_message, NewAssistantMessage) or (hasattr(last_message, "role") and getattr(last_message, "role", None) == "assistant")):
|
|
220
362
|
msg = "Cannot continue running without a valid last message from the assistant."
|
|
221
363
|
raise ValueError(msg)
|
|
222
364
|
|
|
@@ -235,73 +377,58 @@ class Runner:
|
|
|
235
377
|
resp = self.run(user_input, max_steps, includes, record_to=record_to)
|
|
236
378
|
return await self._collect_all_chunks(resp)
|
|
237
379
|
|
|
238
|
-
|
|
239
|
-
"""
|
|
240
|
-
#
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
type="function_call",
|
|
255
|
-
function_call_id=tool_call.id,
|
|
256
|
-
name=tool_call.function.name,
|
|
257
|
-
arguments=tool_call.function.arguments or "",
|
|
258
|
-
content="",
|
|
259
|
-
)
|
|
260
|
-
self.messages.append(function_call_msg)
|
|
261
|
-
else:
|
|
262
|
-
# Regular assistant message without tool calls
|
|
263
|
-
assistant_msg = AgentAssistantMessage(
|
|
264
|
-
role="assistant",
|
|
265
|
-
content=message.content,
|
|
266
|
-
)
|
|
267
|
-
self.messages.append(assistant_msg)
|
|
268
|
-
|
|
269
|
-
def _find_pending_function_calls(self) -> list:
|
|
270
|
-
"""Find function call messages that don't have corresponding outputs yet."""
|
|
271
|
-
function_calls: list[AgentFunctionToolCallMessage] = []
|
|
272
|
-
function_call_ids = set()
|
|
273
|
-
|
|
274
|
-
# Collect all function call messages
|
|
275
|
-
for msg in reversed(self.messages):
|
|
276
|
-
if isinstance(msg, AgentFunctionToolCallMessage):
|
|
277
|
-
function_calls.append(msg)
|
|
278
|
-
function_call_ids.add(msg.function_call_id)
|
|
279
|
-
elif isinstance(msg, AgentFunctionCallOutput):
|
|
280
|
-
# Remove the corresponding function call from our list
|
|
281
|
-
function_call_ids.discard(msg.call_id)
|
|
282
|
-
elif isinstance(msg, AgentAssistantMessage):
|
|
283
|
-
# Stop when we hit the assistant message that initiated these calls
|
|
284
|
-
break
|
|
380
|
+
def _find_pending_tool_calls(self) -> list[AssistantToolCall]:
|
|
381
|
+
"""Find tool calls that don't have corresponding results yet."""
|
|
382
|
+
# Find pending calls directly in new format messages
|
|
383
|
+
pending_calls: list[AssistantToolCall] = []
|
|
384
|
+
|
|
385
|
+
# Look at the last assistant message for pending tool calls
|
|
386
|
+
if not self.messages:
|
|
387
|
+
return pending_calls
|
|
388
|
+
|
|
389
|
+
last_message = self.messages[-1]
|
|
390
|
+
if not isinstance(last_message, NewAssistantMessage):
|
|
391
|
+
return pending_calls
|
|
392
|
+
|
|
393
|
+
# Collect tool calls and results from the last assistant message
|
|
394
|
+
tool_calls = {}
|
|
395
|
+
tool_results = set()
|
|
285
396
|
|
|
286
|
-
|
|
287
|
-
|
|
397
|
+
for content_item in last_message.content:
|
|
398
|
+
if content_item.type == "tool_call":
|
|
399
|
+
tool_calls[content_item.call_id] = content_item
|
|
400
|
+
elif content_item.type == "tool_call_result":
|
|
401
|
+
tool_results.add(content_item.call_id)
|
|
288
402
|
|
|
289
|
-
|
|
290
|
-
|
|
403
|
+
# Return tool calls that don't have corresponding results
|
|
404
|
+
return [call for call_id, call in tool_calls.items() if call_id not in tool_results]
|
|
291
405
|
|
|
292
|
-
|
|
293
|
-
for
|
|
406
|
+
def _get_tool_call_name_by_id(self, call_id: str) -> str | None:
|
|
407
|
+
"""Get the tool name for a given call_id from the last assistant message."""
|
|
408
|
+
if not self.messages or not isinstance(self.messages[-1], NewAssistantMessage):
|
|
409
|
+
return None
|
|
410
|
+
|
|
411
|
+
for content_item in self.messages[-1].content:
|
|
412
|
+
if content_item.type == "tool_call" and content_item.call_id == call_id:
|
|
413
|
+
return content_item.name
|
|
414
|
+
return None
|
|
415
|
+
|
|
416
|
+
def _convert_tool_calls_to_tool_calls(self, tool_calls: list[AssistantToolCall]) -> list[ToolCall]:
|
|
417
|
+
"""Convert AssistantToolCall objects to ToolCall objects for compatibility."""
|
|
418
|
+
|
|
419
|
+
result_tool_calls = []
|
|
420
|
+
for tc in tool_calls:
|
|
294
421
|
tool_call = ToolCall(
|
|
295
|
-
id=
|
|
422
|
+
id=tc.call_id,
|
|
296
423
|
type="function",
|
|
297
424
|
function=ToolCallFunction(
|
|
298
|
-
name=
|
|
299
|
-
arguments=
|
|
425
|
+
name=tc.name,
|
|
426
|
+
arguments=tc.arguments if isinstance(tc.arguments, str) else str(tc.arguments),
|
|
300
427
|
),
|
|
301
|
-
index=len(
|
|
428
|
+
index=len(result_tool_calls),
|
|
302
429
|
)
|
|
303
|
-
|
|
304
|
-
return
|
|
430
|
+
result_tool_calls.append(tool_call)
|
|
431
|
+
return result_tool_calls
|
|
305
432
|
|
|
306
433
|
def set_chat_history(self, messages: Sequence[FlexibleRunnerMessage], root_agent: Agent | None = None) -> None:
|
|
307
434
|
"""Set the entire chat history and track the current agent based on function calls.
|
|
@@ -344,10 +471,20 @@ class Runner:
|
|
|
344
471
|
"""
|
|
345
472
|
if isinstance(message, dict):
|
|
346
473
|
return self._track_transfer_from_dict_message(message, current_agent)
|
|
474
|
+
if isinstance(message, NewAssistantMessage):
|
|
475
|
+
return self._track_transfer_from_new_assistant_message(message, current_agent)
|
|
347
476
|
|
|
348
|
-
|
|
349
|
-
return self._track_transfer_from_function_call_message(message, current_agent)
|
|
477
|
+
return current_agent
|
|
350
478
|
|
|
479
|
+
def _track_transfer_from_new_assistant_message(self, message: NewAssistantMessage, current_agent: Agent) -> Agent:
|
|
480
|
+
"""Track transfers from NewAssistantMessage objects."""
|
|
481
|
+
for content_item in message.content:
|
|
482
|
+
if content_item.type == "tool_call":
|
|
483
|
+
if content_item.name == "transfer_to_agent":
|
|
484
|
+
arguments = content_item.arguments if isinstance(content_item.arguments, str) else str(content_item.arguments)
|
|
485
|
+
return self._handle_transfer_to_agent_tracking(arguments, current_agent)
|
|
486
|
+
if content_item.name == "transfer_to_parent":
|
|
487
|
+
return self._handle_transfer_to_parent_tracking(current_agent)
|
|
351
488
|
return current_agent
|
|
352
489
|
|
|
353
490
|
def _track_transfer_from_dict_message(self, message: dict[str, Any] | MessageDict, current_agent: Agent) -> Agent:
|
|
@@ -365,16 +502,6 @@ class Runner:
|
|
|
365
502
|
|
|
366
503
|
return current_agent
|
|
367
504
|
|
|
368
|
-
def _track_transfer_from_function_call_message(self, message: AgentFunctionToolCallMessage, current_agent: Agent) -> Agent:
|
|
369
|
-
"""Track transfers from AgentFunctionToolCallMessage objects."""
|
|
370
|
-
if message.name == "transfer_to_agent":
|
|
371
|
-
return self._handle_transfer_to_agent_tracking(message.arguments, current_agent)
|
|
372
|
-
|
|
373
|
-
if message.name == "transfer_to_parent":
|
|
374
|
-
return self._handle_transfer_to_parent_tracking(current_agent)
|
|
375
|
-
|
|
376
|
-
return current_agent
|
|
377
|
-
|
|
378
505
|
def _handle_transfer_to_agent_tracking(self, arguments: str | dict, current_agent: Agent) -> Agent:
|
|
379
506
|
"""Handle transfer_to_agent function call tracking."""
|
|
380
507
|
try:
|
|
@@ -431,55 +558,138 @@ class Runner:
|
|
|
431
558
|
return None
|
|
432
559
|
|
|
433
560
|
def append_message(self, message: FlexibleRunnerMessage) -> None:
|
|
434
|
-
if isinstance(message,
|
|
561
|
+
if isinstance(message, NewMessage):
|
|
562
|
+
# Already in new format
|
|
435
563
|
self.messages.append(message)
|
|
436
564
|
elif isinstance(message, dict):
|
|
437
|
-
# Handle different message types
|
|
565
|
+
# Handle different message types from dict
|
|
438
566
|
message_type = message.get("type")
|
|
439
567
|
role = message.get("role")
|
|
440
568
|
|
|
441
|
-
if
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
569
|
+
if role == "user":
|
|
570
|
+
content = message.get("content", "")
|
|
571
|
+
if isinstance(content, str):
|
|
572
|
+
user_message = NewUserMessage(content=[UserTextContent(text=content)])
|
|
573
|
+
elif isinstance(content, list):
|
|
574
|
+
# Handle complex content array
|
|
575
|
+
user_content_items: list[UserMessageContent] = []
|
|
576
|
+
for item in content:
|
|
577
|
+
if isinstance(item, dict):
|
|
578
|
+
item_type = item.get("type")
|
|
579
|
+
if item_type in {"input_text", "text"}:
|
|
580
|
+
user_content_items.append(UserTextContent(text=item.get("text", "")))
|
|
581
|
+
elif item_type in {"input_image", "image_url"}:
|
|
582
|
+
if item_type == "image_url":
|
|
583
|
+
# Handle completion API format
|
|
584
|
+
image_url = item.get("image_url", {})
|
|
585
|
+
url = image_url.get("url", "") if isinstance(image_url, dict) else str(image_url)
|
|
586
|
+
user_content_items.append(UserImageContent(image_url=url))
|
|
587
|
+
else:
|
|
588
|
+
# Handle response API format
|
|
589
|
+
user_content_items.append(
|
|
590
|
+
UserImageContent(
|
|
591
|
+
image_url=item.get("image_url"),
|
|
592
|
+
file_id=item.get("file_id"),
|
|
593
|
+
detail=item.get("detail", "auto"),
|
|
594
|
+
),
|
|
595
|
+
)
|
|
596
|
+
elif hasattr(item, "type"):
|
|
597
|
+
# Handle Pydantic models
|
|
598
|
+
if item.type == "input_text":
|
|
599
|
+
user_content_items.append(UserTextContent(text=item.text))
|
|
600
|
+
elif item.type == "input_image":
|
|
601
|
+
user_content_items.append(
|
|
602
|
+
UserImageContent(
|
|
603
|
+
image_url=getattr(item, "image_url", None),
|
|
604
|
+
file_id=getattr(item, "file_id", None),
|
|
605
|
+
detail=getattr(item, "detail", "auto"),
|
|
606
|
+
),
|
|
607
|
+
)
|
|
608
|
+
else:
|
|
609
|
+
# Fallback: convert to text
|
|
610
|
+
user_content_items.append(UserTextContent(text=str(item)))
|
|
611
|
+
|
|
612
|
+
user_message = NewUserMessage(content=user_content_items)
|
|
477
613
|
else:
|
|
478
|
-
|
|
479
|
-
|
|
614
|
+
# Handle non-string, non-list content
|
|
615
|
+
user_message = NewUserMessage(content=[UserTextContent(text=str(content))])
|
|
616
|
+
self.messages.append(user_message)
|
|
617
|
+
elif role == "system":
|
|
618
|
+
content = message.get("content", "")
|
|
619
|
+
system_message = NewSystemMessage(content=str(content))
|
|
620
|
+
self.messages.append(system_message)
|
|
621
|
+
elif role == "assistant":
|
|
622
|
+
content = message.get("content", "")
|
|
623
|
+
assistant_content_items: list[AssistantMessageContent] = [AssistantTextContent(text=str(content))] if content else []
|
|
624
|
+
|
|
625
|
+
# Handle tool calls if present
|
|
626
|
+
if "tool_calls" in message:
|
|
627
|
+
for tool_call in message.get("tool_calls", []):
|
|
628
|
+
try:
|
|
629
|
+
arguments = json.loads(tool_call["function"]["arguments"]) if isinstance(tool_call["function"]["arguments"], str) else tool_call["function"]["arguments"]
|
|
630
|
+
except (json.JSONDecodeError, TypeError):
|
|
631
|
+
arguments = tool_call["function"]["arguments"]
|
|
632
|
+
|
|
633
|
+
assistant_content_items.append(
|
|
634
|
+
AssistantToolCall(
|
|
635
|
+
call_id=tool_call["id"],
|
|
636
|
+
name=tool_call["function"]["name"],
|
|
637
|
+
arguments=arguments,
|
|
638
|
+
),
|
|
639
|
+
)
|
|
640
|
+
|
|
641
|
+
assistant_message = NewAssistantMessage(content=assistant_content_items)
|
|
642
|
+
self.messages.append(assistant_message)
|
|
643
|
+
elif message_type == "function_call":
|
|
644
|
+
# Handle function_call directly like AgentFunctionToolCallMessage
|
|
645
|
+
# Type guard: ensure we have the right message type
|
|
646
|
+
if "call_id" in message and "name" in message and "arguments" in message:
|
|
647
|
+
function_call_msg = message # Type should be FunctionCallDict now
|
|
648
|
+
if self.messages and isinstance(self.messages[-1], NewAssistantMessage):
|
|
649
|
+
tool_call = AssistantToolCall(
|
|
650
|
+
call_id=function_call_msg["call_id"], # type: ignore
|
|
651
|
+
name=function_call_msg["name"], # type: ignore
|
|
652
|
+
arguments=function_call_msg["arguments"], # type: ignore
|
|
653
|
+
)
|
|
654
|
+
self.messages[-1].content.append(tool_call)
|
|
655
|
+
else:
|
|
656
|
+
assistant_message = NewAssistantMessage(
|
|
657
|
+
content=[
|
|
658
|
+
AssistantToolCall(
|
|
659
|
+
call_id=function_call_msg["call_id"], # type: ignore
|
|
660
|
+
name=function_call_msg["name"], # type: ignore
|
|
661
|
+
arguments=function_call_msg["arguments"], # type: ignore
|
|
662
|
+
),
|
|
663
|
+
],
|
|
664
|
+
)
|
|
665
|
+
self.messages.append(assistant_message)
|
|
666
|
+
elif message_type == "function_call_output":
|
|
667
|
+
# Handle function_call_output directly like AgentFunctionCallOutput
|
|
668
|
+
# Type guard: ensure we have the right message type
|
|
669
|
+
if "call_id" in message and "output" in message:
|
|
670
|
+
function_output_msg = message # Type should be FunctionCallOutputDict now
|
|
671
|
+
if self.messages and isinstance(self.messages[-1], NewAssistantMessage):
|
|
672
|
+
tool_result = AssistantToolCallResult(
|
|
673
|
+
call_id=function_output_msg["call_id"], # type: ignore
|
|
674
|
+
output=function_output_msg["output"], # type: ignore
|
|
675
|
+
)
|
|
676
|
+
self.messages[-1].content.append(tool_result)
|
|
677
|
+
else:
|
|
678
|
+
assistant_message = NewAssistantMessage(
|
|
679
|
+
content=[
|
|
680
|
+
AssistantToolCallResult(
|
|
681
|
+
call_id=function_output_msg["call_id"], # type: ignore
|
|
682
|
+
output=function_output_msg["output"], # type: ignore
|
|
683
|
+
),
|
|
684
|
+
],
|
|
685
|
+
)
|
|
686
|
+
self.messages.append(assistant_message)
|
|
480
687
|
else:
|
|
481
688
|
msg = "Message must have a 'role' or 'type' field."
|
|
482
689
|
raise ValueError(msg)
|
|
690
|
+
else:
|
|
691
|
+
msg = f"Unsupported message type: {type(message)}"
|
|
692
|
+
raise TypeError(msg)
|
|
483
693
|
|
|
484
694
|
async def _handle_agent_transfer(self, tool_call: ToolCall, _includes: Sequence[AgentChunkType]) -> None:
|
|
485
695
|
"""Handle agent transfer when transfer_to_agent tool is called.
|
|
@@ -496,24 +706,18 @@ class Runner:
|
|
|
496
706
|
except (json.JSONDecodeError, KeyError):
|
|
497
707
|
logger.error("Failed to parse transfer_to_agent arguments: %s", tool_call.function.arguments)
|
|
498
708
|
# Add error result to messages
|
|
499
|
-
self.
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
call_id=tool_call.id,
|
|
503
|
-
output="Failed to parse transfer arguments",
|
|
504
|
-
),
|
|
709
|
+
self._add_tool_call_result(
|
|
710
|
+
call_id=tool_call.id,
|
|
711
|
+
output="Failed to parse transfer arguments",
|
|
505
712
|
)
|
|
506
713
|
return
|
|
507
714
|
|
|
508
715
|
if not target_agent_name:
|
|
509
716
|
logger.error("No target agent name provided in transfer_to_agent call")
|
|
510
717
|
# Add error result to messages
|
|
511
|
-
self.
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
call_id=tool_call.id,
|
|
515
|
-
output="No target agent name provided",
|
|
516
|
-
),
|
|
718
|
+
self._add_tool_call_result(
|
|
719
|
+
call_id=tool_call.id,
|
|
720
|
+
output="No target agent name provided",
|
|
517
721
|
)
|
|
518
722
|
return
|
|
519
723
|
|
|
@@ -521,12 +725,9 @@ class Runner:
|
|
|
521
725
|
if not self.agent.handoffs:
|
|
522
726
|
logger.error("Current agent has no handoffs configured")
|
|
523
727
|
# Add error result to messages
|
|
524
|
-
self.
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
call_id=tool_call.id,
|
|
528
|
-
output="Current agent has no handoffs configured",
|
|
529
|
-
),
|
|
728
|
+
self._add_tool_call_result(
|
|
729
|
+
call_id=tool_call.id,
|
|
730
|
+
output="Current agent has no handoffs configured",
|
|
530
731
|
)
|
|
531
732
|
return
|
|
532
733
|
|
|
@@ -539,12 +740,9 @@ class Runner:
|
|
|
539
740
|
if not target_agent:
|
|
540
741
|
logger.error("Target agent '%s' not found in handoffs", target_agent_name)
|
|
541
742
|
# Add error result to messages
|
|
542
|
-
self.
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
call_id=tool_call.id,
|
|
546
|
-
output=f"Target agent '{target_agent_name}' not found in handoffs",
|
|
547
|
-
),
|
|
743
|
+
self._add_tool_call_result(
|
|
744
|
+
call_id=tool_call.id,
|
|
745
|
+
output=f"Target agent '{target_agent_name}' not found in handoffs",
|
|
548
746
|
)
|
|
549
747
|
return
|
|
550
748
|
|
|
@@ -556,12 +754,9 @@ class Runner:
|
|
|
556
754
|
)
|
|
557
755
|
|
|
558
756
|
# Add the tool call result to messages
|
|
559
|
-
self.
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
call_id=tool_call.id,
|
|
563
|
-
output=str(result),
|
|
564
|
-
),
|
|
757
|
+
self._add_tool_call_result(
|
|
758
|
+
call_id=tool_call.id,
|
|
759
|
+
output=str(result),
|
|
565
760
|
)
|
|
566
761
|
|
|
567
762
|
# Switch to the target agent
|
|
@@ -571,12 +766,9 @@ class Runner:
|
|
|
571
766
|
except Exception as e:
|
|
572
767
|
logger.exception("Failed to execute transfer_to_agent tool call")
|
|
573
768
|
# Add error result to messages
|
|
574
|
-
self.
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
call_id=tool_call.id,
|
|
578
|
-
output=f"Transfer failed: {e!s}",
|
|
579
|
-
),
|
|
769
|
+
self._add_tool_call_result(
|
|
770
|
+
call_id=tool_call.id,
|
|
771
|
+
output=f"Transfer failed: {e!s}",
|
|
580
772
|
)
|
|
581
773
|
|
|
582
774
|
async def _handle_parent_transfer(self, tool_call: ToolCall, _includes: Sequence[AgentChunkType]) -> None:
|
|
@@ -591,12 +783,9 @@ class Runner:
|
|
|
591
783
|
if not self.agent.parent:
|
|
592
784
|
logger.error("Current agent has no parent to transfer back to.")
|
|
593
785
|
# Add error result to messages
|
|
594
|
-
self.
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
call_id=tool_call.id,
|
|
598
|
-
output="Current agent has no parent to transfer back to",
|
|
599
|
-
),
|
|
786
|
+
self._add_tool_call_result(
|
|
787
|
+
call_id=tool_call.id,
|
|
788
|
+
output="Current agent has no parent to transfer back to",
|
|
600
789
|
)
|
|
601
790
|
return
|
|
602
791
|
|
|
@@ -608,12 +797,9 @@ class Runner:
|
|
|
608
797
|
)
|
|
609
798
|
|
|
610
799
|
# Add the tool call result to messages
|
|
611
|
-
self.
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
call_id=tool_call.id,
|
|
615
|
-
output=str(result),
|
|
616
|
-
),
|
|
800
|
+
self._add_tool_call_result(
|
|
801
|
+
call_id=tool_call.id,
|
|
802
|
+
output=str(result),
|
|
617
803
|
)
|
|
618
804
|
|
|
619
805
|
# Switch to the parent agent
|
|
@@ -623,10 +809,7 @@ class Runner:
|
|
|
623
809
|
except Exception as e:
|
|
624
810
|
logger.exception("Failed to execute transfer_to_parent tool call")
|
|
625
811
|
# Add error result to messages
|
|
626
|
-
self.
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
call_id=tool_call.id,
|
|
630
|
-
output=f"Transfer to parent failed: {e!s}",
|
|
631
|
-
),
|
|
812
|
+
self._add_tool_call_result(
|
|
813
|
+
call_id=tool_call.id,
|
|
814
|
+
output=f"Transfer to parent failed: {e!s}",
|
|
632
815
|
)
|