模型提供商(云端)
ADK-Rust 通过 adk-model crate 支持多个云端 LLM 提供商。所有提供商都实现了 Llm trait,因此可以在您的 agent 中互换使用。
概览
┌─────────────────────────────────────────────────────────────────────┐
│ Cloud Model Providers │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ • Gemini (Google) ⭐ Default - Multimodal, large context │
│ • OpenAI (GPT-5) 🔥 Popular - Best ecosystem │
│ • Anthropic (Claude) 🧠 Smart - Best reasoning │
│ • DeepSeek 💭 Thinking - Chain-of-thought, cheap │
│ • Groq ⚡ Ultra-Fast - Fastest inference │
│ │
│ For local/offline models, see: │
│ • Ollama → ollama.md │
│ • mistral.rs → mistralrs.md │
│ │
└─────────────────────────────────────────────────────────────────────┘
快速比较
| 提供商 | 最适合 | 速度 | 成本 | 主要特性 |
|---|---|---|---|---|
| Gemini | 通用用途 | ⚡⚡⚡ | 💰 | 多模态、大上下文、思考能力 |
| OpenAI | 可靠性 | ⚡⚡ | 💰💰 | 最佳生态系统 |
| Anthropic | 复杂推理 | ⚡⚡ | 💰💰 | 最安全、最周到 |
| DeepSeek | 思维链 | ⚡⚡ | 💰 | 思考模式,价格低廉 |
| Groq | 速度至关重要 | ⚡⚡⚡⚡ | 💰 | 最快推理 |
第 1 步:安装
将所需的提供商添加到你的 Cargo.toml:
[dependencies]
# Pick one or more providers:
adk-model = { version = "2.1.0", features = ["gemini"] } # Google Gemini (default)
adk-model = { version = "2.1.0", features = ["openai"] } # OpenAI GPT-5
adk-model = { version = "2.1.0", features = ["anthropic"] } # Anthropic Claude
adk-model = { version = "2.1.0", features = ["deepseek"] } # DeepSeek
adk-model = { version = "2.1.0", features = ["groq"] } # Groq (ultra-fast)
# Or all cloud providers at once:
adk-model = { version = "2.1.0", features = ["all-providers"] }
第 2 步:设置你的 API 密钥
export GOOGLE_API_KEY="your-key" # Gemini
export OPENAI_API_KEY="your-key" # OpenAI
export ANTHROPIC_API_KEY="your-key" # Anthropic
export DEEPSEEK_API_KEY="your-key" # DeepSeek
export GROQ_API_KEY="your-key" # Groq
架构规范化
每个提供商都会在请求时自动规范化 MCP 工具架构。你无需执行任何操作——它会透明地完成。但以下是其底层的工作方式:
| 提供商 | 模式适配器 | 行为 |
|---|---|---|
| Gemini | GeminiSchemaAdapter | 激进:解析 $ref、合并组合器、移除不受支持的关键字 |
| OpenAI(严格) | OpenAiStrictSchemaAdapter | 保留结构,添加 additionalProperties: false |
| OpenAI | OpenAiSchemaAdapter | 最小安全修复 |
| Anthropic | AnthropicSchemaAdapter | 近乎直接传递 |
| DeepSeek | GenericSchemaAdapter | 保守的安全转换 |
| Ollama | GenericSchemaAdapter | 保守的安全转换 |
通过 Llm trait 以编程方式访问适配器:
use adk_core::{Llm, SchemaAdapter};
let adapter = model.schema_adapter();
let normalized = adapter.normalize_schema(raw_schema);
完整文档请参阅模式规范化。
Gemini(Google)⭐ 默认
适用场景:通用任务、多模态任务、大型文档
主要亮点:
- 🖼️ 原生多模态(图像、视频、音频、PDF)
- 📚 上下文窗口最多支持 200 万个 token
- 🧠 思考模式:基于级别(Gemini 3)和基于预算(Gemini 2.5),支持思考签名
- 💰 具有竞争力的定价
- ⚡ 快速推理
完整工作示例
use adk_rust::prelude::*;
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
let api_key = std::env::var("GOOGLE_API_KEY")?;
let model = GeminiModel::new(&api_key, "gemini-3.7-flash")?;
let agent = LlmAgentBuilder::new("gemini_assistant")
.description("Gemini-powered assistant")
.instruction("You are a helpful assistant powered by Google Gemini. Be concise.")
.model(Arc::new(model))
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
可用模型
| 模型 | 描述 | 上下文 |
|---|---|---|
gemini-3.7-flash | 默认的均衡代理模型 | 100 万个令牌 |
gemini-3.6-flash | 上一代均衡生成模型 | 100 万个令牌 |
gemini-3.5-flash-lite | 经济高效的路由和大容量任务 | 1M tokens |
gemini-3.1-pro-preview | 高级预览推理 | 2M tokens |
思考模式
Gemini 3 模型支持基于级别的思考,而 Gemini 2.5 使用基于预算的思考。在使用带函数调用的思考模式时,Gemini 2.5+ 和 3.x 模型会返回 thoughtSignature 值,必须在后续轮次中原样回传,以保留推理上下文。ADK-Rust 会自动处理此过程——存在签名时进行序列化,在 None 时省略。
use adk_gemini::{Gemini, ThinkingLevel};
// Gemini 3: level-based thinking
let response = client.generate_content()
.with_user_message("Solve this step by step")
.with_thinking_level(ThinkingLevel::High)
.with_thoughts_included(true)
.execute().await?;
// Gemini 2.5: budget-based thinking
let response = client.generate_content()
.with_user_message("Solve this step by step")
.with_thinking_budget(2048)
.with_thoughts_included(true)
.execute().await?;
示例输出
👤 User: What's in this image? [uploads photo of a cat]
🤖 Gemini: I can see a fluffy orange tabby cat sitting on a windowsill.
The cat appears to be looking outside, with sunlight illuminating its fur.
It has green eyes and distinctive striped markings typical of tabby cats.
OpenAI(GPT-5)🔥 热门
最适合:生产应用、可靠的性能、广泛的功能
主要亮点:
- 🏆 行业标准
- 🔧 出色的工具/函数调用能力
- 📖 最完善的文档和生态系统
- 🎯 一致且可预测的输出
- 📋 通过 JSON 架构强制执行的结构化输出
- 🧠 控制 GPT-5.6 推理模型的推理力度
- 🆕 Responses API —— 面向
/v1/responses的专用客户端,提供推理摘要、内置工具和服务端状态
完整工作示例
use adk_rust::prelude::*;
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
let api_key = std::env::var("OPENAI_API_KEY")?;
let model = OpenAIClient::new(OpenAIConfig::new(&api_key, "gpt-5.6-terra"))?;
let agent = LlmAgentBuilder::new("openai_assistant")
.description("OpenAI-powered assistant")
.instruction("You are a helpful assistant powered by OpenAI GPT-5. Be concise.")
.model(Arc::new(model))
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
结构化输出(JSON 架构)
OpenAI 通过 output_schema 支持有保证的 JSON 输出。ADK-Rust 会自动将其连接到 OpenAI 的 response_format API:
use adk_rust::prelude::*;
use serde_json::json;
use std::sync::Arc;
let model = OpenAIClient::new(OpenAIConfig::new(&api_key, "gpt-5.6-terra"))?;
let agent = LlmAgentBuilder::new("data_extractor")
.model(Arc::new(model))
.instruction("Extract person information from the text.")
.output_schema(json!({
"type": "object",
"properties": {
"name": { "type": "string" },
"age": { "type": "number" },
"email": { "type": "string" }
},
"required": ["name", "age"]
}))
.build()?;
// Response is guaranteed to be valid JSON matching the schema
对于包含嵌套对象的严格模式,请在每个层级包含 additionalProperties: false:
.output_schema(json!({
"type": "object",
"properties": {
"title": { "type": "string" },
"metadata": {
"type": "object",
"properties": {
"author": { "type": "string" },
"tags": { "type": "array", "items": { "type": "string" } }
},
"required": ["author"],
"additionalProperties": false // Required for nested objects
}
},
"required": ["title", "metadata"],
"additionalProperties": false // Auto-injected at root level
}))
推理力度
对于 OpenAI 推理模型,可以控制模型采用的推理力度:
use adk_model::openai::{OpenAIClient, OpenAIConfig, OpenAIReasoningEffort};
let config = OpenAIConfig::new(&api_key, "gpt-5.6-terra");
let model = OpenAIClient::new_with_reasoning_effort(
config,
OpenAIReasoningEffort::XHigh,
)?;
完整词汇表为 None、Minimal、Low、Medium、High、XHigh
和 Max;可用性取决于模型和 API。GPT-5.6 聊天补全
最多支持 XHigh;对于 Max,请使用 OpenAIResponsesClient。原有的
三值 ReasoningEffort API 仍可用于向后兼容。
OpenAI 兼容的本地 APIs
使用 OpenAIConfig::compatible() 连接到本地服务器(Ollama、vLLM、LM Studio):
// Ollama exposes OpenAI-compatible API at /v1
let config = OpenAIConfig::compatible(
"not-needed", // API key (ignored by Ollama)
"http://localhost:11434/v1", // Base URL
"llama3.2" // Model name
);
let model = OpenAIClient::new(config)?;
注意:结构化输出(
output_schema)需要后端支持;原生 OpenAI 完全支持该功能,本地服务器的支持可能有限。
通过 OpenAI 兼容端点使用 Gemini
Gemini 模型可通过 OpenAI 聊天补全线路格式访问,地址为
https://generativelanguage.googleapis.com/v1beta/openai。使用
OpenAICompatibleConfig::gemini(...) 预设(位于 openai 功能下),并配合
GEMINI_API_KEY,即可通过你为其他所有提供商使用的同一
OpenAI 兼容客户端运行 Gemini:
use adk_model::openai_compatible::{OpenAICompatible, OpenAICompatibleConfig};
let api_key = std::env::var("GEMINI_API_KEY")?;
let model = OpenAICompatible::new(
OpenAICompatibleConfig::gemini(api_key, "gemini-3.5-flash"),
)?;
此路径支持聊天、流式传输、函数调用、结构化输出和
推理工作量(OpenAI 的 reasoning_effort 会映射到 Gemini 的思考
级别/预算)。Gemini 特有的选项——例如带有
include_thoughts 的 thinking_config,或 cached_content——会通过请求的
extensions["openai"]["extra_body"]["google"] 映射传递,客户端会将其
逐字合并到请求正文中。
何时使用此方式而不是
GeminiModel:对于原生 Gemini 功能 (服务器端工具、Interactions API、原生ThinkingConfig、 以多模态为先的易用性),请优先使用GeminiModel。如果你希望在不同提供商之间使用 统一的客户端,请使用 OpenAI 兼容预设。
示例(需要 GEMINI_API_KEY 或 GOOGLE_API_KEY):
# Direct client: chat, reasoning effort, extra_body thinking, streaming,
# function calling, structured output.
cargo run -p adk-model --features openai --example gemini_openai_compat
# The same compat client driving a normal LlmAgent in a Runner.
# (Lives in adk-agent: it exercises the agent layer, which sits above adk-model.)
cargo run -p adk-agent --example gemini_openai_compat_agent
旧版推理工作量 API
原有的三级 ReasoningEffort API 仍可用于兼容性:
use adk_model::openai::{OpenAIClient, OpenAIConfig, ReasoningEffort};
let config = OpenAIConfig::new(&api_key, "gpt-5")
.with_reasoning_effort(ReasoningEffort::High);
let model = OpenAIClient::new(config)?;
可用级别:Low(最快)、Medium(均衡)、High(最全面)。
可用模型
| 模型 | 描述 | 上下文 |
|---|---|---|
gpt-5.6-terra | 面向生产环境 agent 的均衡默认选项 | 256K 令牌 |
gpt-5.6-sol | 旗舰级推理与编码 | 256K 令牌 |
gpt-5.6-luna | 高性价比、高容量工作负载 | 128K tokens |
gpt-5.6 | 旗舰别名 | 256K tokens |
示例输出
👤 User: Write a haiku about Rust programming
🤖 GPT-5: Memory so safe,
Ownership guards every byte—
Compiler, my friend.
Anthropic (Claude) 🧠 智能
最适合:复杂推理、对安全至关重要的应用、长文档
主要亮点:
- 🧠 卓越的推理能力
- 🛡️ 最注重安全
- 📚 200K token 上下文
- ✍️ 出色的写作质量
完整工作示例
use adk_rust::prelude::*;
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
let api_key = std::env::var("ANTHROPIC_API_KEY")?;
let model = AnthropicClient::new(AnthropicConfig::new(&api_key, "claude-sonnet-5"))?;
let agent = LlmAgentBuilder::new("anthropic_assistant")
.description("Anthropic-powered assistant")
.instruction("You are a helpful assistant powered by Anthropic Claude. Be concise and thoughtful.")
.model(Arc::new(model))
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
可用模型
| 模型 | 描述 | 上下文 |
|---|---|---|
claude-sonnet-5 | 智能与成本的平衡(默认) | 100 万个 token |
claude-opus-5 | 旗舰级能力 | 100 万个 token |
claude-fable-5 | 高品质创意和长篇工作 | 1M tokens |
claude-haiku-4-5 | 经济高效的上一代模型 | 200K tokens |
示例输出
👤 User: Explain quantum entanglement to a 10-year-old
🤖 Claude: Imagine you have two magic coins. When you flip them, they always
land the same way - both heads or both tails - even if one coin is on Earth
and the other is on the Moon! Scientists call this "entanglement." The coins
are connected in a special way that we can't see, like invisible best friends
who always make the same choice at the exact same time.
DeepSeek 💭 思考
适用于:复杂问题解决、数学、编码、推理任务
主要亮点:
- 💭 思考模式 - 展示思维链推理
- 💰 极具成本效益(比 GPT-4 便宜 10 倍)
- 🔄 针对重复前缀的上下文缓存
- 🧮 擅长数学和编码
完整可运行示例
use adk_rust::prelude::*;
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
let api_key = std::env::var("DEEPSEEK_API_KEY")?;
// Standard chat model
let model = DeepSeekClient::chat(&api_key)?;
// OR: Reasoning model with thinking mode
// let model = DeepSeekClient::reasoner(&api_key)?;
let agent = LlmAgentBuilder::new("deepseek_assistant")
.description("DeepSeek-powered assistant")
.instruction("You are a helpful assistant powered by DeepSeek. Be concise.")
.model(Arc::new(model))
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
可用模型
| 模型 | 描述 | 特殊功能 |
|---|---|---|
deepseek-v4-flash | 当前默认 | 快速通用代理 |
deepseek-v4-pro | 高级推理 | 复杂的智能体工作 |
示例输出(带思考模式的推理器)
👤 User: What's 17 × 23?
🤖 DeepSeek: <thinking>
Let me break this down:
17 × 23 = 17 × (20 + 3)
= 17 × 20 + 17 × 3
= 340 + 51
= 391
</thinking>
The answer is 391.
Groq ⚡ 超高速
最适合:实时应用、聊天机器人、对速度要求高的任务
主要亮点:
- ⚡ 最快的推理速度 - 比竞争对手快 10 倍
- 🔧 LPU(语言处理单元)技术
- 💰 具有竞争力的定价
- 🦙 可运行 LLaMA、Mixtral、Gemma 模型
完整可运行示例
use adk_rust::prelude::*;
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
let api_key = std::env::var("GROQ_API_KEY")?;
let model = GroqClient::new(GroqConfig::gpt_oss_120b(&api_key))?;
let agent = LlmAgentBuilder::new("groq_assistant")
.description("Groq-powered assistant")
.instruction("You are a helpful assistant powered by Groq. Be concise and fast.")
.model(Arc::new(model))
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
可用模型
| 模型 | 方法 | 描述 |
|---|---|---|
openai/gpt-oss-120b | GroqClient::new(GroqConfig::gpt_oss_120b(key)) | 当前生产环境默认值 |
openai/gpt-oss-20b | GroqClient::new(GroqConfig::new(key, "openai/gpt-oss-20b")) | 成本更低的 GPT-OSS 模型 |
| 任意模型 | GroqClient::new(GroqConfig::new(key, "model")) | 自定义模型 |
示例输出
👤 User: Quick! Name 5 programming languages
🤖 Groq (in 0.2 seconds):
1. Rust
2. Python
3. JavaScript
4. Go
5. TypeScript
切换提供商
所有提供商都实现了相同的 Llm trait,因此切换非常简单:
use adk_agent::LlmAgentBuilder;
use std::sync::Arc;
// Just change the model - everything else stays the same!
let model: Arc<dyn adk_core::Llm> = Arc::new(
// Pick one:
// GeminiModel::new(&api_key, "gemini-3.7-flash")?
// OpenAIClient::new(OpenAIConfig::new(&api_key, "gpt-5.6-terra"))?
// AnthropicClient::new(AnthropicConfig::new(&api_key, "claude-sonnet-5"))?
// DeepSeekClient::chat(&api_key)?
// GroqClient::new(GroqConfig::gpt_oss_120b(&api_key))?
);
let agent = LlmAgentBuilder::new("assistant")
.instruction("You are a helpful assistant.")
.model(model)
.build()?;
示例
使用 cargo-adk 生成经过验证、依赖版本为 0.8 的特定提供商项目:
cargo adk new gemini_agent --provider gemini
cargo adk new openai_agent --template openai
cargo adk new anthropic_agent --provider anthropic
生成的项目由 scripts/check-cargo-adk-templates.sh 在 CI 中编译。完整的示例库维护在 adk-playground 仓库中。
相关内容
- Ollama(本地) - 使用 Ollama 在本地运行模型
- 本地模型(mistral.rs) - 原生 Rust 推理
- LlmAgent - 在 agent 中使用模型
- 函数工具 - 向 agent 添加工具
上一页:← 实时 agent | 下一页:Ollama(本地) →
提供商无法承载的内容会怎样
Content 能够表达的内容多于任何单一提供商传输所能接受的内容,因此每个适配器都必须决定如何处理剩余部分。这些决策现在会被记录下来,而不是被不透明地应用。每个部分都会被分类:
| 处理方式 | 含义 |
|---|---|
Converted | 以等效的原生形式传递给提供商 |
Downgraded | 以有损形式传递——文件引用呈现为模型可以读取但无法获取的描述性文本 |
Omitted | 完全未携带 |
降级和省略会在记录时发出 tracing 警告,其中会说明部件种类、MIME 类型和原因,因此两者都不会悄无声息地发生。
要在分派请求之前查看结果:
use adk_core::{Content, Part};
use adk_model::bedrock::convert::report_for_contents;
let content = Content {
role: "user".to_string(),
parts: vec![Part::inline_data("audio/wav", vec![0u8; 16])],
};
let report = report_for_contents(std::slice::from_ref(&content));
for omission in report.omitted_parts() {
println!("{} was dropped: {}", omission.kind, omission.detail);
}
若要拒绝一个会以不完整形式到达模型的请求,而不是接收关于模型从未看到的材料的回答:
use adk_core::{Content, Part};
use adk_model::bedrock::convert::report_for_contents;
let content = Content {
role: "user".to_string(),
parts: vec![Part::inline_data("video/mp4", vec![0u8; 16])],
};
if let Some(error) = report_for_contents(std::slice::from_ref(&content)).into_error() {
return Err(error);
}
into_error 仅涵盖省略。降级仍会到达模型,拒绝降级将拒绝文档所述的文本回退。
**注意:**账本在设计上是完整的。任何离开适配器却没有记录结果的部件(包括未来更改添加的部件)都会被记录为省略,并明确标注“没有记录原因”,而
adk-model/tests/part_conversion_matrix_tests.rs会因此失败。
Bedrock Converse 覆盖范围
| 部分 | 处理方式 |
|---|---|
| 文本、FunctionCall、FunctionResponse、思考 | Converted |
带有 JPEG、PNG、GIF、WebP 的 InlineData | 作为图像块的 Converted |
InlineData 与受支持的文档类型(PDF 及类似类型) | Converted 作为文档块 |
InlineData 与音频、视频或任意二进制数据 | Omitted |
FileData 用于图像或受支持的文档 | Downgraded 转换为文本 — Converse 接受 S3 URIs,而不是任意的 URLs |
FileData 用于任何其他类型 | Omitted |
ServerToolCall, ServerToolResponse | Omitted — Gemini 专属 |
EmbeddedResource 文本,或受支持类型的二进制数据 | Converted |
EmbeddedResource 不受支持类型的二进制数据 | Omitted |