Skip to main content

Client

Struct Client 

Source
pub struct Client { /* private fields */ }
Expand description

The OpenRouter client. Cheap to Clone (internally an Arc).

Implementations§

Source§

impl Client

Source

pub fn builder() -> ClientBuilder

Start a new ClientBuilder.

Source

pub fn new(api_key: impl Into<String>) -> Result<Self>

Build a client with only an API key, using all other defaults.

Source

pub fn api_key(&self) -> &str

Configured API key.

Source

pub fn base_url(&self) -> &Url

Configured base URL.

Source

pub fn http(&self) -> &Client

Underlying reqwest::Client.

Source

pub fn retry(&self) -> &RetryConfig

Active retry configuration.

Source

pub fn stream_reconnects(&self) -> u32

Maximum number of reconnect attempts after a transient stream failure.

Source

pub fn app_name(&self) -> Option<&str>

Optional app-attribution name (sent as X-Title in Phase 2+).

Source

pub fn referer(&self) -> Option<&str>

Optional referer (sent as HTTP-Referer in Phase 2+).

Source

pub async fn chat_complete( &self, req: ChatCompletionRequest, ) -> Result<ChatCompletionResponse>

Send a chat-completions request and decode the unary response.

Retries transient failures per the client’s RetryConfig. If req.stream is set, it is forced to Some(false) so a caller-set stream: true cannot subvert the unary endpoint.

Source

pub async fn complete( &self, req: CompletionRequest, ) -> Result<CompletionResponse>

Send a legacy text-completions request and decode the unary response.

req.stream is forced to Some(false) for the same reason as Client::chat_complete.

Source

pub async fn chat_complete_stream( &self, req: ChatCompletionRequest, ) -> Result<EventStream<ChatCompletionResponse>>

Open a streaming chat-completions request.

Returns an EventStream<ChatCompletionResponse>; each yielded chunk carries delta (instead of message) on its choices. The stream terminates cleanly on the [DONE] SSE marker.

Transient mid-stream disconnects (timeouts, 5xx, 429) trigger a reconnect with exponential backoff capped at MAX_RECONNECT_BACKOFF, re-sending the original request body. Dropping the returned stream cancels the underlying connection.

Source

pub async fn complete_stream( &self, req: CompletionRequest, ) -> Result<EventStream<CompletionResponse>>

Open a streaming legacy completions request. Semantics mirror Client::chat_complete_stream; chunks deserialize into CompletionResponse with the streaming text delta on each choice.

Source

pub async fn list_models( &self, opts: Option<&ListModelsOptions>, ) -> Result<ModelsResponse>

List available models on OpenRouter.

GET /models. Supports an optional category filter (ListModelsOptions::category) and supported-parameter filter. The supported_parameters field of each crate::Model is the union of parameters across all providers — a single provider may not offer every listed parameter.

Source

pub async fn list_model_endpoints( &self, author: &str, slug: &str, ) -> Result<ModelEndpointsResponse>

List per-provider endpoints for a single model.

GET /models/{author}/{slug}/endpoints. The response includes pricing, status, context length, uptime, quantization, and supported parameters for every provider serving the model — useful for routing or price comparison.

Source

pub async fn list_providers(&self) -> Result<ProvidersResponse>

List all providers available through OpenRouter.

GET /providers. Returns the provider name, slug, and policy / status-page URLs (when published).

Source

pub async fn get_credits(&self) -> Result<CreditsResponse>

Retrieve the authenticated user’s purchased credits and total usage.

GET /credits. Use crate::CreditsData::remaining for the available balance.

Source

pub async fn get_key(&self) -> Result<KeyResponse>

Retrieve metadata about the currently authenticated API key.

GET /key. Returns label, configured spend limit, current usage, remaining balance, free-tier flag, provisioning-key flag, and any configured rate limit.

Source

pub async fn get_activity( &self, opts: Option<&ActivityOptions>, ) -> Result<ActivityResponse>

Daily activity grouped by model endpoint for the last 30 completed UTC days.

GET /activity. Requires a provisioning key — using a regular inference key returns 401. If ActivityOptions::date is set (YYYY-MM-DD), results are filtered to that single UTC day.

When ingesting on a schedule, wait ~30 minutes past the UTC boundary before requesting the previous day: events are aggregated by request start time, and some reasoning models take a few minutes to complete.

Source

pub async fn list_keys( &self, opts: Option<&ListKeysOptions>, ) -> Result<ListKeysResponse>

List all API keys on the account.

GET /keys. Requires a provisioning key. Supports offset and include_disabled filters via ListKeysOptions.

Source

pub async fn get_key_by_hash(&self, hash: &str) -> Result<GetKeyByHashResponse>

Look up a single API key by its hash (returned from Client::list_keys or Client::create_key).

GET /keys/{hash}. Requires a provisioning key.

Source

pub async fn create_key( &self, req: &CreateKeyRequest, ) -> Result<CreateKeyResponse>

Create a new API key.

POST /keys. Requires a provisioning key. The plaintext key is returned only once in CreateKeyResponse::key — store it immediately, it cannot be recovered later.

Source

pub async fn update_key( &self, hash: &str, req: &UpdateKeyRequest, ) -> Result<UpdateKeyResponse>

Update an existing API key by hash. Pass only the fields you want to change on UpdateKeyRequest.

PATCH /keys/{hash}. Requires a provisioning key.

Source

pub async fn delete_key(&self, hash: &str) -> Result<DeleteKeyResponse>

Delete an API key by hash.

DELETE /keys/{hash}. Requires a provisioning key. This operation is irreversible — the deleted key cannot be restored, and any clients still using it will immediately start receiving 401s.

Source

pub async fn list_guardrails( &self, opts: Option<&ListGuardrailsOptions>, ) -> Result<ListGuardrailsResponse>

List guardrails for the organization.

GET /guardrails. Requires a provisioning key.

Source

pub async fn create_guardrail( &self, req: &CreateGuardrailRequest, ) -> Result<Guardrail>

Create a new guardrail. name is required.

POST /guardrails. Requires a provisioning key.

Source

pub async fn get_guardrail(&self, id: &str) -> Result<Guardrail>

Fetch a single guardrail by ID.

GET /guardrails/{id}. Requires a provisioning key.

Source

pub async fn update_guardrail( &self, id: &str, req: &UpdateGuardrailRequest, ) -> Result<Guardrail>

Update an existing guardrail. Pass only the fields you want to change on UpdateGuardrailRequest.

PATCH /guardrails/{id}. Requires a provisioning key.

Source

pub async fn delete_guardrail( &self, id: &str, ) -> Result<DeleteGuardrailResponse>

Delete a guardrail by ID. Irreversible.

DELETE /guardrails/{id}. Requires a provisioning key.

Source

pub async fn list_all_guardrail_key_assignments( &self, opts: Option<&ListGuardrailsOptions>, ) -> Result<ListGuardrailKeyAssignmentsResponse>

List key assignments across all guardrails.

GET /guardrails/key-assignments. Requires a provisioning key.

Source

pub async fn list_guardrail_key_assignments( &self, id: &str, opts: Option<&ListGuardrailsOptions>, ) -> Result<ListGuardrailKeyAssignmentsResponse>

List key assignments for a specific guardrail.

GET /guardrails/{id}/key-assignments. Requires a provisioning key.

Source

pub async fn assign_keys_to_guardrail( &self, id: &str, req: &AssignKeysRequest, ) -> Result<AssignKeysResponse>

Assign API keys (by hash) to a guardrail.

POST /guardrails/{id}/key-assignments. Requires a provisioning key.

Source

pub async fn unassign_keys_from_guardrail( &self, id: &str, req: &AssignKeysRequest, ) -> Result<()>

Remove key assignments from a guardrail.

DELETE /guardrails/{id}/key-assignments (with body). Requires a provisioning key.

Source

pub async fn list_all_guardrail_member_assignments( &self, opts: Option<&ListGuardrailsOptions>, ) -> Result<ListGuardrailMemberAssignmentsResponse>

List member assignments across all guardrails.

GET /guardrails/member-assignments. Requires a provisioning key.

Source

pub async fn list_guardrail_member_assignments( &self, id: &str, opts: Option<&ListGuardrailsOptions>, ) -> Result<ListGuardrailMemberAssignmentsResponse>

List member assignments for a specific guardrail.

GET /guardrails/{id}/member-assignments. Requires a provisioning key.

Source

pub async fn assign_members_to_guardrail( &self, id: &str, req: &AssignMembersRequest, ) -> Result<AssignMembersResponse>

Assign organization members (by user id) to a guardrail.

POST /guardrails/{id}/member-assignments. Requires a provisioning key.

Source

pub async fn unassign_members_from_guardrail( &self, id: &str, req: &AssignMembersRequest, ) -> Result<()>

Remove member assignments from a guardrail.

DELETE /guardrails/{id}/member-assignments (with body). Requires a provisioning key.

Source

pub async fn create_video( &self, req: &VideoGenerationRequest, ) -> Result<VideoGenerationResponse>

Submit a new video generation job.

POST /videos. Returns the initial response (job id, polling URL, status). Poll Client::get_video until crate::VideoStatus::is_terminal returns true, or use Client::wait_for_video. model and prompt are required.

Source

pub async fn get_video(&self, job_id: &str) -> Result<VideoGenerationResponse>

Fetch the current status of a video generation job.

GET /videos/{job_id}.

Source

pub async fn get_video_content( &self, job_id: &str, index: u32, ) -> Result<VideoContentResponse>

Download the generated video bytes for a completed job.

GET /videos/{job_id}/content. Pass index = 0 for the default output; non-zero index selects an additional output when the provider produced multiple videos. Returns the bytes plus the upstream Content-Type (typically application/octet-stream).

Source

pub async fn list_video_models(&self) -> Result<VideoModelsResponse>

List the video generation models available through OpenRouter, including each model’s supported aspect ratios, resolutions, durations, and pricing SKUs.

GET /videos/models.

Source

pub async fn wait_for_video( &self, job_id: &str, interval: Duration, ) -> Result<VideoGenerationResponse>

Poll Client::get_video until the job reaches a terminal status.

Sleeps interval between polls. Returns the final response. The caller is responsible for any overall timeout — wrap this in a tokio::time::timeout if you need one.

Source

pub async fn create_speech(&self, req: &SpeechRequest) -> Result<SpeechResponse>

Synthesize speech audio from text.

POST /audio/speech. Returns the raw audio bytes alongside the upstream Content-Type and the resolved format. input, model, and voice must be non-empty. The format defaults to PCM upstream when SpeechRequest::response_format is unset.

Source

pub async fn rerank(&self, req: &RerankRequest) -> Result<RerankResponse>

Rerank documents against a query using a reranking model (e.g. cohere/rerank-v3.5).

POST /rerank. Returns results sorted by descending relevance score. model, query, and at least one document are required.

Source

pub async fn list_zdr_endpoints(&self) -> Result<ZdrEndpointsResponse>

List endpoints compatible with Zero Data Retention.

GET /endpoints/zdr. Returns the endpoints that honor ZDR across all providers — useful as a preview before enforcing ZDR on a guardrail or key. No authentication tier requirement beyond a normal API key.

Source

pub async fn list_organization_members( &self, opts: Option<&ListOrganizationMembersOptions>, ) -> Result<ListOrganizationMembersResponse>

List members of the organization associated with the authenticated management key.

GET /organization/members. Requires a provisioning key. Supports offset / limit pagination via ListOrganizationMembersOptions.

Source

pub async fn list_workspaces( &self, opts: Option<&ListWorkspacesOptions>, ) -> Result<ListWorkspacesResponse>

List workspaces on the organization.

GET /workspaces. Requires a provisioning (management) API key. Supports offset / limit pagination via ListWorkspacesOptions.

Source

pub async fn create_workspace( &self, req: &CreateWorkspaceRequest, ) -> Result<CreateWorkspaceResponse>

Create a new workspace.

POST /workspaces. Requires a provisioning key. name and slug must be non-empty.

Source

pub async fn get_workspace( &self, id_or_slug: &str, ) -> Result<GetWorkspaceResponse>

Fetch a single workspace by UUID or slug.

GET /workspaces/{id_or_slug}. Requires a provisioning key.

Source

pub async fn update_workspace( &self, id_or_slug: &str, req: &UpdateWorkspaceRequest, ) -> Result<UpdateWorkspaceResponse>

Update an existing workspace by UUID or slug. Pass only the fields you want to change on UpdateWorkspaceRequest.

PATCH /workspaces/{id_or_slug}. Requires a provisioning key.

Source

pub async fn delete_workspace( &self, id_or_slug: &str, ) -> Result<DeleteWorkspaceResponse>

Delete a workspace by UUID or slug.

DELETE /workspaces/{id_or_slug}. Requires a provisioning key. The default workspace cannot be deleted, and any workspace with active API keys returns an error.

Source

pub async fn add_workspace_members( &self, id_or_slug: &str, user_ids: &[String], ) -> Result<BulkAddWorkspaceMembersResponse>

Bulk-add organization members to a workspace. Members are assigned the same role they hold in the organization.

POST /workspaces/{id_or_slug}/members/add. Requires a provisioning key.

Source

pub async fn remove_workspace_members( &self, id_or_slug: &str, user_ids: &[String], ) -> Result<BulkRemoveWorkspaceMembersResponse>

Bulk-remove members from a workspace. Members with active API keys in the workspace cannot be removed.

POST /workspaces/{id_or_slug}/members/remove. Requires a provisioning key.

Source§

impl Client

Source

pub async fn exchange_auth_code( &self, req: &ExchangeAuthCodeRequest, ) -> Result<ExchangeAuthCodeResponse>

Exchange an authorization code for an API key (POST /auth/keys).

This is the second step of the OAuth PKCE flow, called after the user has authorized the application at OpenRouter and been redirected back with a ?code=… query parameter. When PKCE was used to build the auth URL, ExchangeAuthCodeRequest::code_verifier must be the verifier that produced the challenge.

Source§

impl Client

Source

pub async fn create_response( &self, req: ResponsesRequest, ) -> Result<ResponsesResponse>

[BETA] Submit a unary Responses API request.

POST /responses. req.stream is forced to Some(false) to keep the unary path honest. Returns the decoded ResponsesResponse.

Source

pub async fn create_response_stream( &self, req: ResponsesRequest, ) -> Result<EventStream<ResponsesResponse>>

[BETA] Open a streaming Responses API request.

POST /responses with SSE. Returns an EventStream whose items deserialize into ResponsesResponse chunks. Reconnect / cancel semantics match Client::chat_complete_stream.

Trait Implementations§

Source§

impl Clone for Client

Source§

fn clone(&self) -> Client

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Client

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more