pub struct OpenAIResponsesClient { /* private fields */ }Expand description
Client for the OpenAI Responses API (/responses endpoint).
Wraps async-openai’s typed Responses client and implements adk_core::Llm.
Supports reasoning summaries, conversation state via previous_response_id,
and built-in tools (web search, file search, code interpreter).
§Example
use adk_model::openai::{OpenAIResponsesClient, OpenAIResponsesConfig};
let config = OpenAIResponsesConfig::new("sk-...", "o3");
let client = OpenAIResponsesClient::new(config)?;Implementations§
Source§impl OpenAIResponsesClient
impl OpenAIResponsesClient
Sourcepub async fn poll_response(
&self,
response_id: &str,
) -> Result<LlmResponse, AdkError>
pub async fn poll_response( &self, response_id: &str, ) -> Result<LlmResponse, AdkError>
Poll a background response by ID.
Calls GET /v1/responses/{response_id} and returns the current status
or completed result as an LlmResponse.
§Status Handling
- Completed: Returns a full
LlmResponsewith content, usage, and metadata. - In Progress / Queued: Returns an
LlmResponsewithprovider_metadatacontainingresponse_idandstatus, but no content. - Failed: Returns an
LlmResponsewitherror_codeanderror_messagepopulated from the response error object.
§Errors
Returns AdkError if the HTTP request fails (network error, auth error, etc.).
§Example
let response = client.poll_response("resp_abc123").await?;
if let Some(metadata) = &response.provider_metadata {
let status = metadata["openai"]["status"].as_str();
println!("Response status: {:?}", status);
}Sourcepub async fn cancel_response(
&self,
response_id: &str,
) -> Result<LlmResponse, AdkError>
pub async fn cancel_response( &self, response_id: &str, ) -> Result<LlmResponse, AdkError>
Cancel a background response by ID.
Calls POST /v1/responses/{response_id}/cancel to cancel a response
that was created with background: true. Only background responses
can be cancelled.
§Returns
Returns an LlmResponse with status: "cancelled" in provider_metadata
on success.
§Errors
Returns AdkError if:
- The HTTP request fails (network error, auth error)
- The response is not a background response
- The response has already completed
§Example
let response = client.cancel_response("resp_abc123").await?;
println!("Response cancelled: {:?}", response.provider_metadata);Source§impl OpenAIResponsesClient
impl OpenAIResponsesClient
Sourcepub async fn compact_response(
&self,
response_id: &str,
) -> Result<LlmResponse, AdkError>
pub async fn compact_response( &self, response_id: &str, ) -> Result<LlmResponse, AdkError>
Explicitly compact a conversation by response ID.
Calls POST /v1/responses/{id}/compact and returns the compacted response.
The compacted response ID is preserved in provider_metadata["openai"]["response_id"]
for subsequent previous_response_id chaining.
§Errors
Returns AdkError with category NotFound and code
model.openai_responses.compaction_not_found if the response ID does not exist (404).
§Example
let compacted = client.compact_response("resp_abc123").await?;
let new_id = compacted.provider_metadata
.as_ref()
.and_then(|m| m.get("openai"))
.and_then(|o| o.get("response_id"))
.and_then(|v| v.as_str());Source§impl OpenAIResponsesClient
impl OpenAIResponsesClient
Sourcepub fn new(config: OpenAIResponsesConfig) -> Result<Self, AdkError>
pub fn new(config: OpenAIResponsesConfig) -> Result<Self, AdkError>
Create a new Responses API client from the given config.
§Errors
Returns AdkError with InvalidInput if api_key is empty and
Open Responses mode is not enabled with a custom base URL.
Sourcepub fn new_with_reasoning_effort(
config: OpenAIResponsesConfig,
reasoning_effort: OpenAIReasoningEffort,
) -> Result<Self, AdkError>
pub fn new_with_reasoning_effort( config: OpenAIResponsesConfig, reasoning_effort: OpenAIReasoningEffort, ) -> Result<Self, AdkError>
Create a Responses API client with the complete reasoning-effort vocabulary.
This constructor supports the none, minimal, xhigh, and max values
used across current OpenAI model generations while retaining the original
configuration field for backward compatibility.
Sourcepub fn with_provider_name(self, provider_name: impl Into<String>) -> Self
pub fn with_provider_name(self, provider_name: impl Into<String>) -> Self
Names the provider that serves the endpoint, such as muse for the Meta Model API.
The name replaces openai-responses on the telemetry span, in the spend bound
(Llm::max_cost_micro_usd) and on every error the client returns, and replaces
openai as the provider responses are priced and attributed under, so the pricing
catalog bills the provider’s own rates.
§Example
use adk_model::openai::{OpenAIResponsesClient, OpenAIResponsesConfig};
let config = OpenAIResponsesConfig::new("key", "muse-spark-1.3")
.with_base_url("https://api.meta.ai/v1")
.with_open_responses_mode(true);
let client = OpenAIResponsesClient::new(config)?.with_provider_name("muse");
assert_eq!(client.provider_name(), "muse");Sourcepub fn with_websocket(self, transport: WsTransport) -> Self
pub fn with_websocket(self, transport: WsTransport) -> Self
Streams generations over transport’s pooled WebSocket connections
(requires the openai-ws feature).
Build the transport from the same OpenAIResponsesConfig as the client, so it uses
the same credentials and endpoint. Non-streaming and background requests stay on
HTTP. A WebSocket failure is returned as it is unless
with_websocket_fallback is on.
§Example
use adk_model::openai::{OpenAIResponsesClient, OpenAIResponsesConfig, WsTransport};
let config = OpenAIResponsesConfig::new("sk-...", "gpt-6.1-sol");
let client = OpenAIResponsesClient::new(config.clone())?
.with_websocket(WsTransport::new(&config)?)
.with_websocket_fallback(true);Sourcepub fn with_websocket_fallback(self, fallback: bool) -> Self
pub fn with_websocket_fallback(self, fallback: bool) -> Self
Sends a streamed generation over HTTP when the WebSocket failed before any of it was
written — a refused or failed handshake, a connect timeout, or every connection busy
past the acquire timeout (default off; requires the openai-ws feature).
A failure after the request was written never falls back: the server may be generating it, and a second request would generate, run hosted tools and bill twice.
§Example
let client = client.with_websocket(WsTransport::new(&config)?).with_websocket_fallback(true);Sourcepub fn provider_name(&self) -> &str
pub fn provider_name(&self) -> &str
The provider name spans, spend bounds and errors carry: the
with_provider_name name, or openai-responses.
Sourcepub fn with_default_headers(self, headers: HeaderMap) -> Result<Self, AdkError>
pub fn with_default_headers(self, headers: HeaderMap) -> Result<Self, AdkError>
Adds default HTTP headers to generation and auxiliary requests.
Headers with the same name replace earlier defaults; the per-request
authorization header takes precedence. The generation transport keeps
redirects disabled, the Open Responses and maximum-reasoning rewrites, and any
Self::with_request_adapter adapter, whichever order the methods are called
in. Unlike builder methods that only store a value, this method rebuilds both
reqwest clients, so it returns Result.
§Example
use adk_model::openai::{OpenAIResponsesClient, OpenAIResponsesConfig};
use http::header::{HeaderMap, HeaderValue};
let mut headers = HeaderMap::new();
headers.insert("x-session-id", HeaderValue::from_static("conversation-1"));
let client = OpenAIResponsesClient::new(OpenAIResponsesConfig::new("sk-key", "gpt-5"))?
.with_default_headers(headers)?;§Errors
Returns an Internal error with code model.openai.http_client_init when
either HTTP client cannot be built.
Sourcepub fn with_timeouts(self, timeouts: HttpTimeouts) -> Result<Self, AdkError>
pub fn with_timeouts(self, timeouts: HttpTimeouts) -> Result<Self, AdkError>
Sets the connect and idle timeouts of the generation transport and of the auxiliary client, so a stalled stream fails instead of holding the run.
See HttpTimeouts for the defaults. Like
Self::with_default_headers, this rebuilds both reqwest clients, so it returns
Result.
§Example
use std::time::Duration;
use adk_model::openai::{OpenAIResponsesClient, OpenAIResponsesConfig};
use adk_model::HttpTimeouts;
let client = OpenAIResponsesClient::new(OpenAIResponsesConfig::new("sk-key", "gpt-6.1-sol"))?
.with_timeouts(HttpTimeouts::new(Duration::from_secs(10), Duration::from_secs(120)))?;§Errors
Returns an Internal error with code model.openai.http_client_init when
either HTTP client cannot be built.
Sourcepub fn with_retry_config(self, retry_config: RetryConfig) -> Self
pub fn with_retry_config(self, retry_config: RetryConfig) -> Self
Set the retry configuration, consuming self.
Sourcepub fn with_request_adapter(self, adapter: RequestAdapter) -> Self
pub fn with_request_adapter(self, adapter: RequestAdapter) -> Self
Customize generation request fields and headers before each HTTP attempt.
The adapter runs under this client’s RetryConfig; no HTTP retry layer is
added. It applies to generation requests, not to compaction or polling.
§Example
use adk_model::openai::{OpenAIResponsesClient, OpenAIResponsesConfig, RequestAdapter};
use std::sync::Arc;
let adapter: RequestAdapter = Arc::new(|body, headers| {
body["metadata"] = serde_json::json!({"application": "example"});
headers.insert("x-request-source", "example".parse().expect("valid header"));
Ok(())
});
let client = OpenAIResponsesClient::new(OpenAIResponsesConfig::new("sk-key", "gpt-5"))?
.with_request_adapter(adapter);Sourcepub fn with_response_observer(self, observer: ResponseObserver) -> Self
pub fn with_response_observer(self, observer: ResponseObserver) -> Self
Observe raw response headers for each Responses generation HTTP attempt.
The observer runs before status handling or body consumption, including
for unsuccessful responses. It runs once per HTTP attempt, so a request
retried under RetryConfig calls it once per attempt. It applies to
POST /responses only, not to background polling, cancellation, or
compaction requests.
The callback runs on the request path: it must not panic, block, or perform I/O. Headers may include cookies and other credentials, so do not log or retain the whole map.
§Example
use adk_model::openai::{OpenAIResponsesClient, OpenAIResponsesConfig, ResponseObserver};
use std::sync::{Arc, atomic::{AtomicUsize, Ordering}};
let observed = Arc::new(AtomicUsize::new(0));
let count = Arc::clone(&observed);
let observer: ResponseObserver = Arc::new(move |headers| {
if headers.contains_key("x-request-id") {
count.fetch_add(1, Ordering::Relaxed);
}
});
let client = OpenAIResponsesClient::new(OpenAIResponsesConfig::new("sk-key", "gpt-5"))?
.with_response_observer(observer);Sourcepub fn set_retry_config(&mut self, retry_config: RetryConfig)
pub fn set_retry_config(&mut self, retry_config: RetryConfig)
Set the retry configuration by mutable reference.
Sourcepub fn retry_config(&self) -> &RetryConfig
pub fn retry_config(&self) -> &RetryConfig
Get a reference to the current retry configuration.
Sourcepub fn is_open_responses_mode(&self) -> bool
pub fn is_open_responses_mode(&self) -> bool
Whether Open Responses mode is enabled.
When true, the client relaxes strict OpenAI field validation for
compatibility with third-party Open Responses-compatible endpoints.
Trait Implementations§
Source§impl Llm for OpenAIResponsesClient
impl Llm for OpenAIResponsesClient
Source§fn max_cost_micro_usd(&self, request: &LlmRequest) -> Option<u64>
fn max_cost_micro_usd(&self, request: &LlmRequest) -> Option<u64>
request can cost on this model. Read moreSource§fn context_window(&self) -> Option<u64>
fn context_window(&self) -> Option<u64>
Source§fn data_locality(&self) -> DataLocality
fn data_locality(&self) -> DataLocality
DataLocality::Remote),
to a server on this machine (DataLocality::Loopback), or nowhere outside this
process (DataLocality::InProcess). Read moreSource§fn data_destinations(&self) -> Vec<DataDestination>
fn data_destinations(&self) -> Vec<DataDestination>
LlmResponse::provider, with the hosts its client connects to. Read moreSource§fn native_web_search(&self) -> Option<NativeWebSearch>
fn native_web_search(&self) -> Option<NativeWebSearch>
Source§fn generate_content<'life0, 'async_trait>(
&'life0 self,
request: LlmRequest,
stream: bool,
) -> Pin<Box<dyn Future<Output = Result<LlmResponseStream, AdkError>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
fn generate_content<'life0, 'async_trait>(
&'life0 self,
request: LlmRequest,
stream: bool,
) -> Pin<Box<dyn Future<Output = Result<LlmResponseStream, AdkError>> + Send + 'async_trait>>where
Self: 'async_trait,
'life0: 'async_trait,
Source§fn generate_content_metered<'life0, 'life1, 'async_trait>(
&'life0 self,
scope: &'life1 ModelCallScope,
req: LlmRequest,
stream: bool,
) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<LlmResponse, AdkError>> + Send>>, AdkError>> + Send + 'async_trait>>where
'life0: 'async_trait,
'life1: 'async_trait,
Self: 'async_trait,
fn generate_content_metered<'life0, 'life1, 'async_trait>(
&'life0 self,
scope: &'life1 ModelCallScope,
req: LlmRequest,
stream: bool,
) -> Pin<Box<dyn Future<Output = Result<Pin<Box<dyn Stream<Item = Result<LlmResponse, AdkError>> + Send>>, AdkError>> + Send + 'async_trait>>where
'life0: 'async_trait,
'life1: 'async_trait,
Self: 'async_trait,
scope. Read moreSource§fn schema_adapter(&self) -> &dyn SchemaAdapter
fn schema_adapter(&self) -> &dyn SchemaAdapter
Source§fn uses_interactions_api(&self) -> bool
fn uses_interactions_api(&self) -> bool
true if this model is configured to use a server-managed
environment (e.g., Gemini Interactions API) where the provider owns
the tool-calling loop and filesystem. Read moreSource§fn native_compaction(&self) -> Option<NativeCompaction>
fn native_compaction(&self) -> Option<NativeCompaction>
Source§fn prewarm<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<(), AdkError>> + Send + 'async_trait>>where
'life0: 'async_trait,
Self: 'async_trait,
fn prewarm<'life0, 'async_trait>(
&'life0 self,
) -> Pin<Box<dyn Future<Output = Result<(), AdkError>> + Send + 'async_trait>>where
'life0: 'async_trait,
Self: 'async_trait,
Auto Trait Implementations§
impl !RefUnwindSafe for OpenAIResponsesClient
impl !UnwindSafe for OpenAIResponsesClient
impl Forget for OpenAIResponsesClient
impl Freeze for OpenAIResponsesClientwhere
*const ArcInner<ClientRef> is !null: Freeze,
PhantomData<ArcInner<ClientRef>>: Freeze,
*const ArcInner<dyn HttpExecutor> is !null: Freeze,
PhantomData<ArcInner<dyn HttpExecutor>>: Freeze,
*const u8 is !null: Freeze,
PhantomData<u8>: Freeze,
*const str is !null: Freeze,
PhantomData<str>: Freeze,
*const [Pos] is !null: Freeze,
PhantomData<[Pos]>: Freeze,
PhantomData<Bucket<HeaderValue>>: Freeze,
PhantomData<ExtraValue<HeaderValue>>: Freeze,
*const ArcInner<dyn Fn(&mut Value, &mut HeaderMap) -> Result<(), AdkError> + Sync + Send> is !null: Freeze,
PhantomData<ArcInner<dyn Fn(&mut Value, &mut HeaderMap) -> Result<(), AdkError> + Sync + Send>>: Freeze,
*const ArcInner<dyn Fn(&HeaderMap) + Sync + Send> is !null: Freeze,
PhantomData<ArcInner<dyn Fn(&HeaderMap) + Sync + Send>>: Freeze,
*const ArcInner<WsTransport> is !null: Freeze,
PhantomData<ArcInner<WsTransport>>: Freeze,
impl Move for OpenAIResponsesClient
impl Send for OpenAIResponsesClient
impl Sync for OpenAIResponsesClient
impl Unpin for OpenAIResponsesClientwhere
Arc<ClientRef>: Unpin,
Arc<dyn HttpExecutor>: Unpin,
*const u8 is !null: Unpin,
Box<str>: Unpin,
Box<[Pos]>: Unpin,
*const u8: Unpin,
Align8<*mut ()>: Unpin,
&'static Vtable: Unpin,
Arc<dyn Fn(&mut Value, &mut HeaderMap) -> Result<(), AdkError> + Sync + Send>: Unpin,
Arc<dyn Fn(&HeaderMap) + Sync + Send>: Unpin,
Arc<WsTransport>: Unpin,
impl UnsafeUnpin for OpenAIResponsesClientwhere
*const ArcInner<ClientRef> is !null: UnsafeUnpin,
PhantomData<ArcInner<ClientRef>>: UnsafeUnpin,
*const ArcInner<dyn HttpExecutor> is !null: UnsafeUnpin,
PhantomData<ArcInner<dyn HttpExecutor>>: UnsafeUnpin,
*const u8 is !null: UnsafeUnpin,
PhantomData<u8>: UnsafeUnpin,
*const str is !null: UnsafeUnpin,
PhantomData<str>: UnsafeUnpin,
*const [Pos] is !null: UnsafeUnpin,
PhantomData<[Pos]>: UnsafeUnpin,
PhantomData<Bucket<HeaderValue>>: UnsafeUnpin,
PhantomData<ExtraValue<HeaderValue>>: UnsafeUnpin,
*const ArcInner<dyn Fn(&mut Value, &mut HeaderMap) -> Result<(), AdkError> + Sync + Send> is !null: UnsafeUnpin,
PhantomData<ArcInner<dyn Fn(&mut Value, &mut HeaderMap) -> Result<(), AdkError> + Sync + Send>>: UnsafeUnpin,
*const ArcInner<dyn Fn(&HeaderMap) + Sync + Send> is !null: UnsafeUnpin,
PhantomData<ArcInner<dyn Fn(&HeaderMap) + Sync + Send>>: UnsafeUnpin,
*const ArcInner<WsTransport> is !null: UnsafeUnpin,
PhantomData<ArcInner<WsTransport>>: UnsafeUnpin,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
Source§impl<T> FutureExt for T
impl<T> FutureExt for T
Source§fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
fn with_context(self, otel_cx: Context) -> WithContext<Self> ⓘ
Source§fn with_current_context(self) -> WithContext<Self> ⓘ
fn with_current_context(self) -> WithContext<Self> ⓘ
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§impl<T> IntoRequest<T> for T
impl<T> IntoRequest<T> for T
Source§fn into_request(self) -> Request<T>
fn into_request(self) -> Request<T>
T in a tonic::Request