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

# LLM 对话

> 使用 hb.LLM 进行对话补全、流式输出与响应投影 (include projection)。

<Note>
  *`llm("hello")` 与 `llm.chat("hello")` 是同一调用。更短才是重点。*
</Note>

`chat` 是 `hb.LLM` 的主要文本入口。它接收 prompt、单条消息或消息列表，执行对话补全，并仅通过 `include` 投影返回你请求的字段。

<br />

## 1. 对话与调用 (Chat and Call)

`LLM` 可调用，因此 `llm("hello")` 与 `llm.chat("hello")` 等价。用 `system=...` 传入 system prompt，在构造时或调用时设置 provider 参数：

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

llm = hb.LLM(model="ds-flash")

text = llm.chat("Summarize HeavenBase in one sentence.")
same = llm("Summarize HeavenBase in one sentence.")

answer = llm.chat("What should I do next?", system="You are concise and practical.")

drafter = hb.LLM(model="ds-flash", temperature=0)
title = drafter.chat("Draft a title", max_tokens=24)
```

<br />

## 2. 消息输入 (Message Inputs)

`chat` 与 `stream` 接受单个字符串、一条 OpenAI 风格消息字典，或消息列表：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
llm.chat("Hello")

llm.chat({"role": "user", "content": "Hello"})

llm.chat([
    {"role": "system", "content": "Be direct."},
    {"role": "user", "content": "Explain vector search."},
])
```

格式化器也接受带 `model_dump()`、`to_dict()`、`dict()`、`json()`，或 `role` 与 `content` 属性的对象，因此 Pydantic 模型与 SDK 消息对象无需手动转换即可传入。

<br />

## 3. 多模态图像 (Multimodal Images)

对多模态模型，用 `images=` 传入图像输入。HeavenBase 将每个输入归一化为 `LLMImage`，并向最后一条 user 消息追加 OpenAI 兼容的 `image_url` 内容部分。

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
answer = hb.LLM(model="qwen3.6", provider="openrouter").chat(
    "What is in this image?",
    images=["./sample.png"],
)

for chunk in hb.LLM(model="gpt-nano").stream("Describe this image.", images=b"...png bytes..."):
    print(chunk, end="")
```

`images=` 接受 `LLMImage`、URL、data URL、base64 字符串、本地路径、类 bytes 对象、二进制文件对象、provider 风格字典、Pillow 图像，以及 numpy 兼容的 ndarray。单个值或可迭代对象均可。完整 `LLMImage` API 见 [Advanced LLM](/features/llm/advanced)。

<br />

## 4. 流式输出 (Streaming)

需要增量到达时使用 `stream`：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
for chunk in llm.stream("Write a short haiku"):
    print(chunk, end="")
```

`chat` 在内部走同一条流式路径并汇总最终响应。这使常规 chat、推理流、用量统计、结构化输出与 tool call 共用一条响应管线，因此无论你汇总还是迭代，`include` 字段含义一致。

<br />

## 5. Include 投影 (Include Projection)

`include` 参数选择响应字段。传 `None` 使用默认 `text` 值，传字符串选单字段，传列表选多个。未知字段名会抛出带上下文的错误。

* `text`：最终 assistant 文本，不含单独推理块。
* `think`：推理或思考内容，当 provider 单独流式输出时可用。
* `content`：用 `<think>` 标签包裹的 `think`，后接 `text`。
* `message`：OpenAI 格式的 assistant 响应字典，含 `role`、`content` 及可选 `tool_calls`；不是完整历史。
* `delta`：本次推理调用产生的新 OpenAI 格式消息。若有可执行工具，包括 assistant tool-call 消息、一条或多条 `role="tool"` 结果消息，以及最终 assistant 响应。
* `messages`：完整对话历史：归一化输入消息加 `delta`。
* `tool_calls`：来自 assistant 响应的归一化 OpenAI `tool_calls`。
* `usage`：本次调用的 provider 用量计数。常见键为 `prompt_tokens`、`completion_tokens` 与 `total_tokens`；流式 usage 块通过累加数值计数器、每个键保留首个非数值来合并。
* `raw`：原始 provider 载荷。
* `elapsed`：请求耗时（秒）。
* `created_at`：本地响应创建时间戳。
* `structured`：解析后的结构化输出。

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
detail = llm.chat(
    "Reply with exactly: hb-ok",
    include=["text", "usage", "elapsed"],
    reduce=False,
    max_tokens=8,
)
```

当 `stream` 包含 `delta` 或 `messages` 时，渐进内容仍正常到达，HeavenBase 会发出一条最终元数据块，其中 `text`/`think` 为空并带上完整的消息 `delta`。单字段 `include` 且 `reduce=True`（默认）时，直接返回值而非单键字典。

<br />

## 6. 思考与推理 (Thinking and Reasoning)

推理 preset 默认启用规范 `think` 选项。可在每次调用覆盖，HeavenBase 将 `think=True` 与 `think=False` 都转换为 OpenAI 兼容入口 (Gateway) 的 gateway 级 `extra_body.reasoning`。模型支持时，将 `think` 与 `reasoning_effort` 及可选推理预算配对使用：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
result = hb.LLM(preset="reason").chat(
    "Solve 17 * 23.",
    think=True,
    reasoning_effort="medium",
    include=["think", "text"],
    reduce=False,
)
```

CLI 输出在打印正常答案文本前，将可见思考块包裹在 `<think>` 与 `</think>` 中。`anthropic` 入口 (Gateway) 将 `think` 映射为原生 Claude thinking，并将思考块归一化回 `think` include 字段。传 `think=False` 可完全抑制响应及其消息历史中的推理内容。

<br />

## 7. CLI 对话与 MCP 工具 (CLI Chat and MCP Tools)

`hb llm chat` 以 `chat` preset 发送单条消息。用 `--preset`、`--model`、`--provider` 覆盖 preset、model 或 provider；用 `--verbose` 查看解析后的 spec；用 `--input` 从文件读取 prompt。

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
$ hb llm chat "What is a data gateway?"
$ hb llm chat --preset system "Name three data backends"
$ hb llm chat --model sonnet --provider anthropic "Draft a release note"
```

添加 `--mcp` 可在单轮 agentic 调用中附加 MCP 工具。HeavenBase 将每个来源导入为工具集 (Toolkit)，让模型调用工具直至产生最终 assistant 响应，然后打印 tool call 与 tool 结果，再输出最终答案。MCP 来源接受 URL 或规范 `namespace.toolkit:version` 引用。负版本号表示相对最新版本的偏移：`-1` 为最新，`-2` 为次新。工具循环由 `--max-steps` 上限控制，默认 20 个 assistant 步。

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
hb llm chat --mcp quickstart.math-tools:-1 "What's 42 * 73?"
hb llm chat --mcp quickstart.math-tools:-1 --max-steps 20 "What's 42 * 73?"
hb llm chat --mcp http://127.0.0.1:7001/mcp "List the available workspace entities."
```

用 `--copy` / `-cp` 将最终响应复制到剪贴板，用 `--json` 输出 JSON 载荷而非纯文本。

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
hb llm chat "Summarize HeavenBase in one sentence." --copy
hb llm chat "Summarize HeavenBase in one sentence." --json --copy
```

<Tip>
  交互式多轮 tool use 请改用 `hb llm session`。完整可执行工具契约见 [Sessions](/features/llm/sessions) 与 [Tool Use](/features/llm/tool-use)。
</Tip>

<br />

## Further Exploration

<Tip>
  **Related resources:**

  * [LLM Overview](/features/llm/overview) - preset、模型目录与解析模型。
  * [Tool Use](/features/llm/tool-use) - 仅 schema 与可执行工具、MCP 工具集 (Toolkit) 与结构化输出。
  * [First LLM](/quickstart/first-llm) - `hb llm` 与 `hb.LLM` 快速入门导览。
</Tip>

<br />
