Skip to content

Kimi K2.6 的代码执行和工具调用能力可用于构建行业研究 Agent:自动联网搜索 → 分析数据 → 生成 Python 图表 → 编译 LaTeX 报告。本文提供 Prompt 设计规范、工具注册方式和完整的多步 Agent 代码框架,适合企业级自动化报告场景。

用 Kimi K2.6 搭建自定义 Agent

典型 Agent 架构

以行业研究助手为例,一个典型的 Agent 任务流程:

用户需求 → 任务拆解 → 工具调用(联网搜索 + 数据获取)→ 数据分析 + 图表生成 → LaTeX 报告编译 → 输出 PDF

Kimi K2.6 会根据当前上下文自动决定是否调用工具,不需要开发者手动判断每一步。


Prompt 设计规范

高质量的 System Prompt 是 Agent 稳定性的关键:

python
SYSTEM_PROMPT = """你是一个专业的行业研究助手,负责生成高质量分析报告。

输出规范:
- 所有输出内容必须与用户提问语言保持一致(中文问题用中文回复)
- 禁止混合语言输出
- 报告格式:使用标准 LaTeX 模板,配色方案为蓝白主色
- 数值必须有数据来源标注

工具使用规范:
- 联网搜索用于获取实时市场数据
- 代码执行用于数据处理和图表生成
- 每步操作前说明目的
"""

工具注册

python
from openai import OpenAI
import json

client = OpenAI(
    api_key="$MOONSHOT_API_KEY",
    base_url="https://api.moonshot.cn/v1",
)

tools = [
    {
        "type": "builtin_function",
        "function": {"name": "$web_search"},  # 联网搜索(需禁用 thinking)
    },
    {
        "type": "function",
        "function": {
            "name": "get_company_info",
            "description": "获取公司基本信息和财务数据",
            "parameters": {
                "type": "object",
                "properties": {
                    "company_name": {"type": "string", "description": "公司名称"},
                    "data_type": {
                        "type": "string",
                        "enum": ["basic", "financial", "news"],
                        "description": "数据类型",
                    },
                },
                "required": ["company_name", "data_type"],
            },
        },
    },
]

注意:同时使用 $web_search 时必须禁用 thinking:extra_body={"thinking": {"type": "disabled"}}


Agent 执行循环

python
def run_agent(user_query: str) -> str:
    messages = [
        {"role": "system", "content": SYSTEM_PROMPT},
        {"role": "user", "content": user_query},
    ]

    while True:
        response = client.chat.completions.create(
            model="kimi-k2.6",
            messages=messages,
            tools=tools,
            max_tokens=65536,
            extra_body={"thinking": {"type": "disabled"}},  # 使用 $web_search 时必须禁用
        )
        choice = response.choices[0]

        if choice.finish_reason != "tool_calls":
            return choice.message.content

        # 处理工具调用
        messages.append(choice.message)
        for tool_call in choice.message.tool_calls:
            result = dispatch_tool(tool_call)
            messages.append({
                "role": "tool",
                "tool_call_id": tool_call.id,
                "content": json.dumps(result, ensure_ascii=False),
            })

def dispatch_tool(tool_call):
    name = tool_call.function.name
    args = json.loads(tool_call.function.arguments)

    if name == "$web_search":
        return args  # 原样返回,Kimi 服务端执行搜索
    elif name == "get_company_info":
        return fetch_company_data(args["company_name"], args["data_type"])
    else:
        return {"error": f"未知工具: {name}"}

如果不需要联网搜索,可以启用 thinking 获得更好的推理效果:

python
response = client.chat.completions.create(
    model="kimi-k2.6",
    messages=messages,
    tools=custom_tools_only,  # 不含 $web_search
    extra_body={"thinking": {"type": "enabled"}},
    temperature=1.0,
    max_tokens=65536,
)
# 每轮必须将 reasoning_content 保留传入下一轮

常见问题

Q: Agent 调用工具后输出质量不稳定怎么办?

A: 主要原因通常是 System Prompt 不够具体。建议:①在 Prompt 中明确每个工具的使用场景和格式要求;②在工具描述(description 字段)中给出具体的调用示例;③对关键约束重复强调(如"必须先搜索再分析")。

Q: 如何控制 Agent 的工具调用次数,防止无限循环?

A: 在执行循环中设置最大轮次限制:for _ in range(max_rounds): ...。建议生产环境设置 10~20 轮上限,超限后返回已有结果或报错。

Q: Agent 任务耗时太长怎么办?

A: 考虑任务拆分和并行化:把一个大任务拆成多个独立子任务,用 asyncio.gather 并发执行,最后合并结果。Kimi K2.6 的 256k 上下文足够承载复杂的合并报告。