Kimi Web Search Agent / Kimi 网络搜索 Agent¶
回答一个需要新信息的问题时,模型往往不能一步结束:它先决定查什么,读到结果后再决定是否继续查。本实验用一条可见的搜索轨迹,解释“思考、行动、观察”怎样组成 Agent 循环。
谁决定下一次搜索 · 选择示例回放或联网查询 · 跟踪一次搜索循环 · 用搜索结果核对回答 · 沿入口追到客户端循环 · 运行注意事项
谁决定下一次搜索¶
用户问题进入对话后,模型可以提出工具调用。程序执行工具,把结果作为新的消息交回模型,随后开始下一轮。离线演示使用预先写好的轨迹,让你先看清控制流。联网时,直连 Kimi 默认用 Moonshot Formula 搜索,走 OpenRouter 默认用 Parallel MCP。
这个实验做什么¶
对应书中实验 1-2 ★:Kimi K3 原生 Agent 能力。模型收到问题后,可以调用搜索工具, 读取结果,再决定继续搜索还是回答。这个过程就是本章介绍的 ReAct 循环。
联网时发生了什么¶
直连 Kimi 时,默认通过 Moonshot 的 Formula 接口使用 web_search。你不需要先读懂全部接口,
只需跟踪三步:
- 程序向服务端获取搜索工具的定义,并把定义交给模型。
- 模型决定搜索时,程序把它给出的工具名和参数交给 Formula 执行。
- 工具执行成功后,程序把结果放回对话,让模型继续处理问题。
搜索在 Moonshot 服务端执行。遇到错误时,先看日志区分是获取工具定义、执行搜索还是模型请求失败。 服务的使用条件见 官方工具说明。 如果暂时无法联网,可以继续用上面的离线演示学习流程。
怎样检查答案¶
一次联网问答完成后,检查轨迹里是否实际调用了 web_search,工具是否返回成功,以及最终答案是否使用了
这些结果。每次提问都会重置对话历史,所以上一个问题中的信息不会自动保留到下一个问题。
搜索成功也不保证答案完整或准确;可以对照结果来源检查模型是否遗漏或误读了信息。
开发计划(尚未实现)¶
- [ ] 添加异步搜索支持(使用 aiohttp)
- [ ] 实现搜索结果缓存机制
- [ ] 支持更多搜索后端(通过
search_impl扩展) - [ ] 支持多语言搜索
- [ ] 添加搜索结果质量评分
- [ ] 实现搜索历史记录
- [ ] 集成重试机制(使用 tenacity)
- [ ] 优化长对话的上下文管理
相关链接¶
选择示例回放或联网查询¶
要熟悉轨迹格式,选 offline-demo,使用预先编写的搜索结果。要观察模型会不会根据第一次返回的内容改写查询,再配置 Kimi 或 Parallel 路线。
配置选项¶
| 配置项 | 说明 | 默认值 |
|---|---|---|
MOONSHOT_API_KEY |
直连 Moonshot 的模型密钥 | 联网时与 OPENROUTER_API_KEY 任选其一 |
KIMI_API_KEY |
旧版 API 密钥变量名(向后兼容) | 可选 |
OPENROUTER_API_KEY |
OpenRouter 的模型密钥 | 联网时与 MOONSHOT_API_KEY 任选其一 |
KIMI_BASE_URL |
API 基础 URL | https://api.moonshot.cn/v1 |
DEFAULT_MODEL |
默认模型 | kimi-k3 |
MAX_SEARCH_ITERATIONS |
最大搜索迭代次数(Config 中设置) | 5 |
SEARCH_TIMEOUT |
模型和搜索请求的超时(秒) | 180 |
temperature |
控制生成内容的创造性 | 0.6 |
跟踪一次搜索循环¶
先运行下方离线命令,不需要模型凭据。按顺序阅读终端输出,再打开 demo.json,把 trace 中的步骤与最终 answer 对照。理解后,按下文配置联网模式,在另一个问题上观察模型是否真的发起了搜索。
先做一个小规模观察¶
在本实验目录运行:
快速开始¶
1. 安装依赖¶
# 推荐在仓库根目录使用统一的第 1 章环境
uv sync --locked --extra ch1
# 切换目录前先激活环境:
# macOS/Linux:
source .venv/bin/activate
# Windows PowerShell:.venv\Scripts\Activate.ps1
# Windows cmd:.venv\Scripts\activate.bat
# 未安装 uv 时可用 pip 兜底:
# python -m pip install -e ".[ch1]"
# 进入本实验目录,后续命令都在这里运行
cd chapter1/web-search-agent
# 迁移期间仍支持单项目兼容路径:
# python -m pip install -r requirements.txt
2. 配置 API Key¶
直连 Kimi。从 Moonshot AI 平台 获取 API Key,然后设置环境变量:
或创建 .env 文件:
注意: 为了向后兼容,系统也支持使用 KIMI_API_KEY 环境变量。
通过 OpenRouter。设置 OPENROUTER_API_KEY,并留空 MOONSHOT_API_KEY 和 KIMI_API_KEY。默认模型 kimi-k3 会映射为 moonshotai/kimi-k2.6。如果手动选择模型,请使用支持工具调用的模型。搜索后端根据实际使用的模型后端选择。
省略 --provider 时,OpenRouter 用 Parallel MCP,直连 Kimi 用 Formula。在 OpenRouter 上显式指定 --provider kimi 时只调用模型;在直连 Kimi 时也可以显式指定 --provider parallel。
3. 运行 Agent¶
main.py 提供了完整的命令行接口(中文帮助)。查看全部参数:
| 参数 | 说明 | 默认值 |
|---|---|---|
query |
要提问的问题(位置参数);省略则进入交互模式 | 无 |
--provider |
kimi(Formula;在 OpenRouter 上只调用模型)、parallel(Parallel MCP)、specstream(SpecStream Search API,需要 SPECSTREAM_API_KEY)、offline-demo(离线示例轨迹) |
直连 Kimi 为 kimi,OpenRouter 为 parallel |
--model |
模型名称 | kimi-k3 |
--max-steps |
最大 ReAct 迭代次数 | 5 |
--base-url |
API 基础 URL | https://api.moonshot.cn/v1 |
--api-key |
Kimi API Key(默认读环境变量) | 环境变量 |
--output, -o |
将问题、ReAct 轨迹与答案保存为 JSON | 无 |
--quiet |
不实时打印 ReAct 轨迹 | 打印 |
离线演示 ReAct 循环(无需 API Key,回放示例轨迹,直观展示“想→做→看”):
用 OpenRouter 体验联网搜索。 上面的安装命令已包含 Parallel MCP 所需的 SDK。只设置 OPENROUTER_API_KEY 后,在本实验目录运行:
程序启动时会显示搜索后端。只有模型调用搜索工具时,生成的搜索词才会发到 https://mcp.parallel.ai/mcp。匿名搜索无需 Parallel API Key,并受匿名调用频率限制。模型调用的费用和配额以服务商为准。打开 result.json,用 provider 和 search_provider 查看模型后端和搜索选项,在 trace 的 observation 步骤里把网页链接和原文摘录与答案引用对照。实验 1-2 的 Formula 验收使用直连 Kimi。
换一个搜索后端对比。 设置 SPECSTREAM_API_KEY 后加上 --provider specstream,直连 Kimi 和 OpenRouter 都可以用。工具定义和 observation 里的结果结构与 Parallel 路线相同(title、url、excerpts),所以同一个问题可以分别用两个后端跑一遍,直接比较模型拿到的资料和最终引用。搜索词只在模型调用工具时发到 https://api.specstream.ai/v1/web-search,每次取 5 条结果。
交互模式(每次提问独立,search_and_answer 会重置对话历史,无跨问题上下文):
单次问答(运行时逐步打印思考/行动/观察轨迹):
快速体验(引导式交互):
高级示例:
运行时会实时打印 ReAct 轨迹:💭 思考 → 🔧 行动(调用
web_search)→ 👀 观察(搜索结果)→ ✅ 最终答案,对应本章讲的“想→做→看”循环。agent.get_trace()可获取结构化轨迹,--output可将其存为 JSON。
使用示例¶
基础使用¶
from agent import WebSearchAgent
from config import Config
# 创建 Agent
agent = WebSearchAgent(api_key=Config.get_api_key())
# 提问并获取答案
question = "Python 3.12 有哪些新特性?"
answer = agent.search_and_answer(question)
print(answer)
高级功能¶
包含:
- 批量搜索:同时搜索多个问题
- 带上下文搜索:提供背景信息进行更精准的搜索
- 比较搜索:搜索并比较多个项目
- 事实核查:验证陈述的真实性
- 研究助手:深度研究某个主题
使用建议¶
- 明确问题: 提供清晰、具体的问题以获得更好的答案
- 提供上下文: 必要时提供背景信息帮助 Agent 理解
- 迭代优化: 如果答案不满意,可以提供更多细节重新提问
- 合理期望: Agent 基于搜索结果回答,可能无法回答所有问题
用搜索结果核对回答¶
离线输出证明的是流程可以展示,不是搜索服务已经连通。联网运行时,要同时检查工具执行状态、返回内容和答案引用。模型可能直接回答而不调用工具;此时应根据问题是否需要外部信息判断它的选择是否合理。
检查自己的解释¶
如果搜索结果互相矛盾,循环应继续搜索、向用户澄清,还是带着不确定性回答?
沿入口追到客户端循环¶
项目说明¶
Autonomous ReAct web-search agent on Kimi K3 using Moonshot's official Formula API (multi-round search + synthesis). 配套《深入理解 AI Agent》第 1 章 实验 1-2 ★:Kimi K3 原生 Agent 能力。
← Chapter 1 index / 返回第 1 章目录 · 📖 Read the chapter / 读本章正文(EN)
核心组件¶
agent.py — 核心 Agent 实现¶
WebSearchAgent: 主要的 Agent 类search_and_answer(): 执行 ReAct 循环并生成答案的主方法get_trace(): 返回上一次运行的结构化 ReAct 轨迹(思考/行动/观察/最终答案)_chat(): 与 Kimi API 进行对话交互_get_system_prompt(): 获取系统提示,定义 Agent 行为_get_tools(): 定义可用的工具(web_search)search_impl():parallel模式的搜索实现,返回带链接和摘录的资料specstream_search.search_impl():specstream模式的搜索实现,返回同样结构的资料format_trace_step(): 将一条轨迹步骤渲染为可读文本run_offline_demo(): 离线回放示例轨迹,无需 API Key 即可演示 ReAct 循环
config.py — 配置管理¶
- API 配置
- 模型选择
- 搜索参数设置
main.py — 主程序入口¶
build_parser(): argparse 命令行接口(中文帮助,见--help)run_interactive_mode(): 交互式对话模式run_single_question(): 单次问答模式- 离线演示模式(
--provider offline-demo)与 JSON 结果输出(--output) - 会话管理
quickstart.py — 快速体验脚本¶
demo_search(): 演示搜索功能interactive_mode(): 简化的交互模式- 彩色输出和用户引导
- API Key 配置检查
examples.py — 高级示例¶
AdvancedWebSearchAgent: 扩展功能的 Agent 类batch_search(): 批量处理多个问题search_with_context(): 带上下文的搜索comparative_search(): 比较多个项目fact_check(): 事实验证功能example_research_assistant(): 深度研究示例
先看一次完整流程¶
这个实验展示模型如何决定搜索、读取搜索结果,再回答问题。先运行离线演示,不需要 API Key:
# 在仓库根目录安装依赖并激活环境
uv sync --locked --extra ch1
source .venv/bin/activate
cd chapter1/web-search-agent
python main.py --provider offline-demo --output demo.json
Windows 的环境激活方式见下文“快速开始”。终端会依次展示思考、工具调用、观察和最终答案,
demo.json 会保存 question、trace 和 answer。其中的搜索内容是预先编写的,
用来解释程序流程;看到它正常输出,不代表真实搜索服务已经连通。
读代码时,从 main.py 的 main() 开始,找到 offline-demo 分支和 run_offline_demo()。
理解这条轨迹后,再按上面的说明配置 Moonshot 或 OpenRouter 模型密钥,运行一次联网问答。
运行注意事项¶
注意事项¶
- API 限制: 请注意 Kimi API 的调用限制和配额
- 搜索质量: 搜索结果质量依赖于 Kimi 的搜索能力
- 响应时间: 网络搜索本身需要时间,而
kimi-k3以reasoning_effort=max运行,单次调用常需一到数分钟,因此SEARCH_TIMEOUT默认为 180 秒 - 速率限制: 遇到 429 时 SDK 会自动重试,重试若把超时预算耗完,最终报出的是超时而不是速率限制;调大
SEARCH_TIMEOUT之前,先看日志里有没有429 - 内容准确性: Agent 会尽力提供准确信息,但建议对重要信息进行二次验证
Notes / 说明¶
- License: MIT. 许可证:MIT。
- Author / 作者: AI Agent 实战训练营;version / 版本: 1.0.0.
- Prefer
--provider offline-demofirst if you only want to see the ReAct shape without spending API quota. 若只想先看 ReAct 形态、不消耗配额,优先运行--provider offline-demo。 - Moonshot Formula search uses a Moonshot key. In Parallel mode, the agent uses the configured model key for inference and sends search queries to Parallel anonymously. Moonshot Formula 搜索需要 Moonshot Key。在 Parallel 模式下,模型调用使用已配置的模型密钥,搜索请求以匿名方式发给 Parallel。
English¶
Overview¶
This project shows how a model decides when to search and how to use the
results. Direct Kimi uses Moonshot's moonshot/web-search:latest Formula by
default. OpenRouter uses Parallel MCP by default. Both routes let the model:
- Understand the question: analyze the user query and identify information needs
- Search when needed: call
web_searchto fetch live web information - Iterate: call search multiple times until evidence is sufficient
- Synthesize: combine multi-source results into a clear, accurate answer
It demonstrates the “Model as Agent” idea and the ReAct loop (think → act → observe).
Exact Formula route¶
Kimi K3's current official hosted-search route is not the legacy
builtin_function passthrough. Every independent question performs this exact
provider-controlled sequence:
GET /v1/formulas/moonshot/web-search:latest/toolsobtains Moonshot's authoritative standardfunctiondeclaration namedweb_search.- The declaration is sent unchanged to
POST /v1/chat/completionswith the conversation. Kimi decides whether and how often to call it. - For each model tool call, the implementation passes the returned
nameand raw serializedargumentsunchanged toPOST /v1/formulas/moonshot/web-search:latest/fibers. - Only HTTP-successful Fibers with
status == "succeeded"are accepted. Theircontext.output(or encrypted output) is returned as the matching tool result.
On the direct Kimi route, Moonshot hosts the Formula search engine. See the official Formula tool guide and web-search guide.
Architecture¶
This diagram follows the direct Kimi route.
Quick Start¶
1. Install dependencies¶
# Recommended from the repository root: use the shared Chapter 1 environment
uv sync --locked --extra ch1
# Activate it before changing directories:
# macOS/Linux:
source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
# Windows cmd: .venv\Scripts\activate.bat
# pip fallback when uv is not installed:
# python -m pip install -e ".[ch1]"
# Enter this experiment directory for the commands below
cd chapter1/web-search-agent
# Single-project compatibility path, still supported during migration:
# python -m pip install -r requirements.txt
2. Configure API Key¶
Get a key from the Moonshot AI platform, then set:
Or create a .env file:
Note: For backward compatibility, KIMI_API_KEY is also accepted.
To use OpenRouter, set OPENROUTER_API_KEY and leave MOONSHOT_API_KEY
and KIMI_API_KEY unset. The default model maps to moonshotai/kimi-k2.6.
If you choose a different model, use one that supports tool calls. With no
--provider flag, the resolved model backend determines the search tool.
OpenRouter uses Parallel MCP and direct Kimi uses Formula. On OpenRouter,
pass --provider kimi for a model-only answer. On direct Kimi you can pass
--provider parallel to choose Parallel explicitly.
3. Run the Agent¶
main.py provides a full CLI (Chinese help). List all flags:
| Flag | Description | Default |
|---|---|---|
query |
Question (positional); omit for interactive mode | none |
--provider |
kimi (Formula, or model-only on OpenRouter), parallel (Parallel MCP), specstream (SpecStream Search API, needs SPECSTREAM_API_KEY), offline-demo (offline sample trace) |
kimi on direct Kimi, parallel on OpenRouter |
--model |
Model name | kimi-k3 |
--max-steps |
Max ReAct iterations | 5 |
--base-url |
API base URL | https://api.moonshot.cn/v1 |
--api-key |
Kimi API key (else from env) | env |
--output, -o |
Save question, ReAct trace, and answer as JSON | none |
--quiet |
Do not stream ReAct trace live | stream on |
Offline ReAct demo (no API key; replays a sample trace to show think → act → observe):
Try live search with OpenRouter. The install commands above include the SDK for Parallel MCP. With only OPENROUTER_API_KEY set, run:
python main.py --output result.json "Find the official Python 3.13 release notes and cite the section on experimental free-threading."
The CLI displays the search backend at startup. It sends the model's search terms to https://mcp.parallel.ai/mcp only when the model calls the search tool. Anonymous search needs no Parallel API key and has its own rate limits. Your model provider's pricing and quotas apply to inference. In result.json, provider identifies the model backend and search_provider records the search choice. Compare the URLs and excerpts in the observation step with the citations in the answer. Use direct Kimi for the Experiment 1-2 Formula acceptance check.
Compare search backends. Set SPECSTREAM_API_KEY and add --provider specstream, on direct Kimi or OpenRouter. The tool schema and the observation payload have the same shape as the Parallel route (title, url, excerpts), so you can run one question through both and compare what the model read with what it cited. Search terms go to https://api.specstream.ai/v1/web-search only when the model calls the tool, five results per call.
Interactive mode (ongoing dialogue):
Single question (streams think / act / observe steps):
Guided quickstart:
Advanced examples:
At runtime the agent prints a ReAct trace: 💭 think → 🔧 act (
web_search) → 👀 observe (search results) → ✅ final answer. Useagent.get_trace()for a structured trace, or--outputto save JSON.
Usage Examples¶
Basic usage¶
from agent import WebSearchAgent
from config import Config
# Create Agent
agent = WebSearchAgent(api_key=Config.get_api_key())
# Ask and get an answer
question = "Python 3.12 有哪些新特性?"
answer = agent.search_and_answer(question)
print(answer)
Advanced features¶
Includes:
- Batch search: multiple questions in one run
- Context-aware search: supply background for sharper queries
- Comparative search: search and compare items
- Fact check: verify claims
- Research assistant: deeper topic research
Core Components¶
agent.py — core agent¶
WebSearchAgent: main agent classsearch_and_answer(): run the ReAct loop and produce an answerget_trace(): structured ReAct trace of the last run (think / act / observe / final)_chat(): chat with the Kimi API_get_system_prompt(): system prompt defining agent behavior_get_tools(): tool definitions ($web_search)search_impl(): returns source links and excerpts inparallelmodespecstream_search.search_impl(): the same result shape inspecstreammodeformat_trace_step(): render one trace step as readable textrun_offline_demo(): offline sample-trace replay (no API key)
config.py — configuration¶
- API settings
- Model selection
- Search parameters
main.py — entry point¶
build_parser(): argparse CLI (Chinese help; see--help)run_interactive_mode(): interactive dialoguerun_single_question(): one-shot Q&A- Offline demo (
--provider offline-demo) and JSON output (--output) - Session management
quickstart.py — guided demo¶
demo_search(): demo searchinteractive_mode(): simplified interactive mode- Colored output and user guidance
- API key checks
examples.py — advanced demos¶
AdvancedWebSearchAgent: extended agentbatch_search(): batch questionssearch_with_context(): context-aware searchcomparative_search(): multi-item comparisonfact_check(): fact verificationexample_research_assistant(): deep research example
Configuration Options¶
| Item | Description | Default |
|---|---|---|
MOONSHOT_API_KEY |
Direct Moonshot model key | Set this or OPENROUTER_API_KEY for online use |
KIMI_API_KEY |
Legacy key env name (compat) | optional |
OPENROUTER_API_KEY |
OpenRouter model key | Set this or MOONSHOT_API_KEY for online use |
KIMI_BASE_URL |
API base URL | https://api.moonshot.cn/v1 |
DEFAULT_MODEL |
Default model | kimi-k3 |
MAX_SEARCH_ITERATIONS |
Max search iterations (in Config) | 5 |
SEARCH_TIMEOUT |
Timeout in seconds for model and search requests | 180 |
temperature |
Generation creativity | 0.6 |
Technical Notes¶
Core stack¶
- Kimi API: Moonshot Kimi K3 (
kimi-k3), a reasoning model with native web search - Built-in tool calling: Kimi
$web_searchbuilt-in function - Iterative search: up to 5 rounds until information is sufficient
- Context management: each question is independent --
search_and_answerresets conversation history every call, so there is no cross-question memory - Temperature control: adjustable creativity
Strengths¶
- Live information: up-to-date web results
- Intent understanding: search aligned with the question
- Structured answers: well-organized responses
- Extensible: easy to add tools via
search_impland related hooks
Development ideas (not implemented)¶
- [ ] Async search (e.g. aiohttp)
- [ ] Result caching
- [ ] More search backends via
search_impl - [ ] Multilingual search
- [ ] Result quality scoring
- [ ] Search history
- [ ] Retries (e.g. tenacity)
- [ ] Better long-dialogue context management
Caveats¶
- API limits: respect Kimi quotas and rate limits
- Search quality: depends on Kimi’s search capability
- Latency: web search can take time, and
kimi-k3runs withreasoning_effort=max, so a single completion often takes one to a few minutes — hence the 180 s defaultSEARCH_TIMEOUT - Rate limits: on a 429 the SDK retries automatically; if the retries use up the timeout budget you will see a timeout rather than a rate-limit error, so check the log for
429before raisingSEARCH_TIMEOUT - Accuracy: double-check critical facts; the agent may still err
Usage tips¶
- Ask clearly: specific questions get better answers
- Give context: background helps when needed
- Iterate: refine with more detail if the first answer is weak
- Set expectations: answers are grounded in search results and may not cover everything