Skip to main content

xil_api/
anthropic.rs

1//! Anthropic Messages API, as `anthropic.Anthropic().messages.create` calls it.
2
3use serde_json::Value;
4
5use crate::{agent, base_url, call_logged, read_json, send_json, ApiError};
6
7pub const DEFAULT_BASE_URL: &str = "https://api.anthropic.com";
8const API_VERSION: &str = "2023-06-01";
9
10pub struct Client {
11    api_key: String,
12    base: String,
13}
14
15impl Client {
16    pub fn new(api_key: &str) -> Client {
17        Client {
18            api_key: api_key.to_string(),
19            base: base_url("ANTHROPIC_BASE_URL", DEFAULT_BASE_URL),
20        }
21    }
22
23    /// `client.messages.create(**body)`, returning the response JSON.
24    pub fn messages_create(&self, body: &Value) -> Result<Value, ApiError> {
25        let req = agent()
26            .post(&format!("{}/v1/messages", self.base))
27            .set("x-api-key", &self.api_key)
28            .set("anthropic-version", API_VERSION);
29        read_json(call_logged("POST", send_json(req, body))?)
30    }
31}