AI API 参考
约 1212 字大约 4 分钟
2026-03-21
AI 平台 Bot API 完整签名参考 — Chat Completion / Embeddings / Image Generation。
Quick Reference
# 通过 BotAPIClient 访问
api.ai.chat(...)
api.ai.embeddings(...)
api.ai.image_generation(...)
# Sugar 便捷方法
api.ai.chat_text(...) # → str
api.ai.generate_image(...) # → Image 消息段BotAPIClient
└── .ai : IAIAPIClient (AIBotAPI)
├── chat() ← Chat Completion → ModelResponse
├── chat_text() ← Chat Completion → str
├── embeddings() ← 文本向量化
├── image_generation() ← 图像生成 → ImageResponse
└── generate_image() ← 图像生成 → Image 消息段接口定义
from ncatbot.api.ai import IAIAPIClientIAIAPIClient 继承自 IAPIClient
| 属性/方法 | 类型 | 说明 |
|---|---|---|
platform | str | 固定返回 "ai" |
call(action, params) | async | 通用调用入口 |
chat(...) | async | Chat Completion → ModelResponse |
chat_text(...) | async | Chat Completion → str (sugar) |
embeddings(...) | async | 文本向量化 |
image_generation(...) | async | 图像生成 → ImageResponse |
generate_image(...) | async | 图像生成 → Image 消息段 (sugar) |
chat()
async def chat(
content_or_messages: str | list[dict] | MessageArray | MessageSegment,
*,
model: str | None = None,
temperature: float | None = None,
max_tokens: int | None = None,
nickname_map: dict[str, str] | None = None,
**kwargs,
) -> ModelResponse参数
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
content_or_messages | str | list[dict] | MessageArray | MessageSegment | ✅ | str 自动包装;list[dict] 透传;MessageArray / MessageSegment 自动转换 |
model | str | ❌ | 覆盖 completion_model,不存在时回退 |
temperature | float | ❌ | 采样温度(0.0–2.0) |
max_tokens | int | ❌ | 最大生成 token 数,覆盖 config 的 max_tokens |
nickname_map | dict[str, str] | ❌ | At 段昵称映射,如 {"12345": "小明"},缺省显示为 @user_id |
**kwargs | ❌ | 透传给 litellm.acompletion() 的其他参数 |
MessageArray 转换规则
| 消息段 | 转换结果 |
|---|---|
PlainText | {"type": "text", "text": ...} |
Image | {"type": "image_url", "image_url": {"url": ...}},base64:// 自动转 data URI |
At | @{user_id} 或 @{nickname}(依据 nickname_map) |
Reply | [回复消息 id=...] |
Video / File / Record | 跳过 + 警告日志 |
| 其他(Face 等) | 跳过 + 警告日志 |
纯文本 MessageArray 自动优化为普通 str content;含图片时使用多模态 list 格式。
返回值:ModelResponse
class ModelResponse:
id: str # 请求唯一标识,如 "chatcmpl-xxx"
choices: list[Choices] # 生成结果列表
created: int # Unix 时间戳
model: str # 实际使用的模型名
usage: Usage # Token 用量统计
system_fingerprint: str | None
class Choices:
finish_reason: str # "stop" | "length" | "tool_calls"
index: int # 结果索引
message: Message # 生成的消息
class Message:
content: str | None # 生成的文本内容
role: str # "assistant"
reasoning_content: str | None # 推理内容(部分模型支持)
class Usage:
prompt_tokens: int # 输入 token 数
completion_tokens: int # 输出 token 数
total_tokens: int # 总 token 数快速取值
resp = await api.ai.chat("你好")
resp.choices[0].message.content # → "你好!有什么可以帮你的?"
resp.usage.total_tokens # → 30
resp.model # → "gpt-4"embeddings()
async def embeddings(
input_text: str | list[str],
*,
model: str | None = None,
**kwargs,
) -> EmbeddingResponse参数
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
input_text | str | list[str] | ✅ | 待嵌入的文本或文本列表 |
model | str | ❌ | 覆盖 embedding_model,不存在时回退 |
**kwargs | ❌ | 透传给 litellm.aembedding() |
返回值:EmbeddingResponse
class EmbeddingResponse:
model: str # 模型名
data: list[Embedding] # 嵌入结果列表
usage: Usage # Token 用量
class Embedding:
embedding: list[float] # 向量
index: int # 在输入列表中的索引快速取值
resp = await api.ai.embeddings("Hello world")
resp.data[0].embedding # → [0.1, -0.2, 0.3, ...]
len(resp.data[0].embedding) # → 1536 (取决于模型)image_generation()
async def image_generation(
prompt: str,
*,
model: str | None = None,
size: str | None = None,
**kwargs,
) -> ImageResponse参数
| 参数 | 类型 | 必需 | 说明 |
|---|---|---|---|
prompt | str | ✅ | 图像描述文本 |
model | str | ❌ | 覆盖 image_model,不存在时回退 |
size | str | ❌ | 图像尺寸,如 "1024x1024", "512x512" |
**kwargs | ❌ | 透传给 litellm.aimage_generation() |
返回值:ImageResponse
class ImageResponse:
created: int # Unix 时间戳
data: list[ImageObject] # 图像结果列表
class ImageObject:
url: str | None # 图片 URL
b64_json: str | None # Base64 编码的图片数据
revised_prompt: str | None # 修正后的提示词快速取值
resp = await api.ai.image_generation("一只猫", size="1024x1024")
resp.data[0].url # → "https://..."模型回退机制
所有方法共享相同的回退逻辑:
- 优先使用调用时传入的
model=参数 - 若未传,使用 config 中对应功能的默认模型(
completion_model/embedding_model/image_model) - 若指定的模型不存在(API 返回 model not found 类错误),自动回退到 config 中的默认模型
- 若默认模型也不存在,抛出原始异常
# config: completion_model = "gpt-4"
await api.ai.chat("hi", model="gpt-4-turbo")
# 1. 尝试 gpt-4-turbo
# 2. 若 gpt-4-turbo 不存在 → 回退到 gpt-4
# 3. 若 gpt-4 也不存在 → 抛出异常call() 通用入口
async def call(action: str, params: dict | None = None) -> Any通过 action 名路由到对应方法:
await api.ai.call("chat", {"content_or_messages": "你好"})
# 等价于
await api.ai.chat("你好")Sugar 便捷方法
chat_text()
async def chat_text(
content_or_messages: str | list[dict] | MessageArray | MessageSegment,
*,
model: str | None = None,
temperature: float | None = None,
max_tokens: int | None = None,
nickname_map: dict[str, str] | None = None,
**kwargs,
) -> str参数与 chat() 完全相同,直接返回 choices[0].message.content(str)。 content 为 None 时返回空字符串。
# 字符串输入
text = await api.ai.chat_text("你好")
# → "你好!有什么可以帮你的?"
# 直接传入事件消息(图文混合)
text = await api.ai.chat_text(event.message)
# 带昵称映射
text = await api.ai.chat_text(event.message, nickname_map={"12345": "小明"})generate_image()
async def generate_image(
prompt: str,
*,
model: str | None = None,
size: str | None = None,
**kwargs,
) -> Image参数与 image_generation() 完全相同,直接返回 ncatbot.types.Image 消息段对象。 可直接放入 MessageArray 或作为 event.reply() 参数发送。
- 有 URL 时:
Image(file=url, url=url) - 仅有 b64_json 时:
Image(file="base64://...")
image = await api.ai.generate_image("一只猫", size="1024x1024")
await event.reply(image) # 直接发送图片延伸阅读
- AI 适配器使用指南 → guide/adapter/ai/
- Trait 协议参考 → traits/
- litellm 文档 → docs.litellm.ai
版权所有
版权归属:huan-yp
