lite-agent 0.11.0__py3-none-any.whl → 0.13.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/agent.py +15 -0
- lite_agent/context.py +37 -0
- lite_agent/runner.py +97 -5
- {lite_agent-0.11.0.dist-info → lite_agent-0.13.0.dist-info}/METADATA +1 -1
- {lite_agent-0.11.0.dist-info → lite_agent-0.13.0.dist-info}/RECORD +6 -5
- {lite_agent-0.11.0.dist-info → lite_agent-0.13.0.dist-info}/WHEEL +0 -0
lite_agent/agent.py
CHANGED
|
@@ -41,6 +41,7 @@ class Agent:
|
|
|
41
41
|
message_transfer: Callable[[RunnerMessages], RunnerMessages] | None = None,
|
|
42
42
|
completion_condition: str = "stop",
|
|
43
43
|
stop_before_tools: list[str] | list[Callable] | None = None,
|
|
44
|
+
termination_tools: list[str] | list[Callable] | None = None,
|
|
44
45
|
) -> None:
|
|
45
46
|
self.name = name
|
|
46
47
|
self.instructions = instructions
|
|
@@ -58,6 +59,20 @@ class Agent:
|
|
|
58
59
|
else:
|
|
59
60
|
self.stop_before_functions = set()
|
|
60
61
|
|
|
62
|
+
# Convert termination_tools to function names
|
|
63
|
+
if termination_tools:
|
|
64
|
+
self.termination_tools = set()
|
|
65
|
+
for func in termination_tools:
|
|
66
|
+
if isinstance(func, str):
|
|
67
|
+
self.termination_tools.add(func)
|
|
68
|
+
elif callable(func):
|
|
69
|
+
self.termination_tools.add(func.__name__)
|
|
70
|
+
else:
|
|
71
|
+
msg = f"termination_tools must contain strings or callables, got {type(func)}"
|
|
72
|
+
raise TypeError(msg)
|
|
73
|
+
else:
|
|
74
|
+
self.termination_tools = set()
|
|
75
|
+
|
|
61
76
|
if isinstance(model, BaseLLMClient):
|
|
62
77
|
# If model is a BaseLLMClient instance, use it directly
|
|
63
78
|
self.client = model
|
lite_agent/context.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Context utilities for injecting history messages into tool calls."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Generic, TypeVar
|
|
6
|
+
|
|
7
|
+
from pydantic import BaseModel
|
|
8
|
+
|
|
9
|
+
T = TypeVar("T")
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class HistoryContext(BaseModel, Generic[T]):
|
|
13
|
+
"""包含历史消息的上下文容器
|
|
14
|
+
|
|
15
|
+
这个类会自动被 Runner 用来包装用户的 context,确保工具函数能够访问历史消息。
|
|
16
|
+
|
|
17
|
+
Attributes:
|
|
18
|
+
history_messages: 工具调用前的所有历史消息
|
|
19
|
+
data: 用户自定义的上下文数据(可选)
|
|
20
|
+
|
|
21
|
+
Examples:
|
|
22
|
+
>>> # 只需要历史消息的工具
|
|
23
|
+
>>> async def count_messages(ctx: Context[HistoryContext[None]]) -> str:
|
|
24
|
+
... return f"总共 {len(ctx.value.history_messages)} 条消息"
|
|
25
|
+
|
|
26
|
+
>>> # 需要历史消息和用户数据的工具
|
|
27
|
+
>>> class UserData(BaseModel):
|
|
28
|
+
... user_id: str
|
|
29
|
+
>>>
|
|
30
|
+
>>> async def analyze_user(ctx: Context[HistoryContext[UserData]]) -> str:
|
|
31
|
+
... messages = ctx.value.history_messages
|
|
32
|
+
... user_id = ctx.value.data.user_id
|
|
33
|
+
... return f"用户 {user_id} 有 {len(messages)} 条消息"
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
history_messages: list[Any]
|
|
37
|
+
data: T | None = None
|
lite_agent/runner.py
CHANGED
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
import json
|
|
2
|
+
import inspect
|
|
2
3
|
from collections.abc import AsyncGenerator, Sequence
|
|
3
4
|
from datetime import datetime, timedelta, timezone
|
|
4
5
|
from os import PathLike
|
|
5
6
|
from pathlib import Path
|
|
6
|
-
from typing import Any, Literal, cast
|
|
7
|
+
from typing import Any, Literal, cast, get_args, get_origin
|
|
8
|
+
|
|
9
|
+
from funcall import Context
|
|
7
10
|
|
|
8
11
|
from lite_agent.agent import Agent
|
|
9
12
|
from lite_agent.constants import CompletionMode, StreamIncludes, ToolName
|
|
13
|
+
from lite_agent.context import HistoryContext
|
|
10
14
|
from lite_agent.loggers import logger
|
|
11
15
|
from lite_agent.types import (
|
|
12
16
|
AgentChunk,
|
|
@@ -109,6 +113,59 @@ class Runner:
|
|
|
109
113
|
"""Normalize record_to parameter to Path object if provided."""
|
|
110
114
|
return Path(record_to) if record_to else None
|
|
111
115
|
|
|
116
|
+
def _tool_expects_history_context(self, tool_calls: Sequence["ToolCall"]) -> bool:
|
|
117
|
+
"""Check if any of the tool calls expect HistoryContext in their signatures.
|
|
118
|
+
|
|
119
|
+
Returns True if any tool function has a Context[HistoryContext[...]] parameter,
|
|
120
|
+
False if they expect Context[...] without HistoryContext wrapper.
|
|
121
|
+
"""
|
|
122
|
+
if not tool_calls:
|
|
123
|
+
return False
|
|
124
|
+
|
|
125
|
+
for tool_call in tool_calls:
|
|
126
|
+
tool_func = self.agent.fc.function_registry.get(tool_call.function.name)
|
|
127
|
+
if not tool_func:
|
|
128
|
+
continue
|
|
129
|
+
|
|
130
|
+
# Get function signature
|
|
131
|
+
sig = inspect.signature(tool_func)
|
|
132
|
+
|
|
133
|
+
# Check each parameter for Context annotation
|
|
134
|
+
for param in sig.parameters.values():
|
|
135
|
+
if param.annotation == inspect.Parameter.empty:
|
|
136
|
+
continue
|
|
137
|
+
|
|
138
|
+
# Check if parameter is Context[...]
|
|
139
|
+
origin = get_origin(param.annotation)
|
|
140
|
+
if origin is not None:
|
|
141
|
+
# Check if it's Context type (compare by string name to handle import differences)
|
|
142
|
+
origin_name = getattr(origin, '__name__', str(origin))
|
|
143
|
+
if 'Context' in origin_name:
|
|
144
|
+
args = get_args(param.annotation)
|
|
145
|
+
if args:
|
|
146
|
+
# Check if the Context contains HistoryContext
|
|
147
|
+
inner_type = args[0]
|
|
148
|
+
inner_origin = get_origin(inner_type)
|
|
149
|
+
if inner_origin is not None:
|
|
150
|
+
inner_name = getattr(inner_origin, '__name__', str(inner_origin))
|
|
151
|
+
if 'HistoryContext' in inner_name:
|
|
152
|
+
logger.debug(f"Tool {tool_call.function.name} expects HistoryContext")
|
|
153
|
+
return True
|
|
154
|
+
# Also check for direct HistoryContext class
|
|
155
|
+
elif hasattr(inner_type, '__name__') and 'HistoryContext' in inner_type.__name__:
|
|
156
|
+
logger.debug(f"Tool {tool_call.function.name} expects HistoryContext")
|
|
157
|
+
return True
|
|
158
|
+
|
|
159
|
+
# Also handle direct annotation checking
|
|
160
|
+
if hasattr(param.annotation, '__name__'):
|
|
161
|
+
annotation_str = str(param.annotation)
|
|
162
|
+
if 'HistoryContext' in annotation_str:
|
|
163
|
+
logger.debug(f"Tool {tool_call.function.name} expects HistoryContext (direct)")
|
|
164
|
+
return True
|
|
165
|
+
|
|
166
|
+
logger.debug("No tools expect HistoryContext")
|
|
167
|
+
return False
|
|
168
|
+
|
|
112
169
|
async def _handle_tool_calls(self, tool_calls: "Sequence[ToolCall] | None", includes: Sequence[AgentChunkType], context: "Any | None" = None) -> AsyncGenerator[AgentChunk, None]: # noqa: ANN401
|
|
113
170
|
"""Handle tool calls and yield appropriate chunks."""
|
|
114
171
|
if not tool_calls:
|
|
@@ -181,6 +238,34 @@ class Runner:
|
|
|
181
238
|
)
|
|
182
239
|
return # Stop processing other tool calls after transfer
|
|
183
240
|
|
|
241
|
+
# Check if tools expect HistoryContext wrapper
|
|
242
|
+
expects_history = self._tool_expects_history_context(tool_calls)
|
|
243
|
+
|
|
244
|
+
if expects_history:
|
|
245
|
+
# Auto-inject history messages into context for tools that expect HistoryContext
|
|
246
|
+
if context is not None and not isinstance(context, Context):
|
|
247
|
+
# If user provided a plain object, wrap it in Context first
|
|
248
|
+
context = Context(context)
|
|
249
|
+
|
|
250
|
+
if isinstance(context, Context):
|
|
251
|
+
# Extract original value and wrap in HistoryContext
|
|
252
|
+
original_value = context.value
|
|
253
|
+
wrapped = HistoryContext(
|
|
254
|
+
history_messages=self.messages.copy(),
|
|
255
|
+
data=original_value,
|
|
256
|
+
)
|
|
257
|
+
context = Context(wrapped)
|
|
258
|
+
else:
|
|
259
|
+
# No context provided, create HistoryContext with only history messages
|
|
260
|
+
wrapped = HistoryContext(history_messages=self.messages.copy())
|
|
261
|
+
context = Context(wrapped)
|
|
262
|
+
elif context is not None and not isinstance(context, Context):
|
|
263
|
+
# Tools don't expect HistoryContext, wrap user object in Context
|
|
264
|
+
context = Context(context)
|
|
265
|
+
elif context is None:
|
|
266
|
+
# Provide empty context for tools that don't expect HistoryContext
|
|
267
|
+
context = Context(None)
|
|
268
|
+
|
|
184
269
|
async for tool_call_chunk in self.agent.handle_tool_calls(tool_calls, context=context):
|
|
185
270
|
# if tool_call_chunk.type == "function_call" and tool_call_chunk.type in includes:
|
|
186
271
|
# yield tool_call_chunk
|
|
@@ -270,12 +355,18 @@ class Runner:
|
|
|
270
355
|
|
|
271
356
|
def is_finish() -> bool:
|
|
272
357
|
if completion_condition == CompletionMode.CALL:
|
|
273
|
-
# Check if
|
|
358
|
+
# Check if any termination tool was called in the last assistant message
|
|
274
359
|
if self.messages and isinstance(self.messages[-1], NewAssistantMessage):
|
|
275
360
|
last_message = self.messages[-1]
|
|
276
361
|
for content_item in last_message.content:
|
|
277
|
-
if isinstance(content_item, AssistantToolCallResult)
|
|
278
|
-
|
|
362
|
+
if isinstance(content_item, AssistantToolCallResult):
|
|
363
|
+
tool_name = self._get_tool_call_name_by_id(content_item.call_id)
|
|
364
|
+
# Check custom termination tools first, then default wait_for_user
|
|
365
|
+
if hasattr(self.agent, "termination_tools") and self.agent.termination_tools:
|
|
366
|
+
if tool_name in self.agent.termination_tools:
|
|
367
|
+
return True
|
|
368
|
+
elif tool_name == ToolName.WAIT_FOR_USER:
|
|
369
|
+
return True
|
|
279
370
|
return False
|
|
280
371
|
return finish_reason == CompletionMode.STOP
|
|
281
372
|
|
|
@@ -484,9 +575,10 @@ class Runner:
|
|
|
484
575
|
max_steps: int = 20,
|
|
485
576
|
includes: list[AgentChunkType] | None = None,
|
|
486
577
|
record_to: PathLike | str | None = None,
|
|
578
|
+
context: Context | None = None,
|
|
487
579
|
) -> list[AgentChunk]:
|
|
488
580
|
"""Run the agent until it completes and return the final message."""
|
|
489
|
-
resp = self.run(user_input, max_steps, includes, record_to=record_to)
|
|
581
|
+
resp = self.run(user_input, max_steps, includes, record_to=record_to, context=context)
|
|
490
582
|
return await self._collect_all_chunks(resp)
|
|
491
583
|
|
|
492
584
|
def _analyze_last_assistant_message(self) -> tuple[list[AssistantToolCall], dict[str, str]]:
|
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
lite_agent/__init__.py,sha256=Swuefee0etSiaDnn30K2hBNV9UI3hIValW3A-pRE7e0,338
|
|
2
|
-
lite_agent/agent.py,sha256=
|
|
2
|
+
lite_agent/agent.py,sha256=gMn-NeQxl0298uKmlJph_c9WP3QN8WeKMEEDuv5RdVw,18681
|
|
3
3
|
lite_agent/chat_display.py,sha256=6gPgutMj7hCUOH6QBcC2f4Bhc93Gdq4vBa_1y6QKt2g,40793
|
|
4
4
|
lite_agent/client.py,sha256=-9BXLhAp3bGJsdKJ02lLpPJeHQKyHKQwhebZ6WCYh_k,9988
|
|
5
5
|
lite_agent/constants.py,sha256=_xIDdQwaJrWk8N_62o-KYEo3jj1waPJ0ZOd3hHybKNo,718
|
|
6
|
+
lite_agent/context.py,sha256=qnqj4JVYL0pkle1YptwM_CXJUWTeLaYtI1_MGtJYaHI,1225
|
|
6
7
|
lite_agent/loggers.py,sha256=XkNkdqwD_nQGfhQJ-bBWT7koci_mMkNw3aBpyMhOICw,57
|
|
7
8
|
lite_agent/message_transfers.py,sha256=N9ViK7Gxqqa1sd3V_hkNuQ9fUipg7M95l-sVBBG2Id4,5357
|
|
8
9
|
lite_agent/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
9
|
-
lite_agent/runner.py,sha256=
|
|
10
|
+
lite_agent/runner.py,sha256=H6gOeynLyLFr-ZTeEvBReuGdURkCVuP6T919_3AQ1CE,48568
|
|
10
11
|
lite_agent/processors/__init__.py,sha256=ybpAzpMBIE9v5I24wIBZRXeaOaPNTmoKH13aofgNI6Q,234
|
|
11
12
|
lite_agent/processors/completion_event_processor.py,sha256=zoWvs8dfrIkCSITGtS-4Hpve3WFCA0UUsMvYifL2fw0,13010
|
|
12
13
|
lite_agent/processors/response_event_processor.py,sha256=Jr3cj1ItJ8aq9UBhEEjDwWDnPNOZ2ZXjWJ3-g4ghkhM,8514
|
|
@@ -29,6 +30,6 @@ lite_agent/utils/message_builder.py,sha256=J-yycL9pXSO9MbgC5NEGqvoP1LC2Nxe9r2YRW
|
|
|
29
30
|
lite_agent/utils/message_converter.py,sha256=5HmNncTl71TD2M_6Ezz1Tnfavzna8DQYb4-D47Du7mA,9165
|
|
30
31
|
lite_agent/utils/message_state_manager.py,sha256=rFUyqyd_7NdJRtyqsAWGcfwrDIlD6gK2dBDSDx1eGBs,5766
|
|
31
32
|
lite_agent/utils/metrics.py,sha256=RzOEhCWxbLmmIEkzaxOJ6tAdthI8dv2Foc98Lq8afOQ,1915
|
|
32
|
-
lite_agent-0.
|
|
33
|
-
lite_agent-0.
|
|
34
|
-
lite_agent-0.
|
|
33
|
+
lite_agent-0.13.0.dist-info/METADATA,sha256=dw2mkbA3X3ZY8bV1xxeW9ybNZnHcFFFXSeTdLl4vuyc,3538
|
|
34
|
+
lite_agent-0.13.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
|
|
35
|
+
lite_agent-0.13.0.dist-info/RECORD,,
|
|
File without changes
|