Skip to main content

rig_core/providers/openai/
wire.rs

1//! OpenAI-compatible configurations, dialect policies, and endpoint wires.
2//! A [`Dialect`](crate::providers::openai::wire::Dialect) selects request
3//! and response policies; [`OpenAIConfig`](crate::providers::openai::OpenAIConfig)
4//! holds credentials and overrides. An
5//! [`OpenAI`](crate::providers::openai::OpenAI) client puts
6//! the configuration on a transport and builds each endpoint's model.
7//!
8//! ```
9//! use rig_core::providers::openai::{OpenAIConfig, Route, wire::OpenAiWire};
10//!
11//! let openai = OpenAIConfig::new("key").with_route(Route::Chat).client();
12//! assert!(matches!(openai.completion("gpt-5.2").wire, OpenAiWire::Chat(_)));
13//! ```
14
15use serde::{Deserialize, Serialize};
16
17use crate::client::env::{self, EnvError};
18use crate::wire::Secret;
19
20use super::responses_api::SystemInstructionsPlacement;
21use super::responses_api::wire::Responses;
22
23mod auth;
24pub(crate) mod chat;
25mod dialects;
26/// The merge that assembles a streamed provider object from its fragments.
27pub(crate) mod dto;
28mod modality;
29mod route;
30
31use auth::default_user_agent;
32pub use auth::{Auth, AuthAlternative, CallerIdentity, Identity};
33pub use chat::Chat;
34pub use dialects::*;
35pub use modality::{
36    AcceptedWidths, DimensionsField, EmbeddingQuirks, Embeddings, EmbeddingsDecoder, ImageBody,
37    ImageDatum, Images, ImagesDecoder, ImagesEvent, ImagesReply, ModelEntry, ModelWidth, Models,
38    ModelsDecoder, ModelsReply, Rerank, RerankQuirks, RerankReply, RerankResultEntry, RerankUsage,
39    Speech, SpeechBody, SpeechDecoder, TranscriptionBody, Transcriptions, Verify, VerifyDecoder,
40};
41pub use route::{OpenAiDecoder, OpenAiEvent, OpenAiReassembler, OpenAiWire, Route};
42
43pub(crate) use modality::{encoded, json_post};
44
45/// Backend selected through the Hugging Face router.
46#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
47pub enum SubRoute {
48    /// Hugging Face's own inference backend: the only one that serves
49    /// transcription and image generation.
50    #[default]
51    HFInference,
52    /// Together AI, through the router.
53    Together,
54    /// SambaNova, through the router.
55    SambaNova,
56    /// Fireworks AI, through the router.
57    Fireworks,
58    /// Hyperbolic, through the router.
59    Hyperbolic,
60    /// Nebius, through the router.
61    Nebius,
62    /// Novita, through the router.
63    Novita,
64    /// A route this build does not name.
65    Custom(String),
66}
67
68impl SubRoute {
69    /// The router's slug for this sub-provider.
70    pub fn slug(&self) -> &str {
71        match self {
72            Self::HFInference => "hf-inference",
73            Self::Together => "together",
74            Self::SambaNova => "sambanova",
75            Self::Fireworks => "fireworks",
76            Self::Hyperbolic => "hyperbolic",
77            Self::Nebius => "nebius",
78            Self::Novita => "novita",
79            Self::Custom(route) => route,
80        }
81    }
82
83    /// The router's model id that selects this sub-provider: `model:slug`.
84    /// A model already ending in `:slug` is returned unchanged.
85    pub fn model_identifier(&self, model: &str) -> String {
86        let slug = self.slug();
87        match model.strip_suffix(slug) {
88            Some(rest) if rest.ends_with(':') => model.to_owned(),
89            _ => format!("{model}:{slug}"),
90        }
91    }
92}
93
94impl std::fmt::Display for SubRoute {
95    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96        f.write_str(self.slug())
97    }
98}
99
100impl From<&str> for SubRoute {
101    fn from(route: &str) -> Self {
102        Self::Custom(route.to_owned())
103    }
104}
105
106impl From<String> for SubRoute {
107    fn from(route: String) -> Self {
108        Self::Custom(route)
109    }
110}
111
112/// How a dialect addresses a model.
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
114pub enum Routing {
115    /// Resolve the endpoint under the base URL and send the model in the body.
116    Path,
117    /// Azure: the model is a *deployment* in the URL
118    /// (`{base}/openai/deployments/{model}/chat/completions?api-version=…`)
119    /// and the body carries no `model` field.
120    AzureDeployment,
121}
122
123/// How a dialect spells the output-token cap.
124#[derive(Clone, Copy, Debug, PartialEq, Eq)]
125pub enum OutputCap {
126    /// `max_tokens`, for every endpoint not observed to reject it.
127    Legacy,
128    /// `max_completion_tokens` for OpenAI's reasoning families, which answer
129    /// a `max_tokens` request with `Unsupported parameter`. Scoped to the
130    /// model, because this same wire reaches compatible servers that know
131    /// only the legacy field.
132    OpenAiReasoningFamilies,
133}
134
135/// The tool schema a dialect's strict function calling takes.
136#[derive(Clone, Copy, Debug, PartialEq, Eq)]
137#[non_exhaustive]
138pub enum StrictSchema {
139    /// OpenAI's: every object closed and every property required.
140    OpenAi,
141    /// DeepSeek's: every object closed and every property required,
142    /// keywords beside a `$ref` kept, a `$ref` in `anyOf` written out, a
143    /// one-member `allOf` merged, a type list naming `object` or `array`
144    /// split into an `anyOf`, and a plain string's `format` outside the five
145    /// it names dropped. A tool whose schema it cannot express, such as a
146    /// map, is sent without `strict`.
147    DeepSeek,
148}
149
150/// Dialect-specific transformation of the serialized chat request.
151#[derive(Clone, Copy, Debug, PartialEq, Eq)]
152#[non_exhaustive]
153pub enum BodyRewrite {
154    /// Send the OpenAI-compatible body unchanged.
155    None,
156    /// Hugging Face's router: qualify the model identifier for sub-providers
157    /// that demand one (Fireworks).
158    HuggingFaceRouter,
159    /// DeepSeek: forced tool choices dropped while the model thinks. Its
160    /// reasoning field is [`Quirks::reasoning_field`].
161    DeepSeek,
162    /// Mira's gateway: content-part arrays flattened to strings.
163    Mira,
164    /// Perplexity: text-only content arrays sent as one string.
165    Perplexity,
166    /// Mistral: the forced tool choice relaxed to `auto` beside a structured
167    /// response format, and its own content chunks.
168    Mistral,
169    /// llama.cpp: refuse a specific-function tool choice, which
170    /// `llama-server` silently treats as `auto`.
171    LlamaCpp,
172    /// Moonshot: refuse a specific-function tool choice and coerce
173    /// `required` to `auto` with a steering message.
174    Moonshot,
175    /// OpenRouter: model ids name the upstream vendor (`anthropic/...`),
176    /// which decides what a request carries.
177    OpenRouter,
178    /// Ollama's OpenAI-compatible API: a refusal of `num_ctx` and
179    /// `options`, which only the native route can send.
180    Ollama,
181}
182
183/// Request restrictions and response handling for a Responses dialect.
184#[derive(Debug, Clone, Copy, PartialEq, Eq)]
185pub enum ResponsesContract {
186    /// Standard Responses behavior with independently configured instruction placement.
187    OpenAi,
188    /// xAI's `/v1/responses`: it answers a success with its error envelope
189    /// as the whole body and publishes a finished tool call at
190    /// `output_item.done`, and its native structured output does not
191    /// compose with tool calls. The stream's own `error` event is not this:
192    /// that is protocol on every dialect and the decoder always reads it.
193    Xai,
194    /// Always-streamed Codex responses with optional content-type and envelope fields.
195    /// Requests omit sampling controls, storage, metadata, and structured output.
196    Codex,
197}
198
199/// What a dialect's Responses endpoint is: where it lives, where the system
200/// preamble goes, and which contract it speaks.
201#[derive(Debug, Clone, Copy, PartialEq, Eq)]
202#[non_exhaustive]
203pub struct ResponsesQuirks {
204    /// The endpoint path, appended to the base URL.
205    pub path: &'static str,
206    /// Where Rig's system instructions go in the request. Not part of
207    /// [`Self::contract`]: OpenAI's contract is served with all three
208    /// placements (OpenAI's own `instructions`, Copilot's and OpenRouter's
209    /// `system` items in `input`).
210    pub system_instructions: SystemInstructionsPlacement,
211    /// The role a system message takes in `input`.
212    pub system_role: &'static str,
213    /// Which contract this dialect's endpoint speaks.
214    pub contract: ResponsesContract,
215    /// Whether newly constructed Responses wires normalize tools for strict validation.
216    pub strict_tools_by_default: bool,
217    /// Whether the endpoint returns reasoning ciphertext through
218    /// `include: ["reasoning.encrypted_content"]`, which the wire then asks
219    /// for whenever a request reasons or stores nothing. Where it does not,
220    /// a reasoning item carries its own text and replays with `store: false`.
221    pub reasoning_ciphertext: bool,
222}
223
224impl ResponsesQuirks {
225    /// OpenAI's own Responses contract.
226    pub const fn openai() -> Self {
227        Self {
228            path: "/responses",
229            system_instructions: SystemInstructionsPlacement::Instructions,
230            system_role: "system",
231            contract: ResponsesContract::OpenAi,
232            strict_tools_by_default: false,
233            reasoning_ciphertext: true,
234        }
235    }
236}
237
238/// Optional executable extensions to the shared OpenAI dialect.
239///
240/// Store this value in a `static`: equality means the same extension definition,
241/// not equality of function addresses (which code generation can merge or duplicate).
242/// This lets named dialect persistence reject replaced hooks without interpreting
243/// their behavior or pretending arbitrary callbacks can be serialized.
244#[derive(Debug)]
245pub struct DialectHooks {
246    /// Derive a default endpoint from a credential. `None` uses the dialect's
247    /// static URL. Called only at construction, never on credential replacement.
248    pub default_endpoint: Option<fn(&str) -> Option<String>>,
249    /// Select the default route for a model, unless configuration or, for a
250    /// dialect that routes by catalog, the model's catalog row chose one.
251    pub model_route: Option<fn(&str) -> Route>,
252    /// Apply the completion envelope after shared authentication and identity.
253    /// Called once by either completion encoder; builder errors remain attached
254    /// and are returned when the encoder finishes the request.
255    pub completion_envelope: Option<CompletionEnvelope>,
256    /// Stamp the envelope every modality request (embeddings, listing,
257    /// verification, transcription, images, speech) carries, on the finished
258    /// request. Runs after shared authentication, so a hook may replace the
259    /// credential header rather than add a second one.
260    pub modality_envelope: Option<ModalityEnvelope>,
261    /// Read the models from the listing reply's JSON body. `None` reads the
262    /// shared `{ "data": [...] }` entries.
263    pub model_listing: Option<ModelCatalogue>,
264}
265
266/// A dialect's modality-request headers, applied to the built request.
267pub type ModalityEnvelope =
268    fn(&OpenAIConfig, &mut http::Request<crate::wire::Body>) -> Result<(), http::Error>;
269
270/// A dialect's reading of its model catalogue, given the listing reply's body.
271pub type ModelCatalogue = fn(serde_json::Value) -> crate::model::ModelList;
272
273/// A dialect's completion headers, applied to the authenticated request builder.
274pub type CompletionEnvelope = fn(
275    &OpenAIConfig,
276    &crate::completion::CompletionRequest,
277    http::request::Builder,
278) -> http::request::Builder;
279
280impl PartialEq for DialectHooks {
281    fn eq(&self, other: &Self) -> bool {
282        std::ptr::eq(self, other)
283    }
284}
285
286impl Eq for DialectHooks {}
287
288/// Everything about a dialect that is not its identity: paths, capability
289/// flags, and the one body rewrite it needs.
290///
291/// `#[non_exhaustive]` because the constants live in this crate and a new
292/// quirk must not be a breaking change for a host that stored a wire.
293#[derive(Clone, Copy, Debug, PartialEq, Eq)]
294#[non_exhaustive]
295pub struct Quirks {
296    /// Provider-owned extensions for defaults and completion headers.
297    pub hooks: Option<&'static DialectHooks>,
298    /// How the dialect authenticates.
299    pub auth: Auth,
300    /// How the dialect addresses a model.
301    pub routing: Routing,
302    /// Which completion endpoint
303    /// [`OpenAI::completion`](crate::providers::openai::OpenAI::completion) builds: the
304    /// dialect's flagship. Chat Completions is the one endpoint every
305    /// dialect serves, so it is the baseline; OpenAI itself, xAI and ChatGPT
306    /// serve `/responses` as their primary API and say so.
307    pub completion_route: Route,
308    /// Whether a model's catalog row picks
309    /// [`OpenAI::completion`](crate::providers::openai::OpenAI::completion)'s
310    /// route when the configuration does not, before any hook, for a gateway
311    /// that serves each model on the API models.dev lists for it.
312    pub routes_by_catalog: bool,
313    /// The chat-completions path, relative to the base URL.
314    pub completion_path: &'static str,
315    /// The embeddings path.
316    pub embeddings_path: &'static str,
317    /// The model-listing path.
318    pub models_path: &'static str,
319    /// The path a credential check hits. Empty means the dialect offers no
320    /// check that does not consume tokens (Azure, Perplexity, Copilot).
321    pub verify_path: &'static str,
322    /// The transcription path.
323    pub transcription_path: &'static str,
324    /// The image-generation path.
325    pub image_generation_path: &'static str,
326    /// The speech path.
327    pub audio_generation_path: &'static str,
328    /// Whether `tools`/`tool_choice` reach the provider at all.
329    pub supports_tools: bool,
330    /// The prefix a wire with [`strict_tools`](Chat::strict_tools) puts
331    /// before [`completion_path`](Self::completion_path), for a dialect that
332    /// serves strict function calling apart. A base URL that already ends
333    /// with it gets no second one.
334    pub strict_tools_prefix: Option<&'static str>,
335    /// The tool schema the dialect's strict function calling takes.
336    pub strict_schema: StrictSchema,
337    /// Whether `output_schema` maps to `response_format`.
338    pub supports_response_format: bool,
339    /// Whether to send `response_format` with tools before any tool result.
340    /// When false, defer the format until a tool result exists to avoid suppressing calls.
341    pub response_format_with_tools: bool,
342    /// Whether this server honours an image inside a `role:"tool"` message.
343    pub supports_image_tool_results: bool,
344    /// Where the server takes `system` messages that come after the
345    /// conversation begins.
346    pub later_system: crate::completion::LaterSystem,
347    /// Whether a streaming request asks for the usage chunk through
348    /// `stream_options`.
349    pub stream_include_usage: bool,
350    /// Whether a stream's `[DONE]` ends the turn when no finish reason
351    /// arrived, as a tool call when the reply holds one and a stop otherwise.
352    /// Off, such a stream is truncated.
353    pub done_without_finish_reason: bool,
354    /// How the dialect spells the output-token cap.
355    pub output_cap: OutputCap,
356    /// Whether to consult upstream-native finish reasons when normalized ones are absent.
357    pub native_finish_reason: bool,
358    /// The finish reasons the dialect documents beyond the ones every Chat
359    /// dialect shares (`stop`, `length`, `tool_calls`, `content_filter` and
360    /// their compatible spellings). Any other reason fails the turn.
361    pub finishes: &'static [(&'static str, crate::completion::FinishReason)],
362    /// The field rebuilt reasoning goes under, which every assistant message
363    /// then carries, empty when the turn has none. `None` sends
364    /// reasoning only under the field it arrived in.
365    pub reasoning_field: Option<&'static str>,
366    /// Whether `completion_tokens_details.reasoning_tokens` can be trusted as
367    /// a part of `completion_tokens`, as OpenAI documents it. A dialect whose
368    /// replies report more reasoning than completion leaves the count
369    /// unreported, so [`Usage`](crate::completion::Usage) never reports more
370    /// reasoning than output.
371    pub reliable_reasoning_count: bool,
372    /// Whether a bare JSON string is accepted as a text-only completion reply.
373    pub accepts_bare_string_reply: bool,
374    /// Whether document and file inputs may use provider file IDs.
375    pub accepts_file_ids: bool,
376    /// Whether the credential is a session token that expires within the
377    /// hour, so a saved copy soon stops working.
378    pub short_lived_key: bool,
379    /// The rewrite this dialect applies to the serialized chat body.
380    pub rewrite: BodyRewrite,
381    /// Paths that strip a trailing `/v1` from the configured base URL.
382    pub root_relative_routes: &'static [&'static str],
383    /// Whether the model is the modality endpoint's *path* rather than a
384    /// body field. Hugging Face's router addresses transcription and image
385    /// generation as `/{model}`; everyone else uses a fixed path.
386    pub model_is_modality_path: bool,
387    /// Which body the image endpoint takes.
388    pub image_body: ImageBody,
389    /// Which body the transcription endpoint takes.
390    pub transcription_body: TranscriptionBody,
391    /// Which body the speech endpoint takes.
392    pub speech_body: SpeechBody,
393    /// What the embeddings endpoint accepts.
394    pub embedding: EmbeddingQuirks,
395    /// What the rerank endpoint accepts.
396    pub rerank: RerankQuirks,
397    /// A second environment variable naming the base URL, kept because the
398    /// provider documents both spellings.
399    pub base_url_env_alias: Option<&'static str>,
400    /// The path the API is served at under the address the base-URL
401    /// variable names, when that variable names the server's root, as
402    /// Ollama's does; empty when it names the API itself.
403    pub base_url_env_path: &'static str,
404    /// The environment variable naming the account a credential belongs to,
405    /// sent as `ChatGPT-Account-Id`.
406    pub account_id_env: Option<&'static str>,
407    /// Instructions this gateway expects every turn to carry, merged ahead
408    /// of the caller's preamble.
409    pub default_instructions: Option<&'static str>,
410    /// The environment variable overriding [`Self::default_instructions`].
411    pub instructions_env: Option<&'static str>,
412    /// The caller identity this gateway requires on every request.
413    pub identity: Option<Identity>,
414    /// The header every completion request carries a session id in: the
415    /// request's cache key when it has one, else a fresh id.
416    pub session_header: Option<&'static str>,
417    /// What the Responses endpoint accepts.
418    pub responses: ResponsesQuirks,
419    /// Whether the catalog's per-token API prices apply to replies. A
420    /// subscription backend or a server that is usually local has none.
421    pub catalog_priced: bool,
422}
423
424impl Quirks {
425    /// Baseline compatible endpoint policies with Chat Completions routing and
426    /// the legacy `max_tokens` cap. Dialects override supported differences.
427    pub const fn openai() -> Self {
428        Self {
429            hooks: None,
430            auth: Auth::Bearer,
431            routing: Routing::Path,
432            completion_route: Route::Chat,
433            routes_by_catalog: false,
434            completion_path: "/chat/completions",
435            embeddings_path: "/embeddings",
436            models_path: "/models",
437            verify_path: "/models",
438            transcription_path: "/audio/transcriptions",
439            image_generation_path: "/images/generations",
440            audio_generation_path: "/audio/speech",
441            supports_tools: true,
442            strict_tools_prefix: None,
443            strict_schema: StrictSchema::OpenAi,
444            supports_response_format: true,
445            response_format_with_tools: false,
446            supports_image_tool_results: false,
447            later_system: crate::completion::LaterSystem::InPlace,
448            stream_include_usage: true,
449            done_without_finish_reason: false,
450            output_cap: OutputCap::Legacy,
451            native_finish_reason: false,
452            finishes: &[],
453            reasoning_field: None,
454            reliable_reasoning_count: true,
455            accepts_bare_string_reply: false,
456            accepts_file_ids: true,
457            short_lived_key: false,
458            rewrite: BodyRewrite::None,
459            embedding: EmbeddingQuirks::openai(),
460            // OpenAI has no reranking endpoint, and neither does any dialect
461            // on this wire but llama.cpp.
462            rerank: RerankQuirks::unsupported(),
463            root_relative_routes: &[],
464            model_is_modality_path: false,
465            image_body: ImageBody::OpenAi,
466            speech_body: SpeechBody::OpenAi,
467            transcription_body: TranscriptionBody::Multipart,
468            base_url_env_alias: None,
469            base_url_env_path: "",
470            account_id_env: None,
471            default_instructions: None,
472            instructions_env: None,
473            identity: None,
474            session_header: None,
475            responses: ResponsesQuirks::openai(),
476            catalog_priced: true,
477        }
478    }
479
480    /// These quirks without the streamed usage chunk: a streaming request
481    /// sends no `stream_options`, so streamed usage reports `None`.
482    pub const fn without_stream_usage(mut self) -> Self {
483        self.stream_include_usage = false;
484        self
485    }
486
487    /// These quirks for a gateway whose streams omit `finish_reason`: a
488    /// `[DONE]` after at least one chunk ends the turn as
489    /// [`FinishReason::ToolCalls`](crate::completion::FinishReason::ToolCalls)
490    /// when the reply holds a tool call, and
491    /// [`FinishReason::Stop`](crate::completion::FinishReason::Stop)
492    /// otherwise. A cut-off stream that still sends `[DONE]` then reads as
493    /// complete, so set this only for a gateway known to omit the field.
494    pub const fn done_without_finish_reason(mut self) -> Self {
495        self.done_without_finish_reason = true;
496        self
497    }
498
499    /// These quirks without structured output: `output_schema` does not map
500    /// to `response_format`.
501    pub const fn without_response_format(mut self) -> Self {
502        self.supports_response_format = false;
503        self
504    }
505}
506
507impl Default for Quirks {
508    /// [`Quirks::openai`].
509    fn default() -> Self {
510        Self::openai()
511    }
512}
513
514/// Provider identity, endpoint defaults, and shared-wire policies.
515#[derive(Clone, Copy, Debug, PartialEq, Eq)]
516pub struct Dialect {
517    /// The provider descriptor name, as records and telemetry name it.
518    pub name: &'static str,
519    /// The default base URL.
520    pub base_url: &'static str,
521    /// The environment variable holding the credential.
522    pub api_key_env: &'static str,
523    /// The environment variable overriding the base URL, when the provider
524    /// has one.
525    pub base_url_env: Option<&'static str>,
526    /// The reply header carrying the provider's transport request id.
527    pub request_id_header: Option<&'static str>,
528    /// A second credential this dialect accepts, with its own variable and
529    /// header. `None` for every dialect but Azure.
530    pub alternate_auth: Option<AuthAlternative>,
531    /// Everything that is not identity.
532    pub quirks: Quirks,
533}
534
535impl Dialect {
536    /// Create a dialect with [`Quirks::openai`] and the supplied identity.
537    /// URL overrides, request-ID headers, and alternative credentials are unset.
538    pub const fn gateway(
539        name: &'static str,
540        base_url: &'static str,
541        api_key_env: &'static str,
542    ) -> Self {
543        Self {
544            name,
545            base_url,
546            api_key_env,
547            base_url_env: None,
548            request_id_header: None,
549            alternate_auth: None,
550            quirks: Quirks::openai(),
551        }
552    }
553
554    /// This dialect with `quirks`.
555    pub const fn with_quirks(mut self, quirks: Quirks) -> Self {
556        self.quirks = quirks;
557        self
558    }
559}
560
561/// Serialize the registered dialect name, rejecting unregistered or modified definitions.
562/// Deserialization resolves that name from this build's registry.
563impl Serialize for Dialect {
564    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
565        let registered = dialects::by_name(self.name) == Some(self);
566        crate::providers::internal::named_dialect::serialize(
567            serializer, "OpenAI", self.name, registered,
568        )
569    }
570}
571
572impl<'de> Deserialize<'de> for Dialect {
573    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
574        crate::providers::internal::named_dialect::deserialize(deserializer, "OpenAI", |name| {
575            dialects::by_name(name).copied()
576        })
577    }
578}
579
580/// The settings of an OpenAI-shaped provider: serializable, and the
581/// credential is never serialized. [`connect`](Self::connect) puts it on a
582/// transport as an [`OpenAI`](super::OpenAI) client.
583#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
584#[serde(deny_unknown_fields)]
585pub struct OpenAIConfig {
586    /// The credential. Never serialized (see [`Secret`]).
587    pub api_key: Secret,
588    /// The base URL every path resolves against.
589    pub base_url: String,
590    /// Which OpenAI-shaped provider this is.
591    pub dialect: Dialect,
592    /// The completion endpoint this configuration uses when asked for "a
593    /// completion", when it differs from the dialect's flagship
594    /// ([`Quirks::completion_route`]). Set by [`with_route`](Self::with_route).
595    #[serde(default, skip_serializing_if = "Option::is_none")]
596    pub route: Option<Route>,
597    /// Azure's `api-version` query parameter, which every Azure route
598    /// requires. `None` for every other dialect.
599    #[serde(default, skip_serializing_if = "Option::is_none")]
600    pub api_version: Option<String>,
601    /// Azure versions its speech endpoint separately from the rest, so a
602    /// speech request carries this `api-version` instead of
603    /// [`Self::api_version`]. `None` falls back to `api_version`.
604    #[serde(default, skip_serializing_if = "Option::is_none")]
605    pub audio_api_version: Option<String>,
606    /// How this configuration's credential is sent. Taken from the dialect,
607    /// except when the credential came from the dialect's
608    /// [`alternate_auth`](Dialect::alternate_auth) variable, which has its
609    /// own header.
610    pub auth: Auth,
611    /// Which sub-provider the Hugging Face router forwards to. `None` leaves
612    /// Chat to the router's own routing and sends the model-addressed
613    /// endpoints to [`SubRoute::HFInference`]. `None` for every other
614    /// dialect, which routes nothing.
615    #[serde(default, skip_serializing_if = "Option::is_none")]
616    pub sub_route: Option<SubRoute>,
617    /// The account the credential belongs to, when the gateway asks which
618    /// (`ChatGPT-Account-Id`).
619    #[serde(default, skip_serializing_if = "Option::is_none")]
620    pub account_id: Option<String>,
621    /// Instructions merged ahead of every Responses turn's preamble, when
622    /// the gateway expects some.
623    #[serde(default, skip_serializing_if = "Option::is_none")]
624    pub instructions: Option<String>,
625    /// The caller identity, when the gateway requires one.
626    #[serde(default, skip_serializing_if = "Option::is_none")]
627    pub identity: Option<CallerIdentity>,
628    /// Responses instruction placement override. `None` uses the dialect default.
629    #[serde(default, skip_serializing_if = "Option::is_none")]
630    pub system_instructions: Option<SystemInstructionsPlacement>,
631}
632
633impl OpenAIConfig {
634    /// Official OpenAI, with `api_key`.
635    pub fn new(api_key: impl Into<Secret>) -> Self {
636        Self::with_key(&OPENAI, api_key)
637    }
638
639    /// `dialect` with `api_key`, at the dialect's default base URL and with
640    /// the instructions and caller identity its gateway expects, if any.
641    pub fn with_key(dialect: &Dialect, api_key: impl Into<Secret>) -> Self {
642        let quirks = &dialect.quirks;
643        let api_key = api_key.into();
644        let base_url = quirks
645            .hooks
646            .and_then(|hooks| hooks.default_endpoint)
647            .and_then(|endpoint| endpoint(api_key.expose()))
648            .unwrap_or_else(|| dialect.base_url.to_owned());
649        Self {
650            api_key,
651            base_url,
652            dialect: *dialect,
653            route: None,
654            // Azure deployment URLs require an explicit API version.
655            api_version: match quirks.routing {
656                Routing::AzureDeployment => Some(dialects::AZURE_DEFAULT_API_VERSION.to_owned()),
657                Routing::Path => None,
658            },
659            audio_api_version: None,
660            auth: quirks.auth,
661            sub_route: None,
662            account_id: None,
663            instructions: quirks.default_instructions.map(str::to_owned),
664            identity: quirks.identity.map(|identity| CallerIdentity {
665                originator: identity.originator.to_owned(),
666                user_agent: default_user_agent(identity.originator),
667            }),
668            system_instructions: None,
669        }
670    }
671
672    /// Read `OPENAI_API_KEY` and the optional `OPENAI_BASE_URL` override.
673    /// Return an environment error for missing credentials or invalid values.
674    pub fn from_env() -> Result<Self, EnvError> {
675        Self::from_env_with(&OPENAI)
676    }
677
678    /// `dialect` from its own `api_key_env` and `base_url_env` (or the
679    /// alias its quirks name), plus whatever else its gateway reads: the
680    /// account id, the default instructions and the caller identity.
681    ///
682    /// Azure additionally reads `AZURE_API_VERSION`, because every Azure
683    /// route carries it and there is no default that would not silently
684    /// address the wrong API.
685    pub fn from_env_with(dialect: &Dialect) -> Result<Self, EnvError> {
686        let (api_key, auth) = Self::credential_from_env(dialect)?;
687        Self::from_env_with_credential(dialect, api_key, auth)
688    }
689
690    /// [`Self::from_env_with`] with the credential already read.
691    pub(crate) fn from_env_with_credential(
692        dialect: &Dialect,
693        api_key: String,
694        auth: Auth,
695    ) -> Result<Self, EnvError> {
696        let quirks = &dialect.quirks;
697        let mut provider = Self::with_key(dialect, api_key);
698        provider.auth = auth;
699        for name in [dialect.base_url_env, quirks.base_url_env_alias]
700            .into_iter()
701            .flatten()
702        {
703            if let Some(base_url) = env::optional(name)? {
704                provider.base_url = match quirks.base_url_env_path {
705                    "" => base_url,
706                    path => format!("{}{path}", base_url.trim_end_matches('/')),
707                };
708                break;
709            }
710        }
711        // Azure speech uses an independently versioned endpoint.
712        if let Routing::AzureDeployment = quirks.routing {
713            provider.api_version = Some(env::required(dialects::AZURE_API_VERSION_ENV)?);
714            provider.audio_api_version = env::optional(dialects::AZURE_AUDIO_API_VERSION_ENV)?
715                .or_else(|| Some(dialects::AZURE_DEFAULT_AUDIO_API_VERSION.to_owned()));
716        }
717        if let Some(name) = quirks.account_id_env {
718            provider.account_id = env::optional(name)?;
719        }
720        if let Some(name) = quirks.instructions_env
721            && let Some(instructions) = env::optional(name)?
722            && !instructions.trim().is_empty()
723        {
724            provider.instructions = Some(instructions);
725        }
726        if let (Some(identity), Some(resolved)) = (quirks.identity, provider.identity.as_mut()) {
727            if let Some(originator) =
728                env::optional(identity.originator_env)?.filter(|value| !value.is_empty())
729            {
730                resolved.originator = originator;
731                resolved.user_agent = default_user_agent(&resolved.originator);
732            }
733            if let Some(user_agent) =
734                env::optional(identity.user_agent_env)?.filter(|value| !value.is_empty())
735            {
736                resolved.user_agent = user_agent;
737            }
738        }
739        Ok(provider)
740    }
741
742    /// Point this configuration at another dialect: the same credential,
743    /// with everything else at that dialect's defaults.
744    pub fn with_dialect(self, dialect: &Dialect) -> Self {
745        Self::with_key(dialect, self.api_key)
746    }
747
748    /// Route through a Hugging Face sub-provider. Chat sends the model as
749    /// `model:slug`, which the router reads as an explicit selection.
750    pub fn with_sub_route(mut self, sub_route: SubRoute) -> Self {
751        self.sub_route = Some(sub_route);
752        self
753    }
754
755    /// Override the base URL.
756    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
757        self.base_url = base_url.into();
758        self
759    }
760
761    /// Set Azure's `api-version`.
762    pub fn with_api_version(mut self, api_version: impl Into<String>) -> Self {
763        self.api_version = Some(api_version.into());
764        self
765    }
766
767    /// Merge these instructions ahead of every Responses turn's preamble.
768    pub fn with_instructions(mut self, instructions: impl Into<String>) -> Self {
769        self.instructions = Some(instructions.into());
770        self
771    }
772
773    /// Put Rig's system instructions somewhere other than the dialect's
774    /// default placement, for every Responses wire this configuration
775    /// builds.
776    pub fn with_system_instructions_placement(
777        mut self,
778        placement: SystemInstructionsPlacement,
779    ) -> Self {
780        self.system_instructions = Some(placement);
781        self
782    }
783
784    /// Send Rig's system instructions as `system` messages in `input`, for a
785    /// backend that rejects or ignores top-level `instructions`.
786    pub fn with_system_instructions_as_messages(self) -> Self {
787        self.with_system_instructions_placement(SystemInstructionsPlacement::InputSystemMessages)
788    }
789
790    /// Where a Responses wire built from this configuration puts Rig's
791    /// system instructions: the dialect's placement unless
792    /// [`with_system_instructions_placement`](Self::with_system_instructions_placement)
793    /// chose another.
794    pub fn system_instructions_placement(&self) -> SystemInstructionsPlacement {
795        self.system_instructions
796            .unwrap_or(self.dialect.quirks.responses.system_instructions)
797    }
798
799    /// Override dialect and model-specific routing for the client's
800    /// [`completion`](crate::providers::openai::OpenAI::completion).
801    pub fn with_route(mut self, route: Route) -> Self {
802        self.route = Some(route);
803        self
804    }
805
806    /// The configured route or dialect's static default. A model-route hook
807    /// may refine the default when a completion wire is constructed.
808    pub fn completion_route(&self) -> Route {
809        self.route.unwrap_or(self.dialect.quirks.completion_route)
810    }
811
812    /// The completion wire for `model` on this configuration's
813    /// [`completion_route`](Self::completion_route): Responses for OpenAI,
814    /// xAI and ChatGPT, model-dependent routing when a dialect supplies it, and
815    /// Chat Completions for other compatible gateways, unless
816    /// [`with_route`](Self::with_route) chose the other one.
817    pub(crate) fn completion(&self, model: impl Into<String>) -> OpenAiWire {
818        OpenAiWire::new(self.clone(), model)
819    }
820
821    /// The Responses wire for `model`: `POST /responses`.
822    pub(crate) fn responses(&self, model: impl Into<String>) -> Responses {
823        Responses::new(self.clone(), model)
824    }
825
826    /// The chat-completions wire for `model`, whatever the dialect's
827    /// [`completion_route`](Quirks::completion_route).
828    pub fn chat(&self, model: impl Into<String>) -> Chat {
829        Chat::new(self.clone(), model)
830    }
831
832    pub(crate) fn completion_headers(
833        &self,
834        request: &crate::completion::CompletionRequest,
835        builder: http::request::Builder,
836    ) -> http::request::Builder {
837        let builder = self.headers_in_session(builder, request.options.cache_key.as_deref());
838        match self
839            .dialect
840            .quirks
841            .hooks
842            .and_then(|hooks| hooks.completion_envelope)
843        {
844            Some(envelope) => envelope(self, request, builder),
845            None => builder,
846        }
847    }
848
849    /// Resolve `path` against the base URL, applying Azure's
850    /// deployment-in-URL routing when the dialect uses it.
851    pub(crate) fn uri(&self, path: &str, model: Option<&str>) -> String {
852        self.uri_versioned(path, model, self.api_version.as_deref())
853    }
854
855    /// [`Self::uri`] with an explicit `api-version`, for the one endpoint
856    /// Azure versions separately (speech).
857    pub(crate) fn uri_versioned(
858        &self,
859        path: &str,
860        model: Option<&str>,
861        api_version: Option<&str>,
862    ) -> String {
863        match (self.dialect.quirks.routing, model) {
864            (Routing::AzureDeployment, Some(model)) => format!(
865                "{}/openai/deployments/{}{}?api-version={}",
866                self.base_url.trim_end_matches('/'),
867                model.trim_start_matches('/'),
868                path,
869                api_version.unwrap_or_default(),
870            ),
871            _ => format!("{}{}", self.base(path), path),
872        }
873    }
874
875    /// The base URL `path` resolves against: the configured one, with the
876    /// version segment dropped for a route the dialect serves at the root.
877    fn base(&self, path: &str) -> &str {
878        let base = self.base_url.trim_end_matches('/');
879        if self.dialect.quirks.root_relative_routes.contains(&path) {
880            return base.strip_suffix("/v1").unwrap_or(base);
881        }
882        base
883    }
884
885    /// The sub-provider the Hugging Face router's model-addressed endpoints
886    /// use. `None` on the configuration means HF Inference.
887    pub(crate) fn route(&self) -> std::borrow::Cow<'_, SubRoute> {
888        match &self.sub_route {
889            Some(route) => std::borrow::Cow::Borrowed(route),
890            None => std::borrow::Cow::Owned(SubRoute::default()),
891        }
892    }
893
894    /// Return `model` for Azure deployment routing, otherwise `None`.
895    pub(crate) fn deployment<'a>(&self, model: &'a str) -> Option<&'a str> {
896        match self.dialect.quirks.routing {
897            Routing::AzureDeployment => Some(model),
898            Routing::Path => None,
899        }
900    }
901}
902
903#[cfg(test)]
904mod tests;