微信扫码
添加专属顾问
 
                        我要投稿
深入解析LLM Agent的核心结构与返回机制,从代码层面揭示其设计精髓。 核心内容: 1. AgentFunction类型别名的精妙设计与实际应用 2. Response和Result模型的结构解析与使用场景 3. 商用代码示例中的关键实现细节剖析
 
                                from typing import List, Callable, Union, Optionalfrom openai.types.chat import ChatCompletionMessagefrom openai.types.chat.chat_completion_message_tool_call import (ChatCompletionMessageToolCall,Function,)# Third-party importsfrom pydantic import BaseModelAgentFunction = 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 = Noneparallel_tool_calls: bool = Trueclass Response(BaseModel):messages: List = []agent: Optional[Agent] = Nonecontext_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] = Nonecontext_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, Callablefrom 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] = Noneparallel_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-10-31
从Palantir智能化技术路线看AI时代企业级架构平台的核心战略位置
2025-10-31
OpenAI 公开 Atlas 架构:为 Agent 重新发明浏览器
2025-10-31
Palantir 本体论模式:重塑企业 AI 应用的 “语义根基” 与产业启示
2025-10-31
树莓派这种“玩具级”设备,真能跑大模型吗?
2025-10-30
Cursor 2.0的一些有趣的新特性
2025-10-30
Anthropic 发布最新研究:LLM 展现初步自省迹象
2025-10-30
让Agent系统更聪明之前,先让它能被信任
2025-10-30
Rag不行?谷歌DeepMind同款,文档阅读新助手:ReadAgent
 
            2025-08-21
2025-08-21
2025-08-19
2025-09-16
2025-10-02
2025-09-08
2025-09-17
2025-08-19
2025-09-29
2025-08-20