微信扫码
添加专属顾问
我要投稿
深入解析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 Protocolclass AgentFunction(Protocol): def __call__(self) -> Union[str, "Agent", dict]: ...
这可以让你用类型检查器验证某个函数是否符合该协议。
如果你的返回值是一些固定的指令(如停止、继续、委托),建议用 Enum
替代字符串:
from enum import Enumclass Action(Enum): CONTINUE = "continue" STOP = "stop" DELEGATE = "delegate"AgentFunction = Callable[[], Union[Action, "Agent", dict]]
这样可以避免拼写错误,并增强语义表达。
你可以定义一个统一的响应结构,让逻辑更清晰:
from typing import Optional, Unionfrom dataclasses import dataclass@dataclassclass AgentResponse: action: str # 如 "continue", "stop" next_agent: Optional["Agent"] = None output: Optional[dict] = NoneAgentFunction = 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-08-05
我不是很看好GPT-5
2025-08-05
企业构建AI Agent 的五个视角|伯克利Agentic AI Summit
2025-08-05
金融Agent竞赛:什么才是最实用的打开方式?
2025-08-05
一条SQL管理向量全生命周期,让AI应用开发更简单
2025-08-05
赛博沙盒:如何与AI共创未来丨1.4万字圆桌实录
2025-08-05
AI与AIGC在企业实践中的应用
2025-08-05
让AI回答更“聪明精准”?你必须认识“命题切块”技术!(附实测详解、RAG新范式解析)
2025-08-05
你的AI,还是它的偏见?揭开大型语言模型在投资分析中的“认知黑箱” | Arxiv 论文
2025-05-29
2025-05-23
2025-06-01
2025-06-07
2025-06-21
2025-06-12
2025-05-20
2025-06-19
2025-06-13
2025-05-28
2025-08-05
2025-08-05
2025-08-05
2025-08-04
2025-08-02
2025-08-02
2025-07-31
2025-07-31