1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
#![warn(clippy::all, clippy::pedantic, clippy::nursery, clippy::cargo)]
#![allow(clippy::doc_markdown)]
#![doc = include_str!("../README.md")]
use reqwest::{
Client as Http, StatusCode,
header::{self, HeaderMap, HeaderValue},
};
use serde_json::json;
use std::env;
use types::{Error, Include, InputItemList, Request, Response, ResponseResult};
/// Types for interacting with the Responses API.
pub mod types;
/// The OpenAI Responses API Client.
pub struct Client {
client: reqwest::Client,
}
/// Errors that can occur when creating a new Client.
#[derive(Debug, thiserror::Error)]
pub enum CreateError {
/// The provided API key contains invalid header value characters. Only visible ASCII characters (32-127) are permitted.
#[error(
"The provided API key contains invalid header value characters. Only visible ASCII characters (32-127) are permitted."
)]
InvalidApiKey,
/// Failed to create the HTTP Client
#[error("Failed to create the HTTP Client: {0}")]
CouldNotCreateClient(#[from] reqwest::Error),
/// Could not retrieve the ``OPENAI_API_KEY`` env var
#[error("Could not retrieve the $OPENAI_API_KEY env var")]
ApiKeyNotFound,
}
impl Client {
/// Creates a new Client with the given API key.
///
/// # Errors
/// - `CreateError::CouldNotCreateClient` if the HTTP Client could not be created.
/// - `CreateError::InvalidApiKey` if the API key contains invalid header value characters.
pub fn new(api_key: &str) -> Result<Self, CreateError> {
let client = Http::builder()
.default_headers(HeaderMap::from_iter([(
header::AUTHORIZATION,
HeaderValue::from_str(&format!("Bearer {api_key}"))
.map_err(|_| CreateError::InvalidApiKey)?,
)]))
.build()?;
Ok(Self { client })
}
/// Creates a new Client from the `OPENAI_API_KEY` environment variable.
/// # Errors
/// - `CreateError::CouldNotCreateClient` if the HTTP Client could not be created.
/// - `CreateError::InvalidApiKey` if the API key contains invalid header value characters.
/// - `CreateError::ApiKeyNotFound` if the `OPENAI_API_KEY` environment variable is not set or contains an equal sign or NUL (`'='` or `'\0'`).
pub fn from_env() -> Result<Self, CreateError> {
let api_key = env::var("OPENAI_API_KEY").map_err(|_| CreateError::ApiKeyNotFound)?;
Self::new(&api_key)
}
/// Creates a model response.
/// Provide [text](https://platform.openai.com/docs/guides/text) or [image](https://platform.openai.com/docs/guides/images) inputs to generate [text](https://platform.openai.com/docs/guides/text) or [JSON](https://platform.openai.com/docs/guides/structured-outputs) outputs.
/// Have the model call your own [custom code](https://platform.openai.com/docs/guides/function-calling) or use built-in [tools](https://platform.openai.com/docs/guides/tools) like [web search](https://platform.openai.com/docs/guides/tools-web-search) or [file search](https://platform.openai.com/docs/guides/tools-file-search) to use your own data as input for the model's response.
/// To receive a stream of tokens as they are generated, use the `stream` function instead.
///
/// ## Errors
///
/// Errors if the request fails to send or has a non-200 status code (except for 400, which will return an OpenAI error instead).
pub async fn create(
&self,
mut request: Request,
) -> Result<Result<Response, Error>, reqwest::Error> {
// Use the `stream` function to stream the response.
request.stream = Some(false);
let mut response = self
.client
.post("https://api.openai.com/v1/responses")
.json(&request)
.send()
.await?;
if response.status() != StatusCode::BAD_REQUEST {
response = response.error_for_status()?;
}
response.json::<ResponseResult>().await.map(Into::into)
}
/// Retrieves a model response with the given ID.
///
/// ## Errors
///
/// Errors if the request fails to send or has a non-200 status code (except for 400, which will return an OpenAI error instead).
pub async fn get(
&self,
response_id: &str,
include: Option<Include>,
) -> Result<Result<Response, Error>, reqwest::Error> {
let mut response = self
.client
.get(format!("https://api.openai.com/v1/responses/{response_id}"))
.query(&json!({ "include": include }))
.send()
.await?;
if response.status() != StatusCode::BAD_REQUEST {
response = response.error_for_status()?;
}
response.json::<ResponseResult>().await.map(Into::into)
}
/// Deletes a model response with the given ID.
///
/// ## Errors
///
/// Errors if the request fails to send or has a non-200 status code.
pub async fn delete(&self, response_id: &str) -> Result<(), reqwest::Error> {
self.client
.delete(format!("https://api.openai.com/v1/responses/{response_id}"))
.send()
.await?
.error_for_status()?;
Ok(())
}
/// Returns a list of input items for a given response.
///
/// ## Errors
///
/// Errors if the request fails to send or has a non-200 status code.
pub async fn list_inputs(&self, response_id: &str) -> Result<InputItemList, reqwest::Error> {
self.client
.get(format!(
"https://api.openai.com/v1/responses/{response_id}/inputs"
))
.send()
.await?
.error_for_status()?
.json()
.await
}
}