智能体循环与聊天机器人的计算成本对比
为何 ReAct 风格的规划与工具链会使推理成本增加10倍——以及哪些机制能控制成本。
为何智能体所需的计算资源是聊天机器人的约10倍
从聊天机器人转向自主智能体并非表面上的变化,而是架构层面的变革。迭代推理循环会大幅增加推理次数和工具输入输出操作,因此同一任务所需的计算成本可能比简单回复高出一个数量级。
聊天机器人:一次有限次调用
传统助手的工作流程大致为:输入提示 → 调用一次(或几次)模型 → 输出答案。成本随输入输出文本的token数量而变化,延迟则由单次处理路径加上采样时间决定。
from langchain_community.vectorstores import FAISS
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
# Initialize the components (Vector store and LLM)
vectorstore = FAISS.from_texts(
["AI Agents require iterative loops."],
embedding=OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever()
model = ChatOpenAI(model="gpt-4o-mini")
# Build the linear RAG chain
rag_chain = (
{"context": retriever, "question": RunnablePassthrough()}
| model
| StrOutputParser()
)
# Execute the single, bounded inference call
# This represents exactly one unit of compute.
response = rag_chain.invoke("Why do agents need more compute?")
智能体:规划、执行、修正
智能体会将这一调用流程封装在循环中:思考 → 选择工具 → 观察结果 → 再次思考。每经过一步都会重新发送不断增长的上下文信息,失败后的自我修正还会增加更多循环次数。
import json
class AgenticResearchLoop:
def __init__(self):
self.conversation_history = []
# We mock the LLM responses to illustrate the sequential, stateful calls
self.mock_llm_steps = [
# Call 1: Initial planning step
{
"thought": "I need to identify the top 3 Salesforce competitors. I will start with a web search.",
"action": "web_search",
"action_input": "top CRM competitors to Salesforce 2024"
},
# Call 2: Analyzing results and planning the next action
{
"thought": "The search returned HubSpot, Microsoft Dynamics, and Veeva. Now I need to query HubSpot's latest quarterly earnings.",
"action": "web_search",
"action_input": "HubSpot latest quarterly earnings revenue"
},
# Call 3: Processing data and executing the next planned step
{
"thought": "HubSpot reported $557M in revenue. Now I will search for Microsoft Dynamics earnings.",
"action": "web_search",
"action_input": "Microsoft Dynamics 365 quarterly revenue growth"
},
# Call 4: Final synthesis of all collected information
{
"thought": "I have successfully retrieved data for the key competitors. I can now compile the final summary.",
"action": "finalize_answer",
"action_input": "Salesforce competitors summary: HubSpot ($557M revenue), Microsoft Dynamics (growing), and Veeva."
}
]
self.api_call_counter = 0
def query_llm(self, accumulated_prompt: str) -> dict:
"""Simulates an expensive inference call to the LLM provider."""
self.api_call_counter += 1
print(f"[LLM CALL #{self.api_call_counter}] Consuming tokens (Context size: {len(accumulated_prompt)} chars)...")
# In production, this would be a real chat completion API call
return self.mock_llm_steps[self.api_call_counter - 1]
def run(self, user_goal: str):
print(f"User Goal: {user_goal}\n")
context = f"Goal: {user_goal}\n"
while self.api_call_counter < len(self.mock_llm_steps):
llm_response = self.query_llm(context)
print(f" Reasoning thought: {llm_response['thought']}")
print(f" Executing Tool: {llm_response['action']}({llm_response['action_input']})")
observation = f"Successful result from {llm_response['action']}"
print(f" Observation: {observation}\n")
context += (
f"Thought: {llm_response['thought']}\n"
f"Action: {llm_response['action']}\n"
f"Observation: {observation}\n"
)
# Execute the agent
agent = AgenticResearchLoop()
agent.run("Research the top 3 competitors to Salesforce and summarize their latest quarterly earnings")
ReAct架构的循环机制
一个简化的ReAct结构就能解释为何计算成本会急剧上升:
+-------------+ Tool Call Parameter +----------------+
| | ----------------------------> | |
| LLM Agent | | External Tool |
| | <---------------------------- | (API/Database) |
+-------------+ Raw JSON Observation +----------------+
|
v
[Append to Context Window] ---> [Trigger Next LLM Inference Turn]
每个工具的输出都会成为下一次推理需要处理的新增token。
爆炸性增长的成因
- 每项任务并非只有一种推论,而是多种推论并存。
- 上下文不断扩展——包括历史记录、工具使用痕迹以及临时笔记。
- 投机性的死胡同——在消耗了相应代币后仍被放弃的计划。
- 工具响应延迟与GPU处理时间相互叠加。
工具使用的复合效应
外部API不仅会增加实际耗时,有时还需更多模型调用来解析结果:
import json
class AgentExecutor:
def __init__(self, prompt_template: str):
self.context = prompt_template
self.total_tokens_processed = 0
def execute_step(self, reasoning: str, action_result: dict):
step_input = f"\nThought: {reasoning}\nObservation: {json.dumps(action_result)}"
self.context += step_input
# Calculate mock token count (roughly 4 characters per token)
context_tokens = len(self.context) // 4
self.total_tokens_processed += context_tokens
print(f"Context Size: {context_tokens} tokens | "
f"Cumulative Tokens Billed: {self.total_tokens_processed}")
agent = AgentExecutor("System: You are an agent that books travel using tools.")
# Step 1: Flight Search Tool Output
agent.execute_step(
reasoning="I need to find flights from JFK to LHR first.",
action_result={"flights": [{"id": "AA100", "price": 450, "time": "08:00"}]}
)
# Step 2: Hotel Search Tool Output (Context has grown)
agent.execute_step(
reasoning="Found flight AA100. Now I must find a hotel near Heathrow.",
action_result={"hotels": [{"name": "Airport Inn", "price": 120, "rating": 4.2}]}
)
即使每一步都看似“简单”,多步骤的完成流程(搜索→加入购物车→支付→确认)仍需要相当于多个聊天机器人回复的工作量。
失败成本高昂
重试和反思虽能提升可靠性,却会增加费用。若没有预算限制,混乱的智能体可能会陷入反复试错的困境。
import time
from typing import Callable, Any, Dict
class AgentRuntimeLimitError(Exception):
"""Raised when an agent violates runtime guardrails."""
pass
def execute_agent_step(
step_fn: Callable[[], Dict[str, Any]],
max_iterations: int = 5,
max_duration_seconds: float = 10.0
) -> Dict[str, Any]:
"""
Executes an agent step loop with strict termination guardrails
to prevent infinite ReAct loops and runaway API billing.
"""
start_time = time.time()
iterations = 0
while iterations < max_iterations:
elapsed_time = time.time() - start_time
if elapsed_time > max_duration_seconds:
raise AgentRuntimeLimitError(f"Execution timed out after {elapsed_time:.2f}s.")
step_result = step_fn()
iterations += 1
if step_result.get("status") == "COMPLETED":
return step_result
raise AgentRuntimeLimitError(f"Exceeded maximum iterations limit: {max_iterations}"
真实的工作负载
- 自主编码功能:编辑、测试、查看日志、再次编辑——可进行数十次模型调用。
- 多API客户操作功能:身份管理、库存查询、物流跟踪——一系列有序的工具功能。
- 基础设施监控功能:在严格的服务水平指标约束下进行状态检测、问题诊断并提出解决方案。
何时只需聊天即可
当任务为问答、摘要生成或单次信息检索时,建议使用一次性处理或轻量级工具。而在环境只能部分观测且需要多步骤操作时,则应使用智能代理。
约束机制
- 限制每次运行的步骤数、令牌数量及成本上限
- 为高风险操作设定确定性的执行路径
- 为代码/命令行工具提供沙箱环境
- 具备可观测性:为每个思考过程和工具使用添加成本标签以便追踪
- 缓存稳定的检索结果;在多次调用之间简化提示词内容
架构所需条件
应将智能体视为分布式系统:包括预算、幂等性、审计以及服务水平目标,而非带有循环标志的聊天界面。10倍的计算性能并非缺陷,而是迭代控制的必然代价,除非你刻意对其进行优化设计。
为每个时间片段添加agent_id和step_index标签,以便财务部门能够对应计算10倍的倍数关系。
为每个时间片段添加agent_id和step_index标签,以便财务部门能够对应计算10倍的倍数关系。
为每个时间片段添加agent_id和step_index标签,以便财务部门能够对应计算10倍的倍数关系。
为每个时间片段添加agent_id和step_index标签,以便财务部门能够对应计算10倍的倍数关系。
为每个时间片段添加agent_id和step_index标签,以便财务部门能够对应计算10倍的倍数关系。
为每个时间片段添加agent_id和step_index标签,以便财务部门能够对应计算10倍的倍数关系。
为每个时间片段添加agent_id和step_index标签,以便财务部门能够对应计算10倍的倍数关系。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个片段添加 agent_id 和 step_index 标签,以便财务部门确定10倍乘数。
为每个时间段添加agent_id和step_index标签,以便财务部门确定10倍乘数。
为每个时间段添加agent_id和step_index标签,以便财务部门确定10倍乘数。
为每个时间段添加agent_id和step_index标签,以便财务部门确定10倍乘数。