Request

Struct Request 

Source
pub struct Request { /* private fields */ }

Implementations§

Source§

impl Request

Source

pub async fn execute<F, Fut>(self, callback: F) -> Result<()>
where F: FnMut(String) -> Fut, Fut: Future<Output = ()> + Send,

Examples found in repository?
examples/basic_usage.rs (line 25)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9    dotenv().ok();
10    let secret_key = std::env::var("ANTHROPIC_API_KEY").unwrap_or_default();
11
12    let request = Client::new()
13        .version("2023-06-01")
14        // Set verbose to true if you need return the response as it is from Anthropic
15        // .verbose(true) 
16        .auth(secret_key.as_str())
17        .model("claude-3-opus-20240229")
18        .messages(&json!([
19            {"role": "user", "content": "Write me a poem about bravery"}
20        ]))
21        .max_tokens(1024)
22        .build()?;
23
24    if let Err(error) = request
25        .execute(|text| async move { println!("{text}") })
26        .await
27    {
28        eprintln!("Error: {error}");
29    }
30
31    Ok(())
32}
More examples
Hide additional examples
examples/tool_use_usage.rs (line 43)
8async fn main() -> Result<(), Box<dyn std::error::Error>> {
9    dotenv().ok();
10    let secret_key = std::env::var("ANTHROPIC_API_KEY").unwrap_or_default();
11
12    let request = Client::new()
13        .auth(secret_key.as_str())
14        .model("claude-3-opus-20240229")
15        .beta("tools-2024-04-04") // add the beta header
16        .tools(&json!([
17          {
18            "name": "get_weather",
19            "description": "Get the current weather in a given location",
20            "input_schema": {
21              "type": "object",
22              "properties": {
23                "location": {
24                  "type": "string",
25                  "description": "The city and state, e.g. San Francisco, CA"
26                }
27              },
28              "required": ["location"]
29            }
30          }
31        ]))
32        .tool_choice(ToolChoice::Auto)
33        .messages(&json!([
34          {
35            "role": "user",
36            "content": "What is the weather like in San Francisco?"
37          }
38        ]))
39        .max_tokens(1024)
40        .build()?;
41
42    if let Err(error) = request
43        .execute(|text| async move { println!("{text}") })
44        .await
45    {
46        eprintln!("Error: {error}");
47    }
48
49    Ok(())
50}
examples/streaming_usage.rs (lines 30-43)
9async fn main() -> Result<(), Box<dyn std::error::Error>> {
10    dotenv().ok();
11    let secret_key = std::env::var("ANTHROPIC_API_KEY").unwrap_or_default();
12
13    let request = Client::new()
14        .auth(secret_key.as_str())
15        .model("claude-3-opus-20240229")
16        .messages(&json!([
17            {"role": "user", "content": "Write me a poem about bravery"}
18        ]))
19        .system("Make it sound like Edgar Allan Poe")
20        .temperature(0.1)
21        .max_tokens(1024)
22        .stream(true)
23        .build()?;
24
25    let message = Arc::new(Mutex::new(String::new()));
26    let message_clone = message.clone();
27
28    // NOTE: you should spawn a new thread if you need to
29    if let Err(error) = request
30        .execute(move |text| {
31            let message_clone = message_clone.clone();
32            async move {
33                println!("{text}");
34
35                {
36                    let mut message = message_clone.lock().unwrap();
37                    *message = format!("{}{}", *message, text);
38                    drop(message);
39                }
40                // Mimic async process
41                // tokio::time::sleep(tokio::time::Duration::from_millis(200)).await;
42            }
43        })
44        .await
45    {
46        eprintln!("Error: {error}");
47    }
48
49    let final_message = message.lock().unwrap();
50    println!("Message: {}", *final_message); // or get the whole message at the end
51
52    Ok(())
53}

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> 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, 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