大模型调用方法
AI 调用方式总览
重点:服务端无状态:大模型服务端不保存会话,所有上下文由客户端本地维护 (messages 数组)。
- 同大类(Chat):同一个接口/函数
client.chat.completions.create(),靠参数区分(stream/tools/response_format/thinking),不换函数
| 类别 | 说明 | 入口 |
|---|---|---|
| Chat 对话类 | 聊天问答、文本生成。包含普通文本、流式、Tool Calling、JSON 结构化输出。**开发最常用 | chat.completions |
| Embedding 向量嵌入类 | 文本转向量,RAG 检索,不产生文本回答 | embeddings |
| Batch 批量异步任务类 | 离线批量提交大量请求 | batches |
| Realtime 实时语音类 | WebSocket 长连接音频实时对话,非 HTTP REST | wss:// |
| Responses(新一代统一对话 API) | 事件化对话接口,独立入口 | responses |
Chat 对话类
全部共用
POST /v1/chat/completions,靠增加/修改参数切换模式。
| 调用模式 | 核心目标 | 必须新增/修改的参数 | 关键说明 |
|---|---|---|---|
| 普通非流式对话 | 一次性返回完整回答 | stream=false(默认) | 最基础,返回完整 message.content |
| 普通流式对话(SSE 打字机) | 增量逐片段返回 | stream=true | 读 delta.content;finish_reason 在最后一条 chunk |
| Tool Calling 工具调用 | AI 判断调用外部函数,唯一区分 Agent 和普通对话的核心能力 | tools=[...],可选 tool_choice | 返回 tool_calls(流式 / 非流式双形态);由你的代码执行函数;finish_reason=tool_calls |
| JSON 结构化输出 | 强制输出合法 JSON | response_format={"type":"json_object"} | 适合数据抽取 |
参数叠加组合
- 流式 + Tool:
stream=true + tools(Agent 最常用) - Tool + JSON:
tools + response_format
标准 OpenAI 参数
协议标准,所有兼容服务商必须支持。
model、messages、temperature、top_p、max_tokens、stream、stop、n、presence_penalty、frequency_penalty、tools、tool_choice、response_format、user
请求参数列表
| 参数名 | 类型 | 必填 | 说明 |
|---|---|---|---|
model | string | 是 | 模型 ID;DeepSeek 写模型名,豆包填 Endpoint ID |
messages | array | 是 | 消息列表,role:system/user/assistant/tool |
temperature | float | 否 | 0~2,随机性 |
top_p | float | 否 | 0~1,核采样 |
max_tokens | integer | 否 | 最大输出 token |
stream | boolean | 否 | true=SSE 流式,false 一次性返回 |
stop | string/array | 否 | 停止序列 |
n | integer | 否 | 生成候选条数,默认 1 |
presence_penalty | float | 否 | -2~2,新话题激励 |
frequency_penalty | float | 否 | -2~2,抑制重复 |
tools | array | 否 | Tool 调用函数 schema 数组 |
tool_choice | string/object | 否 | auto/none/指定工具 |
response_format | object | 否 | {"type":"json_object"} 强制 JSON |
user | string | 否 | 用户标识,日志风控 |
thinking | object | DeepSeek 独有 | {"type":"enabled"} |