微信扫码
添加专属顾问
我要投稿
深入解析LLM Agent的核心结构与返回机制,从代码层面揭示其设计精髓。核心内容:1. AgentFunction类型别名的精妙设计与实际应用2. Response和Result模型的结构解析与使用场景3. 商用代码示例中的关键实现细节剖析
from typing import List, Callable, Union, Optional
from openai.types.chat import ChatCompletionMessage
from openai.types.chat.chat_completion_message_tool_call import (
ChatCompletionMessageToolCall,
Function,
)
# Third-party imports
from pydantic import BaseModel
AgentFunction = Callable[[], Union[str, "Agent", dict]]
class Agent(BaseModel):
name: str = "Agent"
model: str = "gpt-4o"
instructions: Union[str, Callable[[], str]] = "You are a helpful agent."
functions: List[AgentFunction] = []
tool_choice: str = None
parallel_tool_calls: bool = True
class Response(BaseModel):
messages: List = []
agent: Optional[Agent] = None
context_variables: dict = {}
class Result(BaseModel):
"""
Encapsulates the possible return values for an agent function.
Attributes:
value (str): The result value as a string.
agent (Agent): The agent instance, if applicable.
context_variables (dict): A dictionary of context variables
"""
value: str = ""
agent: Optional[Agent] = None
context_variables: dict = {}
AgentFunction = Callable[[], Union[str, "Agent", dict]]
Callable[[], ...]
[]
表示参数列表(这里是空的),也可以写成 Callable[[int, str], ...]
等表示有参数的函数。Union[str, "Agent", dict]
str
"Agent"
dict
使用
"Agent"
而不是Agent
是为了防止在类定义之前就引用它(比如在类内部定义函数时),Python 3.7+ 支持from __future__ import annotations
后可以直接写Agent
。
将函数签名抽象为一个名字 AgentFunction
,可以让其他开发者更容易理解它的用途和结构。
例如:
def my_func() -> AgentFunction:
...
def my_func() -> Callable[[], Union[str, "Agent", dict]]:
...
如果你有很多函数或方法返回类似的结构(如状态、子代理、配置等),统一使用 AgentFunction
可以帮助你确保接口一致性。
允许函数返回不同类型的值,适用于如下场景:
假设你正在构建一个 Agent 框架,每个 agent 都可以决定下一步要做什么:
def decide_next_action() -> AgentFunction:
if should_stop():
return "STOP"
elif need_delegate():
return AnotherAgent()
else:
return {"action": "continue", "data": ...}
虽然当前定义已经很清晰,但根据你的具体需求,也可以考虑以下几点改进:
Protocol
定义更严格的函数接口(Python 3.8+)
如果你希望对函数的输入输出做更精确控制,可以用 Protocol
:
from typing import Protocol
class AgentFunction(Protocol):
def __call__(self) -> Union[str, "Agent", dict]:
...
这可以让你用类型检查器验证某个函数是否符合该协议。
如果你的返回值是一些固定的指令(如停止、继续、委托),建议用 Enum
替代字符串:
from enum import Enum
class Action(Enum):
CONTINUE = "continue"
STOP = "stop"
DELEGATE = "delegate"
AgentFunction = Callable[[], Union[Action, "Agent", dict]]
这样可以避免拼写错误,并增强语义表达。
你可以定义一个统一的响应结构,让逻辑更清晰:
from typing import Optional, Union
from dataclasses import dataclass
class AgentResponse:
action: str # 如 "continue", "stop"
next_agent: Optional["Agent"] = None
output: Optional[dict] = None
AgentFunction = Callable[[], AgentResponse]
这个 Agent
类定义基于 Python 的数据类(dataclass)或 Pydantic 的 BaseModel,假设是使用了 Pydantic 的 BaseModel
。它定义了一个代理(Agent)的模板,其中包含了一些属性来描述该代理的行为和功能。下面是对每个字段的分析以及潜在的改进点。
name: str = "Agent"
"Agent"
。model: str = "gpt-4o"
"gpt-4o"
。gpt-4o
应该是 gpt-4
或者其他有效模型名)。考虑使用枚举或者更严格的验证规则来限制允许的模型名称。instructions: Union[str, Callable[[], str]] = "You are a helpful agent."
Callable
版本。functions: List[AgentFunction] = []
None
作为默认值,并在类内部处理初始化逻辑。tool_choice: str = None
None
。parallel_tool_calls: bool = True
True
。from typing import List, Optional, Union, Callable
from pydantic import BaseModel
# 假设 AgentFunction 是已经定义好的类型别名
AgentFunction = Callable[[], Union[str, "Agent", dict]]
class Agent(BaseModel):
name: str = "Agent"
# 确认模型名称的有效性
model: str = "gpt-4" # 注意这里修正了模型名
# 提供了更详细的默认指令
instructions: Union[str, Callable[[], str]] = "You are an intelligent assistant designed to help users with their queries."
# 使用 None 代替直接定义可变默认值
functions: Optional[List[AgentFunction]] = None
# 定义工具选择的枚举或其他限制方式
tool_choice: Optional[str] = None
parallel_tool_calls: bool = True
# 初始化函数,用于设置默认值
def __init__(self, **data):
super().__init__(**data)
if self.functions is None:
self.functions = []
functions
),避免直接使用可变对象作为默认参数。instructions
),提供更加具体的指导或示例。tool_choice
的类型安全性。53AI,企业落地大模型首选服务商
产品:场景落地咨询+大模型应用平台+行业解决方案
承诺:免费场景POC验证,效果验证后签署服务协议。零风险落地应用大模型,已交付160+中大型企业
2025-06-21
工业大模型定义及技术架构
2025-06-21
精|知识探索新范式:深度研究Deep Research智能体全面综述,系统、方法与应用
2025-06-21
Qwen3 Embedding模型架构、训练方法、数据策略
2025-06-21
别搞通用智能体,落地赚钱才是王道
2025-06-21
大模型工程化:从“实验玩具”到“应用落地”的关键突破口
2025-06-21
AI Agent 在角色扮演场景的研究进展
2025-06-21
MCP技术浪潮中的Agent应用开发新范式
2025-06-21
官宣|Zilliz Cloud 建表功能大升级,更多检索类型支持,更低成本
2025-05-29
2025-04-11
2025-04-01
2025-04-12
2025-04-29
2025-04-12
2025-04-06
2025-04-15
2025-04-13
2025-04-17
2025-06-20
2025-06-20
2025-06-20
2025-06-20
2025-06-19
2025-06-19
2025-06-18
2025-06-17