rig/providers/anthropic/
client.rs1use super::completion::{ANTHROPIC_VERSION_LATEST, CompletionModel};
3use crate::client::{
4 ClientBuilderError, CompletionClient, ProviderClient, ProviderValue, VerifyClient, VerifyError,
5 impl_conversion_traits,
6};
7
8const ANTHROPIC_API_BASE_URL: &str = "https://api.anthropic.com";
12
13pub struct ClientBuilder<'a> {
14 api_key: &'a str,
15 base_url: &'a str,
16 anthropic_version: &'a str,
17 anthropic_betas: Option<Vec<&'a str>>,
18 http_client: Option<reqwest::Client>,
19}
20
21impl<'a> ClientBuilder<'a> {
34 pub fn new(api_key: &'a str) -> Self {
35 Self {
36 api_key,
37 base_url: ANTHROPIC_API_BASE_URL,
38 anthropic_version: ANTHROPIC_VERSION_LATEST,
39 anthropic_betas: None,
40 http_client: None,
41 }
42 }
43
44 pub fn base_url(mut self, base_url: &'a str) -> Self {
45 self.base_url = base_url;
46 self
47 }
48
49 pub fn anthropic_version(mut self, anthropic_version: &'a str) -> Self {
50 self.anthropic_version = anthropic_version;
51 self
52 }
53
54 pub fn anthropic_beta(mut self, anthropic_beta: &'a str) -> Self {
55 if let Some(mut betas) = self.anthropic_betas {
56 betas.push(anthropic_beta);
57 self.anthropic_betas = Some(betas);
58 } else {
59 self.anthropic_betas = Some(vec![anthropic_beta]);
60 }
61 self
62 }
63
64 pub fn custom_client(mut self, client: reqwest::Client) -> Self {
65 self.http_client = Some(client);
66 self
67 }
68
69 pub fn build(self) -> Result<Client, ClientBuilderError> {
70 let mut default_headers = reqwest::header::HeaderMap::new();
71 default_headers.insert(
72 "anthropic-version",
73 self.anthropic_version
74 .parse()
75 .map_err(|_| ClientBuilderError::InvalidProperty("anthropic-version"))?,
76 );
77 if let Some(betas) = self.anthropic_betas {
78 default_headers.insert(
79 "anthropic-beta",
80 betas
81 .join(",")
82 .parse()
83 .map_err(|_| ClientBuilderError::InvalidProperty("anthropic-beta"))?,
84 );
85 };
86
87 let http_client = if let Some(http_client) = self.http_client {
88 http_client
89 } else {
90 reqwest::Client::builder().build()?
91 };
92
93 Ok(Client {
94 base_url: self.base_url.to_string(),
95 api_key: self.api_key.to_string(),
96 default_headers,
97 http_client,
98 })
99 }
100}
101
102#[derive(Clone)]
103pub struct Client {
104 base_url: String,
106 api_key: String,
108 http_client: reqwest::Client,
110 default_headers: reqwest::header::HeaderMap,
112}
113
114impl std::fmt::Debug for Client {
115 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116 f.debug_struct("Client")
117 .field("base_url", &self.base_url)
118 .field("http_client", &self.http_client)
119 .field("api_key", &"<REDACTED>")
120 .field("default_headers", &self.default_headers)
121 .finish()
122 }
123}
124
125impl Client {
126 pub fn builder(api_key: &str) -> ClientBuilder<'_> {
139 ClientBuilder::new(api_key)
140 }
141
142 pub fn new(api_key: &str) -> Self {
148 Self::builder(api_key)
149 .build()
150 .expect("Anthropic client should build")
151 }
152
153 pub(crate) fn post(&self, path: &str) -> reqwest::RequestBuilder {
154 let url = format!("{}/{}", self.base_url, path).replace("//", "/");
155 self.http_client
156 .post(url)
157 .header("X-Api-Key", &self.api_key)
158 .headers(self.default_headers.clone())
159 }
160
161 pub(crate) fn get(&self, path: &str) -> reqwest::RequestBuilder {
162 let url = format!("{}/{}", self.base_url, path).replace("//", "/");
163 self.http_client
164 .get(url)
165 .header("X-Api-Key", &self.api_key)
166 .headers(self.default_headers.clone())
167 }
168}
169
170impl ProviderClient for Client {
171 fn from_env() -> Self {
174 let api_key = std::env::var("ANTHROPIC_API_KEY").expect("ANTHROPIC_API_KEY not set");
175 Client::new(&api_key)
176 }
177
178 fn from_val(input: crate::client::ProviderValue) -> Self {
179 let ProviderValue::Simple(api_key) = input else {
180 panic!("Incorrect provider value type")
181 };
182 Client::new(&api_key)
183 }
184}
185
186impl CompletionClient for Client {
187 type CompletionModel = CompletionModel;
188 fn completion_model(&self, model: &str) -> CompletionModel {
189 CompletionModel::new(self.clone(), model)
190 }
191}
192
193impl VerifyClient for Client {
194 #[cfg_attr(feature = "worker", worker::send)]
195 async fn verify(&self) -> Result<(), VerifyError> {
196 let response = self.get("/v1/models").send().await?;
197 match response.status() {
198 reqwest::StatusCode::OK => Ok(()),
199 reqwest::StatusCode::UNAUTHORIZED | reqwest::StatusCode::FORBIDDEN => {
200 Err(VerifyError::InvalidAuthentication)
201 }
202 reqwest::StatusCode::INTERNAL_SERVER_ERROR => {
203 Err(VerifyError::ProviderError(response.text().await?))
204 }
205 status if status.as_u16() == 529 => {
206 Err(VerifyError::ProviderError(response.text().await?))
207 }
208 _ => {
209 response.error_for_status()?;
210 Ok(())
211 }
212 }
213 }
214}
215
216impl_conversion_traits!(
217 AsTranscription,
218 AsEmbeddings,
219 AsImageGeneration,
220 AsAudioGeneration for Client
221);