RIG中文文档非官方中文译本

编写自己的服务商

实战指南官网快照 · 2026-11-10阅读英文原文 ↗
Rig 0.46.0 实际适配版

本页 11 个 Rust 代码块均有编译检查记录;片段已补齐所需上下文。 5 个代码块已更新。

查看逐块编译结果、运行前提与示例项目 →

Rig 内置许多服务商,你也可以在 Rig 仓库之外添加自己的实现。本指南按工作量由小到大介绍三种方式:

  1. 服务商使用 OpenAI Chat Completions 格式:声明一个 dialect(协议变体)。
  2. 服务商使用 Anthropic Messages 格式:声明一个 Messages dialect。
  3. 服务商有自己的 API:为它编写 wire(协议适配器)。

Rig 模型如何构成#

Rig 中的每个模型都是 rig::driver::Model<W, T>,组合了两部分:

  • Wire(W: rig::wire::Wire):描述一个端点的普通数据,负责把请求编码成 HTTP 请求,并提供响应解码器。它不接触网络。
  • Transport(T: rig::driver::Transport<W>):负责请求如何传输。任何实现 HttpClientExt 的 HTTP 客户端都是 transport,因此大多数 wire 无需指定它。默认使用共享的 reqwest 客户端。

Driver 位于两者之间,负责其余事项:发送请求、将响应拆成帧(SSE、NDJSON 或完整响应体)、状态检查、遥测,以及把解码事件归并成 CompletionResponse。单次响应(model.call)和流式响应(model.stream)经过同一个解码器,因此服务商只需实现一次,就能支持两种方式。同一模型也能用于 Agent(AgentBuilder::new(model))、包装成 DynModel,并兼容 Agent 运行时中的所有 hook 和工具。

OpenAI 这样的服务商客户端只是便利封装:配置加 transport,以及 completion(model) 等返回 Model 的方法。

兼容 OpenAI 的服务商#

如果服务商接受 OpenAI Chat Completions 请求,无需自己写 wire。声明包含服务商名称、默认 base URL 和 API Key 环境变量名的 Dialect,再通过 Quirks 调整不同之处:

rust
use rig::providers::openai::OpenAIConfig;
use rig::providers::openai::wire::{Dialect, Quirks};


/// Acme's gateway speaks Chat Completions but rejects `stream_options` and
/// has no structured output.
const ACME: Dialect = Dialect::gateway("acme", "https://api.acme.test/v1", "ACME_API_KEY")
    .with_quirks(Quirks::openai().without_stream_usage().without_response_format());


let acme = OpenAIConfig::from_env_with(&ACME)?.client();
let model = acme.completion("acme-large");


let agent = AgentBuilder::new(model).preamble("You are terse.").build();
let answer = agent.prompt("Say hello.").await?.output();

完整代码与上下文 ↗编译通过 · Rig 0.46.0

Quirks 还有更多开关,例如 done_without_finish_reason() 用于以 [DONE] 结束、但不带结束原因的流。只接一个特定端点时,也可以使用 OpenAIConfig::new(key).with_base_url(url)。

兼容 Anthropic Messages 的服务商#

接受 Anthropic Messages 格式的服务商,可通过 anthropic::compatible 采用相同方式:

rust
use rig::providers::anthropic::{self, AnthropicConfig, Dialect};


const ACME_MESSAGES: Dialect = anthropic::compatible(
    "acme",
    "https://api.acme.test/anthropic",
    "ACME_API_KEY",
    Some("ACME_BASE_URL"),
);


let model = AnthropicConfig::from_env_with(&ACME_MESSAGES)?
    .client()
    .completion("acme-large");
let response = model.call("Say hello.").await?;
println!("{}", response.text());

完整代码与上下文 ↗编译通过 · Rig 0.46.0

使用独立 API 的服务商#

本指南后面的部分,为虚构 API Acme 构建补全服务商。它接收以下请求:

plaintext
POST {base_url}/v1/generate
{"model": "acme-large", "messages": [{"role": "user", "content": "Hi"}], "stream": false}

单次响应是一个 JSON 文档。流式响应采用相同结构的换行分隔 JSON(NDJSON),每行携带一段文本,最后一行标记 done:

plaintext
{"id": "gen_1", "model": "acme-large", "text": "Hello!", "done": true,
 "usage": {"input_tokens": 5, "output_tokens": 2}}

需要编写五部分:

部分 Trait 职责
配置与 wire 结构体 — 普通数据:base URL、Key、模型
历史消息适配(ReplayTarget) ReplayTarget 模型能读取哪些内容,以及选项如何映射到请求
解码器 Decoder 将每个响应帧转换为文本、工具调用和结束信息
重组器 Reassemble 根据流重建服务商原始响应文档,供 raw 使用
Wire Wire 连接以上各部分,并编码 HTTP 请求

配置与 wire#

Wire 是普通数据,应实现 Clone,通常还实现 Debug、PartialEq、Serialize 和 Deserialize,以便像其他配置一样保存和加载。凭证应保存在 rig::wire::Secret 中;它在打印和序列化时显示为 [redacted],防止 Key 进入日志。

rust
use rig::wire::Secret;


/// Where Acme lives and the key it takes.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AcmeConfig {
    pub api_key: Secret,
    pub base_url: String,
}


impl AcmeConfig {
    pub fn new(api_key: impl Into<Secret>) -> Self {
        Self {
            api_key: api_key.into(),
            base_url: "https://api.acme.test".to_owned(),
        }
    }


    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = base_url.into();
        self
    }
}


/// Acme's generate endpoint, for one model.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AcmeChat {
    pub config: AcmeConfig,
    pub model: String,
}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

历史消息适配(ReplayTarget)#

每个补全协议适配器(wire)都实现 ReplayTarget。这里的 replay 指让目标模型继续读取已有对话,和 cassette 的离线重放不是同一功能。编码器运行前,Rig 用它把对话整理成适合该模型的形式。模型不能读取的内容会降级:图片变成占位符;tools 关闭时,工具调用与结果转换成文本。这样,其他任何服务商产生的历史都能发送给你的服务商,而编码器只会收到你声明支持的内容。

map_options 说明请求中的每个通用选项(top_p、seed、stop、推理等)如何发送。解构 fields 时不要使用 ..,这样 Rig 新增选项后,你必须处理它才能通过编译。Mapping::Send 将 JSON 合并到请求体;Mapping::unsupported 在发送前拒绝该选项。

rust
use rig::completion::options::{Mapping, OptionFields, OptionMap};
use rig::completion::{Accepts, CompletionRequest, Media, ReplayTarget};
use rig::message::Api;


impl ReplayTarget for AcmeChat {
    fn api(&self) -> Api {
        Api::from_static("acme.generate")
    }


    fn provider(&self) -> &str {
        "acme"
    }


    fn model(&self) -> &str {
        &self.model
    }


    /// Text only: no images, and no tool calling.
    fn accepts(&self, _model: &str) -> Accepts {
        Accepts {
            tools: false,
            ..Accepts::TEXT
        }
    }


    /// No media at all: text documents are sent as their text.
    fn encodes(&self, _model: &str, _media: Media<'_>) -> bool {
        false
    }


    fn map_options(&self, _request: &CompletionRequest, fields: OptionFields<'_>) -> OptionMap {
        let OptionFields {
            reasoning,
            cache,
            service_tier,
            verbosity,
            parallel_tool_calls,
            top_p,
            seed,
            stop,
            cache_key,
        } = fields;
        const NO_FIELD: &str = "Acme has no such field";
        OptionMap {
            reasoning: Mapping::of(reasoning, |_| Mapping::unsupported(NO_FIELD)),
            cache: Mapping::of(cache, |_| Mapping::unsupported(NO_FIELD)),
            service_tier: Mapping::of(service_tier, |_| Mapping::unsupported(NO_FIELD)),
            verbosity: Mapping::of(verbosity, |_| Mapping::unsupported(NO_FIELD)),
            parallel_tool_calls: Mapping::of(parallel_tool_calls, |_| {
                Mapping::unsupported(NO_FIELD)
            }),
            top_p: Mapping::of(top_p, |top_p| Mapping::Send(json!({ "top_p": top_p }))),
            seed: Mapping::of(seed, |seed| Mapping::Send(json!({ "seed": seed }))),
            stop: Mapping::of_stop(stop, |stop| Mapping::Send(json!({ "stop": stop }))),
            cache_key: Mapping::unrouted(cache_key),
        }
    }
}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

0.46.0 的 OptionFields / OptionMap 包含 cache_key。示例使用 Mapping::unrouted(cache_key) 明确处理未映射选项。

ReplayTarget 还提供一些带默认实现的方法,供规则更严格的服务商使用,例如 starts_with_user、alternates_roles 和 normalize_tool_call_id。按你的 API 要求覆盖相应方法即可。

解码器#

解码器读取一次响应。classify 把帧解析为你的类型化事件。对于 JSON 帧,使用 rig::providers::internal::wire 中的共享分类器,以便将无效 JSON 报告为损坏响应,而不是静默跳过。decode 通过 Out 将事件写入响应:

  • out.run(Block::Text, text) 追加文本。连续的同类内容会合并为一个块。
  • out.end(Finish { .. }) 用用量、结束原因、响应 ID 和模型信息结束响应。若所有帧耗尽仍未结束,会报告响应被截断。
rust
use rig::completion::{FinishReason, Usage};
use rig::operation::{Block, Completion, Finish};
use rig::providers::internal::wire::classify_untyped_line;
use rig::wire::{Decoder, Flow, Out, WireEvent, WireFrame};
use rig::ProviderError;


/// One Acme reply document, or one line of a streamed reply.
#[derive(Debug, Serialize, Deserialize)]
pub struct Chunk {
    #[serde(default)]
    pub id: Option<String>,
    #[serde(default)]
    pub model: Option<String>,
    #[serde(default)]
    pub text: String,
    #[serde(default)]
    pub done: bool,
    #[serde(default)]
    pub usage: Option<AcmeUsage>,
    // Preserve vendor-specific fields for CompletionResponse::raw.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}


#[derive(Debug, Serialize, Deserialize)]
pub struct AcmeUsage {
    pub input_tokens: u64,
    pub output_tokens: u64,
}


#[derive(Debug, Default)]
pub struct AcmeDecoder;


impl<'id> Decoder<'id, Completion> for AcmeDecoder {
    type Event = Chunk;


    fn classify(&self, frame: WireFrame) -> WireEvent<Chunk> {
        classify_untyped_line(frame.as_str().as_bytes())
    }


    fn decode(
        &mut self,
        chunk: Chunk,
        mut out: Out<'id, Completion>,
    ) -> Result<Flow, ProviderError> {
        if !chunk.text.is_empty() {
            out.run(Block::Text, &chunk.text)?;
        }
        if !chunk.done {
            return Ok(Flow::More);
        }
        out.end_run()?;
        let usage = chunk.usage.map_or_else(Usage::new, |usage| {
            Usage::new()
                .input_tokens(usage.input_tokens)
                .output_tokens(usage.output_tokens)
        });
        Ok(out.end(Finish {
            usage,
            reason: Some(FinishReason::Stop),
            response_id: chunk.id,
            model: chunk.model,
            ..Finish::default()
        }))
    }
}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

解码器无需知道响应是否来自流。单次响应时,完整响应体就是一帧;流式响应时,每行 NDJSON 是一帧。

重组器#

CompletionResponse::raw 保存服务商原始响应文档。对于单次响应,Rig 直接使用响应体。对于流式响应,没有完整响应体,因此 wire 的重组器会观察 classify 产生的每个类型化事件(此处是 Chunk)并重建文档。在本例中,就是拼接文本,并保留最后一行的其他字段:

rust
use rig::operation::Completion;
use rig::wire::document::{Reassemble, Serves};
use serde_json::{Map, Value};


#[derive(Default)]
pub struct AcmeDocument {
    text: String,
    last: Map<String, Value>,
}


impl Reassemble<Chunk> for AcmeDocument {
    fn absorb(&mut self, event: &Chunk) {
        let Ok(Value::Object(chunk)) = serde_json::to_value(event) else {
            return;
        };
        if let Some(text) = chunk.get("text").and_then(Value::as_str) {
            self.text.push_str(text);
        }
        self.last = chunk;
    }


    fn finish(self) -> Value {
        if self.last.is_empty() {
            return Value::Null;
        }
        let mut document = self.last;
        document.insert("text".to_owned(), Value::String(self.text));
        Value::Object(document)
    }
}


impl Serves<Completion> for AcmeDocument {}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

Wire#

Wire 实现指定操作(Completion)、载荷(Encoded,包含 HTTP 请求及拆分响应的方式)、帧类型、解码器和重组器。describe 为遥测提供服务商名与模型名,并指向 replay target。

encode 不得执行任何 I/O。在闭包中构建你自己的请求体,再传给 options::request_params。它会按照所有内置服务商相同的顺序,依次加入映射后的选项、类型化服务商选项,以及调用方的 additional_params。

rust
use rig::completion::options::{request_params, RawAt};
use rig::completion::CompletionRequest;
use rig::error::EncodeError;
use rig::http_client::{HeaderValue, Request};
use rig::message::{AssistantContent, Message, UserContent};
use rig::operation::Completion;
use rig::wire::{Descriptor, Encoded, Framing, Mode, Wire, WireFrame};
use serde_json::{Map, Value};


impl AcmeChat {
    /// Acme's own fields: model, messages, sampling and the stream flag.
    fn base(&self, request: &CompletionRequest, mode: Mode) -> Result<Map<String, Value>, EncodeError> {
        if !request.tools.is_empty() {
            return Err(EncodeError::request("Acme does not support tools"));
        }
        let mut messages = Vec::new();
        for message in &request.chat_history {
            let (role, content) = match message.as_ref() {
                Message::System { content } => ("system", content.clone()),
                Message::User { content } => ("user", user_text(content)?),
                Message::Assistant(turn) => ("assistant", assistant_text(&turn.content)),
            };
            messages.push(json!({ "role": role, "content": content }));
        }
        let mut body = Map::new();
        // `prepare` has already resolved the model: the request's override, or ours.
        let model = request.model.clone().unwrap_or_else(|| self.model.clone());
        body.insert("model".into(), json!(model));
        body.insert("messages".into(), json!(messages));
        body.insert("stream".into(), json!(mode == Mode::Streaming));
        if let Some(temperature) = request.temperature {
            body.insert("temperature".into(), json!(temperature));
        }
        if let Some(max_tokens) = request.max_tokens {
            body.insert("max_tokens".into(), json!(max_tokens));
        }
        Ok(body)
    }
}


/// The text of a user message. `accepts` and `encodes` mean the adapter
/// has already replaced anything else.
fn user_text(content: &[UserContent]) -> Result<String, EncodeError> {
    let mut texts = Vec::new();
    for part in content {
        match part {
            UserContent::Text(text) => texts.push(text.text()),
            _ => return Err(EncodeError::request("Acme takes text only")),
        }
    }
    Ok(texts.join("\n"))
}


fn assistant_text(content: &[AssistantContent]) -> String {
    content
        .iter()
        .filter_map(|block| match block {
            AssistantContent::Text(text) => Some(text.text()),
            _ => None,
        })
        .collect()
}


impl Wire for AcmeChat {
    type Op = Completion;
    type Payload = Encoded;
    type Frame = WireFrame;
    type Event = Chunk;
    type Decoder<'id> = AcmeDecoder;
    type Reassembler = AcmeDocument;


    fn describe(&self) -> Descriptor<'_> {
        Descriptor::new("acme").model(self.model.as_str()).replay(self)
    }


    fn encode(&self, request: CompletionRequest, mode: Mode) -> Result<Encoded, EncodeError> {
        let body = request_params(self, &request, |_| self.base(&request, mode), RawAt::Top, &[])?;
        let mut authorization =
            HeaderValue::from_str(&format!("Bearer {}", self.config.api_key.expose()))
                .map_err(EncodeError::request)?;
        authorization.set_sensitive(true);
        let http = Request::post(format!("{}/v1/generate", self.config.base_url))
            .header("content-type", "application/json")
            .header("authorization", authorization)
            .body(body.into_body())?;
        let framing = match mode {
            Mode::Unary => Framing::Whole,
            Mode::Streaming => Framing::Ndjson,
        };
        Ok(Encoded::new(http, framing).with_route(Some("/v1/generate")))
    }


    fn decoder<'id>(&self) -> Self::Decoder<'id> {
        AcmeDecoder
    }
}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

Wire::Event 与解码器事件类型一致;这里为 Chunk。chat_history 内的消息由 Arc 持有,匹配时使用 message.as_ref()。

服务器发送事件流使用 Framing::Sse。如果服务商在响应头返回请求 ID,用 Encoded::with_request_id_header 指定 header 名称,Rig 就会将其附到响应和错误上。

客户端#

客户端是普通 Rust 代码。沿用内置客户端结构:一个配置、一个 transport,以及每类模型对应一个方法。DynHttpClient 持有任意 HttpClientExt;rig::rig_reqwest::shared() 是进程级共享 reqwest 客户端,也是所有内置服务商的默认选择:

rust
use rig::driver::Model;
use rig::http_client::{DynHttpClient, HttpClientExt};
use rig::wire::Secret;


#[derive(Clone)]
pub struct Acme {
    config: AcmeConfig,
    http: DynHttpClient,
}


impl Acme {
    pub fn new(api_key: impl Into<Secret>) -> Self {
        Self {
            config: AcmeConfig::new(api_key),
            http: rig::rig_reqwest::shared(),
        }
    }


    pub fn from_env() -> Result<Self, std::env::VarError> {
        Ok(Self::new(std::env::var("ACME_API_KEY")?))
    }


    /// Send through another HTTP client: a configured reqwest client,
    /// middleware, or your own `HttpClientExt`.
    pub fn with_http(mut self, http: impl HttpClientExt + 'static) -> Self {
        self.http = DynHttpClient::new(http);
        self
    }


    pub fn completion(&self, model: impl Into<String>) -> Model<AcmeChat> {
        let wire = AcmeChat {
            config: self.config.clone(),
            model: model.into(),
        };
        Model::new(wire, self.http.clone())
    }
}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

使用它#

这个模型可以用于内置模型能用的任何地方:直接调用、流式输出和 Agent。

rust
use futures::StreamExt;
use rig::streaming::{Item, StreamEvent};


let model = Acme::from_env()?.completion("acme-large");


// One request, no agent loop.
let response = model.call("Say hello.").await?;
println!("{} ({:?} output tokens)", response.text(), response.usage.output_tokens);


// The same request, streamed through the same decoder.
let mut stream = model.stream("Count to five.")?;
while let Some(item) = stream.next().await {
    if let Item::Event(StreamEvent::Text { text, .. }) = item? {
        print!("{text}");
    }
}


// As an agent model.
let agent = AgentBuilder::new(model).preamble("You are terse.").build();
println!("{}", agent.prompt("What is Rust?").await?.output());

完整代码与上下文 ↗编译通过 · Rig 0.46.0

无网络测试#

Transport 独立于 wire,因此可以将 wire 放在重放已记录响应体的 transport 上测试。Framing::split 按与 HTTP transport 相同的方式把响应体拆成帧。该测试会运行真实的编码器、解码器、归并逻辑和重组器:

rust
use futures::stream;
use rig::driver::{Exchange, Model, Opened, Opening, Transport};
use rig::wire::{Encoded, Wire, WireFrame};


/// Replays one recorded reply body for any HTTP wire.
#[derive(Clone)]
struct Replay(&'static str);


impl<W: Wire<Payload = Encoded, Frame = WireFrame>> Transport<W> for Replay {
    fn send(&self, payload: Encoded, _exchange: Exchange) -> Opening<WireFrame> {
        let frames = payload.framing.split(self.0.as_bytes());
        Opening::ready(Opened::new(stream::iter(frames.into_iter().map(Ok))))
    }
}


let wire = AcmeChat {
    config: AcmeConfig::new("test-key"),
    model: "acme-large".to_owned(),
};
let streamed = concat!(
    r#"{"text":"Hel"}"#, "\n",
    r#"{"text":"lo"}"#, "\n",
    r#"{"id":"gen_1","done":true,"usage":{"input_tokens":3,"output_tokens":2},"vendor_metric":7}"#, "\n",
);
let model = Model::new(wire, Replay(streamed));


let response = model.stream("hi")?.finish().await?;
assert_eq!(response.text(), "Hello");
assert_eq!(response.usage.output_tokens, Some(2));
assert_eq!(response.raw["text"], "Hello");
assert_eq!(response.raw["vendor_metric"], 7);

完整代码与上下文 ↗编译通过 · Rig 0.46.0

工具调用#

要支持工具,在 accepts 中设置 tools: true。然后发送 request.tools,其中每个工具包含 name、description 和 JSON Schema parameters,并编码历史中的 AssistantContent::ToolCall 与 UserContent::ToolResult。解码时,用 out.fragment 写入每个工具调用增量。Writer 按服务商给出的索引汇总片段,允许 ID 或名称晚到,并随着参数增长发出流式事件。结束响应前,关闭每个尚未结束的调用:

rust
use rig::operation::{CallFragment, Completion};
use rig::wire::Out;
use rig::ProviderError;


/// One streamed tool-call delta, as an OpenAI-style API sends it.
fn write_call_delta(
    out: &mut Out<'_, Completion>,
    index: usize,
    id: Option<&str>,
    name: Option<&str>,
    arguments: &str,
) -> Result<(), ProviderError> {
    out.fragment(Some(index), CallFragment { id, name, arguments: Some(arguments) })
}


/// The provider's end of the reply: close the open calls, then `out.end(..)`.
fn close_calls(out: &mut Out<'_, Completion>) -> Result<(), ProviderError> {
    out.finish_open()
}

完整代码与上下文 ↗编译通过 · Rig 0.46.0

如果调用一次性完整到达,使用 out.whole(index, Block::Call { .. }, item, arguments);推理文本的 Block::Reasoning 采用相同机制。内置服务商是对接真实 API 的最佳参考。Ollama 原生聊天 wire(rig::providers::ollama::Chat)是一个紧凑完整的示例,包含工具、图片和 NDJSON 流式输出。

其他操作#

补全只是一种操作。嵌入、重排序、转写、图片和音频生成(rig::operation::{Embedding, Rerank, Transcription, ImageGeneration, AudioGeneration})遵循同样方式:为对应操作实现 wire,指定其 Op 类型,并提供响应解码器。可参考匹配的内置 wire,例如 openai::wire::Embeddings。

如果端点不属于任何现有操作,可定义自己的 rig::wire::Operation,包含请求、响应和 fold(归并器)。当响应是单个 JSON 文档时,现成的 Json 解码器和 Whole fold 可以完成工作。Rig 的 frozen_api 示例 展示了这种方式(p6_http_operation.rs),以及自定义 OpenAI 协议变体(p7_openai_compatible_vendor.rs)和返回已记录响应的传输层(p8_custom_transport.rs)。

另请参阅#

本文译自 Rig 官方英文文档,中文翻译未经官方审核。代码已按 Rig 0.46.0 更新;英文快照保存在 source,验证范围见版本说明。
原文版权归 Playgrounds / Rig 作者所有 · MIT 许可 · 升级与验证记录 · 站点地图

搜索中文概念、方法名或英文术语。