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

# Advanced LLM

> 入口 (Gateway)、响应缓存、client 导出、图像生成与异步 API。

<Note>
  *默认配置帮你起步。需要看清接线时，请看本页。*
</Note>

多数工作流不会离开 `hb.LLM(preset="chat")` 与默认 OpenAI 兼容入口 (Gateway)。当你经 Portkey 路由、缓存确定性调用、导出 SDK client 或生成图像时，同一解析模型仍然适用——preset、model、provider、gateway。

<br />

## 1. 入口 (Gateway) 详解 (Gateways in Depth)

默认入口 (Gateway) 为 `openai`。它用 OpenAI Python SDK 访问 provider 的 OpenAI 兼容端点 (Endpoint)，因此无需 Portkey、LiteLLM、Bifrost 或原生 Anthropic SDK 进程。

| Gateway     | Use when                                              |
| ----------- | ----------------------------------------------------- |
| `openai`    | 你想用 OpenAI Python SDK 访问 OpenAI 兼容端点 (Endpoint)。这是默认。 |
| `anthropic` | 你想用官方 Anthropic Python SDK 与原生 Messages 载荷。           |
| `portkey`   | 你需要入口 (Gateway) 级路由、可观测性、缓存或策略控制。                     |
| `bifrost`   | 你运行 Bifrost 兼容入口 (Gateway) 并想要 provider 前缀模型路由。       |
| `litellm`   | 你已通过 LiteLLM Python 入口 (Gateway) 标准化 provider 路由。     |
| `mock`      | 你需要测试与 demo 用的确定性离线行为。                                |

需要入口 (Gateway) 级路由、可观测性、缓存或策略控制时使用 Portkey：

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
export PORTKEY_API_KEY="..."
```

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

llm = hb.LLM(model="ds-flash", provider="deepseek", gateway="portkey")
```

其他入口 (Gateway) 说明：

* `litellm` 发送 provider 前缀模型 ID，例如 `deepseek/deepseek-v4-flash`。
* `bifrost` 发送 provider 前缀模型 ID，并使用 `BIFROST_BASE_URL`，默认为 `http://localhost:8080/v1`。
* `mock` 保持离线并使用内置 mock 适配器。

Portkey、LiteLLM 与 Bifrost 今日可路由 Anthropic 流量。除非工作负载需要独立于 provider、gateway 与 `base_url` 配置的载荷族策略，否则将端点切换保留在这些层。

上游临时限制会明确抛出：

* `gateway="portkey"` 搭配 `provider="openrouter"` 的嵌入在 Portkey 入口 (Gateway) 支持落地前被阻止。
* Bifrost 图像生成在上游图像支持未解决前被阻止。
* 原生 `anthropic` 入口 (Gateway) 对嵌入与图像生成抛出异常，因为 Claude Messages 不提供这些操作。

若非默认入口 (Gateway) 无法被当前环境导入，`hb.LLM` 回退到 `openai` 入口 (Gateway)。

分步入入口 (Gateway) 配置见 [First LLM](/quickstart/first-llm) §5.2 与 [LLM providers](/integrations/llm-providers)。

<br />

## 2. 响应缓存 (Response Caching)

HeavenBase 在由 SQLite 实体支撑的专用 `llm-cache` 工作区中缓存归一化 LLM 响应。三个命名空间：`text` 用于 chat 补全，`embedding` 用于向量，`image` 用于生成图像。

缓存默认启用（`heavenbase.llm.cache.enabled: true`）。需要全新 provider 调用时禁用：

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

llm = hb.LLM(preset="chat", cache=False)
text = llm.chat("Reply with exactly: hb-ok")
```

按调用覆盖接受 `cache=False`、`cache=True` 或自定义 cache config 字典。Chat 缓存自动跳过 tool 循环——可执行工具会禁用该次调用的 text 缓存。

默认策略为 `deterministic`。Text 与 image 缓存写入要求确定性请求参数：`temperature=0`（或未设置且固定 `seed`）、默认 `top_p`/`top_k`，图像还需设置 `seed`。无 seed 的随机调用绕过缓存读写。

在 `heavenbase.llm.cache.namespaces` 下配置命名空间：

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
hb cfg set heavenbase.llm.cache.namespaces.text.ttl_seconds 86400
hb cfg set heavenbase.llm.cache.namespaces.embedding.enabled true
```

嵌入缓存按输入哈希在 [Embeddings](/features/llm/embeddings) 所述批处理路径内去重。

<br />

## 3. Client 复用与 SDK 导出 (Client Reuse and SDK Exports)

每个解析后的 `LLMSpec` 可产生确定性哈希键：

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

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

spec_key = llm.spec.hash_key()
client_key = llm.spec.client_key()
```

`hash_key()` 包含解析后的 model、provider、gateway 模式、请求默认与物化解析值。`client_key()` 仅包含入口 (Gateway) client 构造字段：gateway、API key、base URL、headers、timeout 与 retries。

`openai`、`portkey`、`bifrost` 与 `anthropic` 的 SDK 适配器以 `client_key()` 为键保留内存缓存，因此重复的 `LLM` 实例复用同一 SDK client。

OpenAI 兼容 `LLM` 实例可在外部库拥有调用循环时导出原始 SDK client：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
llm = hb.LLM(preset="chat")
client = llm.to_client()       # openai.OpenAI
aclient = llm.to_aclient()     # openai.AsyncOpenAI

response = client.chat.completions.create(
    messages=[{"role": "user", "content": "Hello"}],
    **llm.to_args(),
)
```

`to_client()`、`to_aclient()` 与 `to_args()` 适用于 OpenAI 兼容入口 (Gateway)：`openai`、`portkey` 或 `bifrost`。对 `litellm`、`anthropic` 与 `mock` 抛出 `ValueError`。

对原生 Anthropic 入口 (Gateway)：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
llm = hb.LLM(model="sonnet", provider="anthropic", gateway="anthropic")
client = llm.to_anthropic_client()
aclient = llm.to_anthropic_aclient()
```

OpenAI Agents SDK 集成模式见 [First LLM](/quickstart/first-llm) §5.3。

<br />

## 4. 图像生成 (Image Generation)

用 `imagen` 获取图像生成响应：

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

image = hb.LLM(preset="imagen").imagen("A clean product render of a white ceramic mug")
image.save("mug.png")
image.to_pil().show()
```

内置图像模型为 `gpt-5-image-mini` 与 `gpt-5.4-image-2`：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
image = hb.LLM(model="gpt-image-2").imagen("A small product icon for HB")
```

图像响应尽可能归一化为 `LLMImage` 对象；原始 provider 载荷仍可通过 `include="raw"` 获取。

`imagen` 接受与 chat 相同的 `images=` 输入格式作为参考图像：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
reference = hb.LLMImage.from_any("./style-reference.png")
image = hb.LLM(preset="imagen").imagen("Apply this style to an HB mark", images=reference)
```

<br />

## 5. LLMImage API

`LLMImage` 是 chat 输入、参考图像与生成输出的共享图像类型。

工厂方法归一化常见来源：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
from heavenbase.utils import LLMImage

img = LLMImage.from_any("./photo.png")
img = LLMImage.from_bytes(raw_bytes, format="png")
img = LLMImage.from_b64("...")
img = LLMImage.from_url("https://example.com/image.png")
img = LLMImage.from_provider_item(provider_response_item)
```

转换辅助方法：

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
img.to_bytes()
img.to_b64()
img.to_data_url()
img.to_dict()      # OpenAI-compatible image_url content part
img.to_pil()
img.save("out.png")
```

URL 支撑的 `LLMImage` 仅在转换为 bytes、base64、data URL 或保存时才惰性拉取。拉取超时由 `heavenbase.llm.image_url_timeout` 配置。

<br />

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

`LLMToolCallRepair` 在执行前修复畸形的 OpenAI 风格 tool-call 参数字符串。它剥离 markdown 围栏、平衡 JSON 括号、填充缺失必填 schema 字段，并重新序列化为紧凑 JSON。

全局 config 位于 `heavenbase.llm.tool_call_repair`：

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

向 `hb.LLM(...)` 传入 `tool_call_repair={...}`，或在单次 `chat` 调用上传 `repair_tool_calls=True`。实例启用修复时，默认应用 `repair_tool_calls=True`。

`strict: true` 时，参数无法解析则抛出 `ValueError`，而非返回原始字符串。

<br />

## 7. 自定义 OpenAI 兼容提供商 (Custom OpenAI-Compatible Providers)

对实现 OpenAI API 但不在捆绑模型目录中的 provider，使用 `custom` preset：

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

llm = hb.LLM(
    preset="custom",
    base_url="http://localhost:9999/v1",
    model="third-party-model",
    api_key="optional-key",
)
```

custom provider 需要调用时 `base_url` 与具体 `model`。

<br />

## 8. 异步 API (Async APIs)

每个同步方法都有异步对应物：

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

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

async def main():
    text = await llm.achat("hello")
    async for chunk in llm.astream("Count to three."):
        print(chunk, end="")
    vec = await llm.aembed("semantic text")
    img = await llm.aimagen("a blue square")

asyncio.run(main())
```

异步可执行工具需要 `achat`——当 tool callable 为 async 时，同步 `chat` 会抛出异常。

<br />

## Further Exploration

<Tip>
  **Related resources:**

  * [LLM Overview](/features/llm/overview) — preset、模型目录与解析模型。
  * [First LLM](/quickstart/first-llm) — 入口 (Gateway) 配置与 client 导出演练。
  * [LLM providers](/integrations/llm-providers) — 各 provider 配置与路由检查。
</Tip>

<br />
