pub struct Client { /* private fields */ }Expand description
The OpenRouter client. Cheap to Clone (internally an Arc).
Implementations§
Source§impl Client
impl Client
Sourcepub fn builder() -> ClientBuilder
pub fn builder() -> ClientBuilder
Start a new ClientBuilder.
Sourcepub fn new(api_key: impl Into<String>) -> Result<Self>
pub fn new(api_key: impl Into<String>) -> Result<Self>
Build a client with only an API key, using all other defaults.
Sourcepub fn retry(&self) -> &RetryConfig
pub fn retry(&self) -> &RetryConfig
Active retry configuration.
Sourcepub fn stream_reconnects(&self) -> u32
pub fn stream_reconnects(&self) -> u32
Maximum number of reconnect attempts after a transient stream failure.
Sourcepub fn app_name(&self) -> Option<&str>
pub fn app_name(&self) -> Option<&str>
Optional app-attribution name (sent as X-Title in Phase 2+).
Sourcepub async fn chat_complete(
&self,
req: ChatCompletionRequest,
) -> Result<ChatCompletionResponse>
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.
Sourcepub async fn complete(
&self,
req: CompletionRequest,
) -> Result<CompletionResponse>
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.
Sourcepub async fn chat_complete_stream(
&self,
req: ChatCompletionRequest,
) -> Result<EventStream<ChatCompletionResponse>>
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.
Sourcepub async fn complete_stream(
&self,
req: CompletionRequest,
) -> Result<EventStream<CompletionResponse>>
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.
Sourcepub async fn list_models(
&self,
opts: Option<&ListModelsOptions>,
) -> Result<ModelsResponse>
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.
Sourcepub async fn list_model_endpoints(
&self,
author: &str,
slug: &str,
) -> Result<ModelEndpointsResponse>
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.
Sourcepub async fn list_providers(&self) -> Result<ProvidersResponse>
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).
Sourcepub async fn get_credits(&self) -> Result<CreditsResponse>
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.
Sourcepub async fn get_key(&self) -> Result<KeyResponse>
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.
Sourcepub async fn get_activity(
&self,
opts: Option<&ActivityOptions>,
) -> Result<ActivityResponse>
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.
Sourcepub async fn list_keys(
&self,
opts: Option<&ListKeysOptions>,
) -> Result<ListKeysResponse>
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.
Sourcepub async fn get_key_by_hash(&self, hash: &str) -> Result<GetKeyByHashResponse>
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.
Sourcepub async fn create_key(
&self,
req: &CreateKeyRequest,
) -> Result<CreateKeyResponse>
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.
Sourcepub async fn update_key(
&self,
hash: &str,
req: &UpdateKeyRequest,
) -> Result<UpdateKeyResponse>
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.
Sourcepub async fn delete_key(&self, hash: &str) -> Result<DeleteKeyResponse>
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.
Sourcepub async fn list_guardrails(
&self,
opts: Option<&ListGuardrailsOptions>,
) -> Result<ListGuardrailsResponse>
pub async fn list_guardrails( &self, opts: Option<&ListGuardrailsOptions>, ) -> Result<ListGuardrailsResponse>
List guardrails for the organization.
GET /guardrails. Requires a provisioning key.
Sourcepub async fn create_guardrail(
&self,
req: &CreateGuardrailRequest,
) -> Result<Guardrail>
pub async fn create_guardrail( &self, req: &CreateGuardrailRequest, ) -> Result<Guardrail>
Create a new guardrail. name is required.
POST /guardrails. Requires a provisioning key.
Sourcepub async fn get_guardrail(&self, id: &str) -> Result<Guardrail>
pub async fn get_guardrail(&self, id: &str) -> Result<Guardrail>
Fetch a single guardrail by ID.
GET /guardrails/{id}. Requires a provisioning key.
Sourcepub async fn update_guardrail(
&self,
id: &str,
req: &UpdateGuardrailRequest,
) -> Result<Guardrail>
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.
Sourcepub async fn delete_guardrail(
&self,
id: &str,
) -> Result<DeleteGuardrailResponse>
pub async fn delete_guardrail( &self, id: &str, ) -> Result<DeleteGuardrailResponse>
Delete a guardrail by ID. Irreversible.
DELETE /guardrails/{id}. Requires a provisioning key.
Sourcepub async fn list_all_guardrail_key_assignments(
&self,
opts: Option<&ListGuardrailsOptions>,
) -> Result<ListGuardrailKeyAssignmentsResponse>
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.
Sourcepub async fn list_guardrail_key_assignments(
&self,
id: &str,
opts: Option<&ListGuardrailsOptions>,
) -> Result<ListGuardrailKeyAssignmentsResponse>
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.
Sourcepub async fn assign_keys_to_guardrail(
&self,
id: &str,
req: &AssignKeysRequest,
) -> Result<AssignKeysResponse>
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.
Sourcepub async fn unassign_keys_from_guardrail(
&self,
id: &str,
req: &AssignKeysRequest,
) -> Result<()>
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.
Sourcepub async fn list_all_guardrail_member_assignments(
&self,
opts: Option<&ListGuardrailsOptions>,
) -> Result<ListGuardrailMemberAssignmentsResponse>
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.
Sourcepub async fn list_guardrail_member_assignments(
&self,
id: &str,
opts: Option<&ListGuardrailsOptions>,
) -> Result<ListGuardrailMemberAssignmentsResponse>
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.
Sourcepub async fn assign_members_to_guardrail(
&self,
id: &str,
req: &AssignMembersRequest,
) -> Result<AssignMembersResponse>
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.
Sourcepub async fn unassign_members_from_guardrail(
&self,
id: &str,
req: &AssignMembersRequest,
) -> Result<()>
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.
Sourcepub async fn create_video(
&self,
req: &VideoGenerationRequest,
) -> Result<VideoGenerationResponse>
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.
Sourcepub async fn get_video(&self, job_id: &str) -> Result<VideoGenerationResponse>
pub async fn get_video(&self, job_id: &str) -> Result<VideoGenerationResponse>
Fetch the current status of a video generation job.
GET /videos/{job_id}.
Sourcepub async fn get_video_content(
&self,
job_id: &str,
index: u32,
) -> Result<VideoContentResponse>
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).
Sourcepub async fn list_video_models(&self) -> Result<VideoModelsResponse>
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.
Sourcepub async fn wait_for_video(
&self,
job_id: &str,
interval: Duration,
) -> Result<VideoGenerationResponse>
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.
Sourcepub async fn create_speech(&self, req: &SpeechRequest) -> Result<SpeechResponse>
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.
Sourcepub async fn rerank(&self, req: &RerankRequest) -> Result<RerankResponse>
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.
Sourcepub async fn list_zdr_endpoints(&self) -> Result<ZdrEndpointsResponse>
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.
Sourcepub async fn list_organization_members(
&self,
opts: Option<&ListOrganizationMembersOptions>,
) -> Result<ListOrganizationMembersResponse>
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.
Sourcepub async fn list_workspaces(
&self,
opts: Option<&ListWorkspacesOptions>,
) -> Result<ListWorkspacesResponse>
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.
Sourcepub async fn create_workspace(
&self,
req: &CreateWorkspaceRequest,
) -> Result<CreateWorkspaceResponse>
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.
Sourcepub async fn get_workspace(
&self,
id_or_slug: &str,
) -> Result<GetWorkspaceResponse>
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.
Sourcepub async fn update_workspace(
&self,
id_or_slug: &str,
req: &UpdateWorkspaceRequest,
) -> Result<UpdateWorkspaceResponse>
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.
Sourcepub async fn delete_workspace(
&self,
id_or_slug: &str,
) -> Result<DeleteWorkspaceResponse>
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.
Sourcepub async fn add_workspace_members(
&self,
id_or_slug: &str,
user_ids: &[String],
) -> Result<BulkAddWorkspaceMembersResponse>
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.
Sourcepub async fn remove_workspace_members(
&self,
id_or_slug: &str,
user_ids: &[String],
) -> Result<BulkRemoveWorkspaceMembersResponse>
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
impl Client
Sourcepub async fn exchange_auth_code(
&self,
req: &ExchangeAuthCodeRequest,
) -> Result<ExchangeAuthCodeResponse>
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
impl Client
Sourcepub async fn create_response(
&self,
req: ResponsesRequest,
) -> Result<ResponsesResponse>
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.
Sourcepub async fn create_response_stream(
&self,
req: ResponsesRequest,
) -> Result<EventStream<ResponsesResponse>>
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.