Struct Credentials

Source
pub struct Credentials { /* private fields */ }
Expand description

Holds the API key and base URL for an Anthropic-compatible API.

This struct is used to authenticate requests to the Anthropic API. It can be created from environment variables or explicitly with an API key and base URL.

Implementations§

Source§

impl Credentials

Source

pub fn new(api_key: impl Into<String>, base_url: impl Into<String>) -> Self

Creates credentials with the given API key and base URL.

If the base URL is empty, it will use the default Anthropic API URL.

§Examples
use anthropic_api::Credentials;

let credentials = Credentials::new("your-api-key", "");
Source

pub fn from_env() -> Credentials

Fetches the credentials from the environment variables ANTHROPIC_API_KEY and ANTHROPIC_BASE_URL.

§Panics

This function will panic if the ANTHROPIC_API_KEY variable is missing from the environment. If only the ANTHROPIC_BASE_URL variable is missing, it will use the default URL.

§Examples
use anthropic_api::Credentials;

// Assumes ANTHROPIC_API_KEY is set in the environment
let credentials = Credentials::from_env();
Examples found in repository?
examples/models.rs (line 6)
4async fn main() -> Result<(), Box<dyn std::error::Error>> {
5    // Load credentials from environment variables
6    let credentials = Credentials::from_env();
7
8    // List all available models
9    println!("Listing all available models:");
10    let models = ModelList::builder()
11        .credentials(credentials.clone())
12        // Add the limit to the request if desired
13        // .limit(5u32)
14        .create()
15        .await?;
16
17    println!("Available models:");
18    for model in &models.data {
19        println!("- {} ({})", model.display_name, model.id);
20    }
21
22    // Get details for a specific model
23    if let Some(first_model) = models.data.first() {
24        println!("\nGetting details for model: {}", first_model.id);
25        let model_details = Model::builder(&first_model.id)
26            .credentials(credentials)
27            .create()
28            .await?;
29
30        println!("Model details:");
31        println!("  ID: {}", model_details.id);
32        println!("  Name: {}", model_details.display_name);
33        println!("  Created at: {}", model_details.created_at);
34        println!("  Type: {}", model_details.model_type);
35    }
36
37    Ok(())
38}
More examples
Hide additional examples
examples/tool_use.rs (line 28)
27async fn main() {
28    let credentials = Credentials::from_env();
29
30    // Define a calculator tool
31    let calculator_tool = Tool {
32        name: "calculator".to_string(),
33        description: "A calculator that can perform basic arithmetic operations".to_string(),
34        input_schema: json!({
35            "type": "object",
36            "properties": {
37                "operation": {
38                    "type": "string",
39                    "enum": ["add", "subtract", "multiply", "divide"]
40                },
41                "operands": {
42                    "type": "array",
43                    "items": {"type": "number"},
44                    "minItems": 2,
45                    "maxItems": 2
46                }
47            },
48            "required": ["operation", "operands"]
49        }),
50    };
51
52    let content =
53        "You are a helpful AI assistant. Please calculate 15 + 27 using the calculator tool.";
54    let mut messages = vec![Message {
55        role: MessageRole::User,
56        content: MessageContent::Text(content.to_string()),
57    }];
58
59    println!("Claude: {}", content);
60
61    // Create message request with tool
62    let response = MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
63        .credentials(credentials.clone())
64        .tools(vec![calculator_tool.clone()])
65        .tool_choice(ToolChoice::Any)
66        .create()
67        .await
68        .unwrap();
69
70    // Print assistant's response and tool usage
71    for content in response.content {
72        match content {
73            ResponseContentBlock::Text { text } => {
74                println!("Assistant: {}", text.trim());
75                messages.push(Message {
76                    role: MessageRole::Assistant,
77                    content: MessageContent::Text(text),
78                });
79            }
80            ResponseContentBlock::ToolUse { name, input, .. } => {
81                println!("Claude decided to use the tool: {}: {}", name, input);
82            }
83            ResponseContentBlock::Thinking {
84                signature,
85                thinking,
86            } => {
87                println!("Claude {} is thinking: {}", signature, thinking);
88            }
89            ResponseContentBlock::RedactedThinking { data } => {
90                println!("Claude is thinking: {}", data);
91            }
92        }
93    }
94}
examples/message_cli.rs (line 28)
26async fn main() {
27    // Load .env file containing ANTHROPIC_API_KEY
28    let credentials = Credentials::from_env();
29
30    let mut messages = vec![Message {
31        role: MessageRole::User,
32        content: MessageContent::Text(
33            "You are a helpful AI assistant. Please introduce yourself briefly.".to_string(),
34        ),
35    }];
36
37    // Create initial message request
38    let response = MessagesBuilder::builder("claude-3-7-sonnet-20250219", messages.clone(), 2048)
39        .credentials(credentials.clone())
40        // Uncomment this to enable thinking
41        // .thinking(Thinking {
42        //     thinking_type: ThinkingType::Enabled,
43        //     budget_tokens: 1024,
44        // })
45        .create()
46        .await
47        .unwrap();
48
49    // Print assistant's response
50    if let Some(content) = response.content.first() {
51        match content {
52            ResponseContentBlock::Text { text } => {
53                println!("Assistant: {}", text.trim());
54                messages.push(Message {
55                    role: MessageRole::Assistant,
56                    content: MessageContent::Text(text.clone()),
57                });
58            }
59            _ => {}
60        }
61    }
62
63    // Start conversation loop
64    loop {
65        print!("User: ");
66        stdout().flush().unwrap();
67
68        let mut user_input = String::new();
69        stdin().read_line(&mut user_input).unwrap();
70
71        // Add user message
72        messages.push(Message {
73            role: MessageRole::User,
74            content: MessageContent::Text(user_input),
75        });
76
77        // Send message request
78        let response =
79            MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
80                .credentials(credentials.clone())
81                .create()
82                .await
83                .unwrap();
84
85        // Print assistant's response
86        if let Some(content) = response.content.first() {
87            match content {
88                ResponseContentBlock::Text { text } => {
89                    println!("Assistant: {}", text.trim());
90                    messages.push(Message {
91                        role: MessageRole::Assistant,
92                        content: MessageContent::Text(text.clone()),
93                    });
94                }
95                _ => {}
96            }
97        }
98    }
99}
examples/streaming.rs (line 29)
28async fn main() {
29    let credentials = Credentials::from_env();
30
31    let mut messages = vec![Message {
32        role: MessageRole::User,
33        content: MessageContent::Text(
34            "You are a helpful AI assistant. Please introduce yourself briefly.".to_string(),
35        ),
36    }];
37
38    // Create initial message request with streaming
39    let mut stream =
40        MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
41            .credentials(credentials.clone())
42            .create_stream()
43            .await
44            .unwrap();
45
46    // Print assistant's streaming response
47    print!("Assistant: ");
48    stdout().flush().unwrap();
49    while let Some(event) = stream.recv().await {
50        match event {
51            StreamEvent::ContentBlockDelta { delta, .. } => {
52                if let ContentBlockDelta::Text { text } = delta {
53                    print!("{}", text);
54                    stdout().flush().unwrap();
55                }
56            }
57            StreamEvent::MessageStop => {
58                println!();
59            }
60            _ => {}
61        }
62    }
63
64    // Start conversation loop
65    loop {
66        print!("\nUser: ");
67        stdout().flush().unwrap();
68
69        let mut user_input = String::new();
70        stdin().read_line(&mut user_input).unwrap();
71
72        // Add user message
73        messages.push(Message {
74            role: MessageRole::User,
75            content: MessageContent::Text(user_input),
76        });
77
78        // Send message request with streaming
79        let mut stream =
80            MessagesResponse::builder("claude-3-7-sonnet-20250219", messages.clone(), 1024)
81                .credentials(credentials.clone())
82                .create_stream()
83                .await
84                .unwrap();
85
86        // Print assistant's streaming response and store the text
87        print!("\nAssistant: ");
88        stdout().flush().unwrap();
89        let mut full_response = String::new();
90        while let Some(event) = stream.recv().await {
91            match event {
92                StreamEvent::ContentBlockDelta { delta, .. } => {
93                    if let ContentBlockDelta::Text { text } = delta {
94                        print!("{}", text);
95                        stdout().flush().unwrap();
96                        full_response.push_str(&text);
97                    }
98                }
99                StreamEvent::MessageStop => {
100                    println!();
101                }
102                _ => {}
103            }
104        }
105
106        // Add assistant's complete response to messages
107        messages.push(Message {
108            role: MessageRole::Assistant,
109            content: MessageContent::Text(full_response),
110        });
111    }
112}
Source

pub fn api_key(&self) -> &str

Returns the API key

Source

pub fn base_url(&self) -> &str

Returns the base URL

Trait Implementations§

Source§

impl Clone for Credentials

Source§

fn clone(&self) -> Credentials

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Credentials

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl PartialEq for Credentials

Source§

fn eq(&self, other: &Credentials) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl Eq for Credentials

Source§

impl StructuralPartialEq for Credentials

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

impl<T> ErasedDestructor for T
where T: 'static,