Agno 与 DeepSeek V4 集成实战指南:Thinking 模式、推理控制与工具调用
【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno
本篇技术指南以 cookbook/90_models/deepseek/README.md 为核心骨架,深入讲解如何在 Agno 框架中使用 DeepSeek 官方 OpenAI 兼容 API,覆盖 V4 系列模型(deepseek-v4-flash与deepseek-v4-pro)的选型、Thinking 模式默认开启机制、reasoning_effort推理力度控制、结构化输出、工具调用与失败重试等完整能力。读完本文,你将能够在 Agno 中快速搭建基于 DeepSeek 的 Agent、按场景开关思考模式、并把思维链输出到终端用于调试。
一、DeepSeek 模型在 Agno 中的定位
DeepSeek 提供 OpenAI 兼容的 API(https://api.deepseek.com),因此在 Agno 中由agno.models.deepseek.DeepSeek类承载,该类继承自OpenAILike(见 libs/agno/agno/models/deepseek/deepseek.py),这意味着 DeepSeek 可以被当作一个"换端点的 OpenAI 兼容模型"直接使用,无需额外的适配层。
从源码可以确认,DeepSeek类的默认配置为:
id默认deepseek-v4-flash;name默认DeepSeek,provider默认DeepSeek;base_url默认https://api.deepseek.com;api_key默认从环境变量DEEPSEEK_API_KEY读取(见 deepseek.py);- 若未设置 API Key,构造客户端时会立即抛出
ModelAuthenticationError并提示设置DEEPSEEK_API_KEY(见 deepseek.py)。
二、可用模型与 deprecated 模型 id 迁移
2.1 V4 系列模型
原文档给出的模型清单如下:
| Model id | Description |
|---|---|
deepseek-v4-flash | Fast V4 model (default),1M context。Hybrid:thinking + non-thinking。 |
deepseek-v4-pro | Flagship V4 model,1M context。Hybrid:thinking + non-thinking。 |
两者均支持 1M 上下文,且属于"混合"模型——同一个 id 既可开启 Thinking(返回reasoning_content)也可关闭 Thinking(直接返回内容)。flash定位为快速版(默认),pro为旗舰版,适合高难度推理任务。
2.2 Deprecated 模型 id
| Legacy id | Maps to |
|---|---|
deepseek-chat | deepseek-v4-flash的 non-thinking 模式 |
deepseek-reasoner | deepseek-v4-flash的 thinking 模式 |
这些旧 id 仍然可用(服务端会路由到 V4 对应模式),但官方建议迁移到新 id。在 Agno 源码中也有对应的实现印证:_non_thinking_model_ids集合包含deepseek-chat,即该旧 id 默认不开启 thinking(见 deepseek.py);而deepseek-reasoner本身即 thinking 模型,无需特殊处理。
三、环境准备与安装
1. 创建并激活虚拟环境
python3 -m venv ~/.venvs/aienv source ~/.venvs/aienv/bin/activate2. 导出DEEPSEEK_API_KEY
export DEEPSEEK_API_KEY=***需要先到 DeepSeek 开放平台申请 API Key。Agno 源码会在构造客户端时读取该环境变量,未设置则直接抛错(见 deepseek.py)。
3. 安装依赖库
uv pip install -U openai ddgs duckdb yfinance agno其中openai是底层 OpenAI 兼容客户端;ddgs(DuckDuckGo 搜索)与yfinance(金融数据)分别是 tool_use.py、thinking_tool_calls.py 等工具调用示例的可选依赖;agno为本框架本体。根据 cookbook/90_models/deepseek/TEST_LOG.md 的记录,工具类示例需要在安装了这些可选依赖的 venv 中运行。
四、Thinking 模式:默认开启的推理机制
4.1 默认行为
DeepSeek V4 模型的 Thinking 模式默认开启,因此模型开箱即返回reasoning_content(思维链内容),这与旧版deepseek-chat的行为不同。Agno 源码中的_thinking_enabled()方法完整描述了这一决策逻辑(见 deepseek.py):
use_thinking显式设置时,以显式值为准;- 未设置时,thinking-capable 模型(V4 系列)默认开启,legacy 非思考模型(
deepseek-chat)默认关闭。
开启时,get_request_params()会向请求注入extra_body={"thinking": {"type": "enabled"}};显式关闭时则注入{"type": "disabled"}(见 deepseek.py)。
4.2 用use_thinking开关
DeepSeek(id="deepseek-v4-flash", use_thinking=False)关闭思考,响应更快、更便宜,且不再返回reasoning_content;use_thinking=True强制开启思考。
完整的对照示例见 thinking_mode.py:它同时构造了一个默认开启思考的thinking_agent和一个use_thinking=False的non_thinking_agent,用同一个问题("Why is the sky blue?")分别流式调用,验证reasoning_content是否存在。
from agno.agent import Agent from agno.models.deepseek import DeepSeek # Thinking enabled (default) - returns reasoning_content thinking_agent = Agent(model=DeepSeek(id="deepseek-v4-flash"), markdown=True) # Thinking disabled - faster, no reasoning_content non_thinking_agent = Agent( model=DeepSeek(id="deepseek-v4-flash", use_thinking=False), markdown=True, ) if __name__ == "__main__": thinking_agent.print_response("Why is the sky blue?", stream=True) non_thinking_agent.print_response("Why is the sky blue?", stream=True)4.3 思考模式的参数约束
当 Thinking 模式处于激活状态时,temperature、top_p、presence_penalty、frequency_penalty会被 API 静默忽略。这是 DeepSeek V4 的硬性行为(源码类注释中亦明确说明,见 deepseek.py)。因此:
- 追求确定性的任务(如结构化抽取),可考虑
use_thinking=False以便自由调节采样参数; - 需要深度推理的任务,放弃上述采样参数,专注于
reasoning_effort。
五、控制推理力度:reasoning_effort
对于高要求的 Agent 任务,DeepSeek 建议将reasoning_effort设为"max"。合法取值为"high"与"max"("low"、"medium"会在服务端被映射为"high")。默认不设置(None),此时 API 使用其自身默认值"high"。
从源码看,reasoning_effort仅在 thinking 开启时有效:当关闭 thinking 时,get_request_params()会将其从请求参数中移除,避免无效参数(见 deepseek.py)。
from agno.agent import Agent from agno.models.deepseek import DeepSeek agent = Agent( model=DeepSeek(id="deepseek-v4-pro", reasoning_effort="max"), markdown=True, ) task = ( "A farmer needs to cross a river with a fox, a chicken and a sack of grain. " "The boat only fits the farmer and one item. The fox cannot be left alone with " "the chicken, and the chicken cannot be left alone with the grain. " "Provide a step-by-step solution." ) if __name__ == "__main__": agent.print_response(task, stream=True, show_full_reasoning=True)要点:show_full_reasoning=True会在终端完整打印思维链(reasoning_content),适合调试与验证推理过程。完整示例见 reasoning_effort.py。
六、搭建 Agent 的四种运行模式
basi.py 演示了同一个 Agent 的四种调用方式,这是 Agno 中最基础的用法:
from agno.agent import Agent, RunOutput from agno.models.deepseek import DeepSeek import asyncio agent = Agent(model=DeepSeek(id="deepseek-v4-flash"), markdown=True) if __name__ == "__main__": # --- Sync --- agent.print_response("Share a 2 sentence horror story") # --- Sync + Streaming --- agent.print_response("Share a 2 sentence horror story", stream=True) # --- Async --- asyncio.run(agent.aprint_response("Share a 2 sentence horror story")) # --- Async + Streaming --- asyncio.run(agent.aprint_response("Share a 2 sentence horror story", stream=True))如需把响应存入变量而不是打印,可使用run: RunOutput = agent.run("...")然后访问run.content(示例中以注释形式给出)。
提示:由于 Thinking 默认开启,流式场景下响应会先产出
reasoning_content增量、再产出正文增量。测试日志 TEST_LOG.md 提到集成测试已按此"thinking-aware"行为更新,意味着你的流式处理逻辑需要兼容这一顺序。
七、推理 Agent:用思维链解复杂谜题
reasoning_agent.py 展示了一个推理型 Agent:使用旗舰模型deepseek-v4-pro求解"传教士与食人族过河"问题,并要求给出分步解答与 ASCII 示意图。
from agno.agent import Agent from agno.models.deepseek import DeepSeek task = ( "Three missionaries and three cannibals need to cross a river. " "They have a boat that can carry up to two people at a time. " "If, at any time, the cannibals outnumber the missionaries on either side of the river, " "the cannibals will eat the missionaries. " "How can all six people get across the river safely? " "Provide a step-by-step solution and show the solutions as an ascii diagram" ) agent = Agent( model=DeepSeek( id="deepseek-v4-pro", ), markdown=True, ) agent.print_response(task, stream=True)这类场景正是deepseek-v4-pro+ Thinking 模式的典型用例:复杂约束类问题需要模型先展开推理再给出结构化解答,markdown=True让输出保持可读的排版。
八、结构化输出:JSON 模式是可靠路径
DeepSeek 官方支持 JSON 模式(response_format={"type": "json_object"}),但不支持原生的 json_schema 结构化输出。因此,在 Agno 中使用output_schema时,推荐显式设置use_json_mode=True。这一结论在源码中也有直接体现:DeepSeek类的supports_native_structured_outputs = False(见 deepseek.py)。
structured_output.py 演示了两种写法:
from typing import List from agno.agent import Agent, RunOutput from agno.models.deepseek import DeepSeek from pydantic import BaseModel, Field class MovieScript(BaseModel): setting: str = Field(..., description="Provide a nice setting for a blockbuster movie.") ending: str = Field(..., description="Ending of the movie. If not available, provide a happy ending.") genre: str = Field(..., description="Genre of the movie. If not available, select action, thriller or romantic comedy.") name: str = Field(..., description="Give a name to this movie") characters: List[str] = Field(..., description="Name of characters for this movie.") storyline: str = Field(..., description="3 sentence storyline for the movie. Make it exciting!") # Agent that uses JSON mode (recommended for DeepSeek) json_mode_agent = Agent( model=DeepSeek(id="deepseek-v4-flash"), description="You help people write movie scripts.", output_schema=MovieScript, use_json_mode=True, ) # Agent that uses native structured outputs (output_schema without JSON mode) structured_output_agent = Agent( model=DeepSeek(id="deepseek-v4-flash"), description="You help people write movie scripts.", output_schema=MovieScript, ) if __name__ == "__main__": json_mode_agent.print_response("New York") structured_output_agent.print_response("New York")根据 TEST_LOG.md 的验证结果,两种方式最终都能产出合法 JSON:use_json_mode=True走官方 JSON 模式;仅传output_schema时,Agno 会退回到基于提示词的 JSON 兜底方案。实战建议:优先use_json_mode=True,它更稳定可靠。
九、工具调用:Thinking 与工具协作
DeepSeek V4 模型在 Thinking 与非 Thinking 模式下均支持工具调用;且 Thinking 模式下的工具调用能力进一步增强——模型在输出最终答案前,可以进行多轮"推理 → 工具调用 → 推理"的循环,从而提升回答质量。
- tool_use.py:使用
deepseek-v4-flash+WebSearchTools,同步与"异步+流式"两种方式询问"法国正在发生什么";
import asyncio from agno.agent import Agent from agno.models.deepseek import DeepSeek from agno.tools.websearch import WebSearchTools agent = Agent( model=DeepSeek(id="deepseek-v4-flash"), tools=[WebSearchTools()], markdown=True, ) if __name__ == "__main__": agent.print_response("Whats happening in France?") asyncio.run(agent.aprint_response("Whats happening in France?", stream=True))- thinking_tool_calls.py:使用
deepseek-v4-pro+WebSearchTools,流式输出并以show_full_reasoning=True展示思考与工具调用交织的过程:
from agno.agent import Agent from agno.models.deepseek import DeepSeek from agno.tools.websearch import WebSearchTools agent = Agent( model=DeepSeek(id="deepseek-v4-pro"), tools=[WebSearchTools()], markdown=True, stream=True, ) agent.print_response("Whats happening in France?", show_full_reasoning=True)运行工具类示例前需安装
ddgs(uv pip install ddgs)。工具调用参数会在reasoning_content中体现,结合show_full_reasoning=True可以完整观察模型"先想后做"的决策链路。
十、失败重试机制
当 API 请求失败(网络抖动、限流、无效模型 id 等)时,可以通过retries、delay_between_retries、exponential_backoff三个参数配置重试行为。retry.py 用一个故意写错的模型 id(deepseek-wrong-id)来触发重试:
from agno.agent import Agent from agno.models.deepseek import DeepSeek wrong_model_id = "deepseek-wrong-id" agent = Agent( model=DeepSeek( id=wrong_model_id, retries=3, # 请求重试次数 delay_between_retries=1, # 重试间隔(秒) exponential_backoff=True, # 若为 True,每次重试间隔翻倍 ), ) agent.print_response("What is the capital of France?")参数说明:
retries:最大重试次数;delay_between_retries:两次重试之间的基础间隔(秒);exponential_backoff:开启后间隔按 2 的幂次递增(1s → 2s → 4s…),适合应对限流类错误。
十一、示例清单与运行方式
原文档给出的全部示例及运行命令如下(在仓库根目录执行):
# Basic agent (sync, async, streaming) python cookbook/90_models/deepseek/basic.py # Tool use python cookbook/90_models/deepseek/tool_use.py # Structured output python cookbook/90_models/deepseek/structured_output.py # Reasoning agent (thinking mode) python cookbook/90_models/deepseek/reasoning_agent.py # Thinking + tool calls python cookbook/90_models/deepseek/thinking_tool_calls.py # Controlling reasoning effort python cookbook/90_models/deepseek/reasoning_effort.py # Toggling thinking mode on/off python cookbook/90_models/deepseek/thinking_mode.py # Retry behavior python cookbook/90_models/deepseek/retry.py各示例均需提前设置DEEPSEEK_API_KEY环境变量。按 TEST_LOG.md 的实测记录(2026-05-29,针对 DeepSeek V4 API):
basic.py、thinking_mode.py、reasoning_effort.py、structured_output.py全部 PASS;- 相关单元测试
libs/agno/tests/unit/reasoning/test_reasoning_checkers.py与libs/agno/tests/unit/models/deepseek/test_deepseek.py共79 passed(无需网络); - 集成测试
libs/agno/tests/integration/models/deepseek/test_basic.py共9 passed(流式测试已适配"先 reasoning_content 后 content"的顺序); tool_use.py、structured_output.py、reasoning_agent.py、thinking_tool_calls.py依赖可选 cookbook 依赖(ddgs/yfinance),需在安装了这些依赖的演示 venv 中运行。
十二、选型建议速查
| 场景 | 推荐配置 |
|---|---|
| 默认通用 Agent | DeepSeek(id="deepseek-v4-flash")(thinking 默认开启) |
| 追求速度/成本,不需要思维链 | DeepSeek(id="deepseek-v4-flash", use_thinking=False) |
| 高难度推理(数学、谜题、复杂规划) | DeepSeek(id="deepseek-v4-pro", reasoning_effort="max"),配合show_full_reasoning=True观察思维链 |
| 结构化输出 | output_schema=YourModel+use_json_mode=True |
| 需要实时信息 | tools=[WebSearchTools()](配合thinking_tool_calls.py体验多轮推理+工具调用) |
| 请求不稳定环境 | retries=3, delay_between_retries=1, exponential_backoff=True |
注意事项汇总:
- Thinking 开启时
temperature/top_p/presence_penalty/frequency_penalty被 API 忽略; reasoning_effort合法值为"high"与"max",关闭 thinking 后该参数自动失效;- 旧 id
deepseek-chat/deepseek-reasoner仍可用,但建议迁移到 V4 系列; - DeepSeek 无原生 json_schema 结构化输出,
use_json_mode=True是可靠路径。
通过以上配置与源码级原理,你已可以在 Agno 中完整驾驭 DeepSeek V4 的混合思考能力,构建从简单问答到复杂推理、从工具调用到结构化输出的各类 Agent 应用。
【免费下载链接】agnoBuild, run, and manage agent platforms.项目地址: https://gitcode.com/GitHub_Trending/ag/agno
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考