> ## Documentation Index
> Fetch the complete documentation index at: https://ahvn.top/llms.txt
> Use this file to discover all available pages before exploring further.

# Tool Use

> 结构化 tool call、可执行工具、MCP 工具集 (Toolkit) 与结构化输出。

<Note>
  *模型提议。HeavenBase 可执行——或只把 JSON 交给你然后退后。*
</Note>

Tool use 是 chat 不再只是文本的地方。向 `chat`、`stream` 或 `LLMSession` 传入 tools，HeavenBase 会归一化 schema、运行可执行 callable，并通过 `include` 投影完整轮次。

## 1. 可传入的内容 (What You Can Pass)

`tools` 列表接受：

* OpenAI 兼容 function schema 字典。
* 带类型注解与 docstring 的普通 Python callable。
* HeavenBase `Tool` 对象。
* HeavenBase `Toolkit` 对象，包括用 `Toolkit.from_fastmcp(...)` 导入的 MCP 服务器。

仅 schema 的工具发送给 provider 并以 `tool_calls` 返回。可执行工具自动运行，其 `role="tool"` 结果消息出现在 `delta` 与 `messages` 中。

Tool 执行错误序列化为结构化 tool 结果内容：

```json theme={"theme":{"light":"github-light","dark":"github-dark"}}
{"ok": false, "error": {"type": "ValueError", "message": "bad input"}}
```

<br />

## 2. 仅 Schema 的工具 (Schema-Only Tools)

由其他进程执行调用时使用仅 schema 的工具：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heavenbase as hb

llm = hb.LLM(preset="chat")

tools = [
    {
        "type": "function",
        "function": {
            "name": "lookup_user",
            "description": "Look up a user by id",
            "parameters": {
                "type": "object",
                "properties": {"user_id": {"type": "string"}},
                "required": ["user_id"],
            },
        },
    }
]

calls = llm.chat("Find user 42", tools=tools, include="tool_calls")
```

Tool call 从流式 delta 收集，并以标准 OpenAI `tool_calls` 形状返回。

<br />

## 3. 可执行工具 (Executable Tools)

需要 HeavenBase 为模型运行工具时使用函数或工具集 (Toolkit)：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heavenbase as hb


def add(left: int, right: int) -> int:
    """Add two numbers."""
    return left + right


llm = hb.LLM(preset="chat")
result = llm.chat(
    "Use the add tool to calculate 42 + 73.",
    tools=[add],
    include=["text", "delta"],
    reduce=False,
)

print(result["text"])
print([message["role"] for message in result["delta"]])
```

当模型调用 `add` 时，HeavenBase 追加 assistant tool-call 消息、tool 结果消息，再向模型请求最终答案。典型 `delta` 如下：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
[
    {"role": "assistant", "tool_calls": [...]},
    {"role": "tool", "tool_call_id": "...", "name": "add", "content": "115"},
    {"role": "assistant", "content": "42 + 73 = 115."},
]
```

用 `max_tool_turns` 控制 assistant 迭代次数（Python 默认 `8`，CLI 映射自 `--max-steps`）：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
llm.chat("Plan a three-step fix.", tools=[...], max_tool_turns=12)
```

异步 callable 需使用 `achat` 而非 `chat`。

<br />

## 4. MCP 作为工具集 (MCP as Toolkit)

MCP 服务器导入为 HeavenBase 工具集 (Toolkit) 后成为普通工具：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heavenbase as hb

workspace = hb.HeavenBase("demo", backends={"main": {"type": "inmem"}})
server_toolkit = workspace.to_mcp(name="demo-heavenbase")
mcp_tools = hb.Toolkit.from_fastmcp(server_toolkit.to_fastmcp())

answer = hb.LLM(preset="chat").chat(
    "List entities in the workspace.",
    tools=[mcp_tools],
)
```

FastMCP client 接受的 HTTP/SSE MCP URL 同样适用。

CLI 暴露相同执行路径：

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
hb llm chat --mcp quickstart.math-tools:-1 "Use the math tools for 42 * 73."
hb llm chat --mcp quickstart.math-tools:-1 --max-steps 20 "Use the math tools for 42 * 73."
hb llm session --mcp http://127.0.0.1:7001/mcp
```

会话内用 `/mcp SOURCE` 添加另一 MCP 来源。`hb llm chat --max-steps` 限制 tool 循环中的 assistant 迭代；默认 20。

<br />

## 5. 结构化输出 (Structured Output)

直接传入 OpenAI 兼容的 `response_format` 参数：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
import heavenbase as hb

llm = hb.LLM(preset="chat")

data = llm.chat(
    "Return JSON with keys name and score.",
    response_format={"type": "json_object"},
    include="structured",
)
```

多数 provider 通过常规路径流式输出结构化内容。已知模型对流式结构化 JSON 不可靠时，其模型默认可设 `structured_stream: false`。

需要单一可靠载荷时强制非流式结构化调用：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
data = llm.chat(
    "Return JSON with key ok=true.",
    response_format={"type": "json_object"},
    include="structured",
    enforce_non_stream_structured=True,
)
```

对 `stream(..., enforce_non_stream_structured=True)`，HeavenBase 执行一次非流式请求并 yield 单个投影块。

<br />

## 6. Tool-Call 修复 (Tool-Call Repair)

部分 provider 在 `tool_calls[].function.arguments` 中返回畸形 JSON。HeavenBase 可在执行前修复常见错误——围栏代码块、括号不平衡、缺失必填字段。

修复默认关闭。全局启用：

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
hb cfg set heavenbase.llm.tool_call_repair.enabled true
```

或按实例：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
llm = hb.LLM(preset="chat", tool_call_repair={"enabled": True})
result = llm.chat("Use the tool.", tools=[add], repair_tool_calls=True)
```

在 config 中设 `strict: true` 可在修复失败时抛出异常，而非返回原始参数。修复行为细节见 [Advanced LLM](/features/llm/advanced)。

<br />

## Further Exploration

<Tip>
  **Related resources:**

  * [Sessions](/features/llm/sessions) — 使用 `LLMSession` 与 `hb llm session` 的多轮 tool use。
  * [LLM Chat](/features/llm/chat) — 单轮 agentic 调用的 CLI `--mcp`。
  * [First MCP](/quickstart/first-mcp) — 从快速入门附加数学工具集 (Toolkit)。
</Tip>

<br />
