### Agent Builder Source: https://docs.rs/aquaregia/latest/aquaregia/agent/struct.Agent.html Demonstrates how to start building an Agent using the `builder` function. ```APIDOC ## impl Agent

### pub fn builder( client: impl Into>>, model: impl IntoModelRef

, ) -> AgentBuilder

Starts building an `Agent` from a provider-bound client and model. ``` -------------------------------- ### SSE Format Example Source: https://docs.rs/aquaregia/latest/aquaregia/stream/index.html Example of the text-based Server-Sent Events format used by the parser. ```text event: message_type data: {"json": "payload"} data: [DONE] ``` -------------------------------- ### Quick Start: OpenAI Compatible Client Source: https://docs.rs/aquaregia/latest/aquaregia/index.html Demonstrates how to initialize an `LlmClient` for an OpenAI-compatible endpoint and generate text. Ensure the `DEEPSEEK_API_KEY` environment variable is set. ```rust use aquaregia::{GenerateTextRequest, LlmClient}; #[tokio::main] async fn main() -> Result<(), Box> { let client = LlmClient::openai_compatible("https://api.deepseek.com") .api_key(std::env::var("DEEPSEEK_API_KEY")?) .build()?; let out = client .generate(GenerateTextRequest::from_user_prompt( "deepseek-chat", "Explain Rust ownership in 3 bullet points.", )) .await?; println!("{}", out.output_text); Ok(()) } ``` -------------------------------- ### Agent Builder Initialization Source: https://docs.rs/aquaregia/latest/aquaregia/agent/struct.Agent.html Starts the process of building an Agent. Requires a provider-bound client and a model reference. ```rust pub fn builder( client: impl Into>>, model: impl IntoModelRef

, ) -> AgentBuilder

``` -------------------------------- ### Generate Text with OpenAI Adapter Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/openai/index.html Example of initializing the OpenAI client and generating text using a user prompt. Ensure you have the 'api-key' for authentication. The `build()` method returns a Result, so error handling is necessary. ```rust use aquaregia::{LlmClient, GenerateTextRequest}; let client = LlmClient::openai("api-key").build()?; let response = client .generate(GenerateTextRequest::from_user_prompt("gpt-4o", "Hello!")) .await?; println!("{}", response.output_text); ``` -------------------------------- ### Example Usage Source: https://docs.rs/aquaregia/latest/aquaregia/struct.CancellationToken.html Demonstrates how to use CancellationToken to coordinate between tasks, allowing one task to signal cancellation to another. ```APIDOC ## Examples ### Basic Cancellation ```rust use tokio::select; use tokio_util::sync::CancellationToken; #[tokio::main] async fn main() { let token = CancellationToken::new(); let cloned_token = token.clone(); let join_handle = tokio::spawn(async move { // Wait for either cancellation or a very long time select! { _ = cloned_token.cancelled() => { // The token was cancelled 5 } _ = tokio::time::sleep(std::time::Duration::from_secs(9999)) => { 99 } } }); tokio::spawn(async move { tokio::time::sleep(std::time::Duration::from_millis(10)).await; token.cancel(); }); assert_eq!(5, join_handle.await.unwrap()); } ``` ``` -------------------------------- ### Anthropic Adapter Usage Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/anthropic/index.html Example demonstrating how to initialize and use the Anthropic adapter for text generation. ```APIDOC ## POST /api/generate_text ### Description Generates text using the Anthropic API via the Aquaregia adapter. ### Method POST ### Endpoint /api/generate_text ### Parameters #### Query Parameters - **model** (string) - Required - The name of the Anthropic model to use (e.g., "claude-sonnet-4-5"). #### Request Body - **prompt** (string) - Required - The user's prompt for text generation. ### Request Example ```rust use aquaregia::{LlmClient, GenerateTextRequest}; let client = LlmClient::anthropic("api-key").build()?; let response = client .generate(GenerateTextRequest::from_user_prompt("claude-sonnet-4-5", "Hello!")) .await?; println!("{}", response.output_text); ``` ### Response #### Success Response (200) - **output_text** (string) - The generated text output from the Anthropic model. #### Response Example ```json { "output_text": "This is the generated text." } ``` ``` -------------------------------- ### Struct AgentStepStart Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.AgentStepStart.html Represents the start of an agent step, including the step index and messages. ```APIDOC ## Struct AgentStepStart ### Description Emitted when an agent step begins. ### Fields - **step** (u8) - 1-based step index. - **messages** (Vec) - Messages sent to the model for this step. ### Example ```rust { "step": 1, "messages": [ { "role": "user", "content": "Hello!" } ] } ``` ``` -------------------------------- ### Adjusting AgentRunPlan via prepare_call Source: https://docs.rs/aquaregia/latest/aquaregia/agent/struct.AgentRunPlan.html Example of using the prepare_call callback to dynamically modify the AgentRunPlan, such as setting the temperature before execution. ```rust let client = LlmClient::openai("key").build()?; let agent = Agent::builder(client, "gpt-4o") .prepare_call(|plan| { // Dynamically adjust temperature based on task plan.temperature = Some(0.7); }) .build()?; ``` -------------------------------- ### AgentStart Struct Definition Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.AgentStart.html Defines the structure for agent start information, including model ID, messages, tool count, and max steps. This is emitted once before the first agent step. ```rust pub struct AgentStart { pub model_id: String, pub messages: Vec, pub tool_count: usize, pub max_steps: u8, } ``` -------------------------------- ### Initialize a tool descriptor with aquaregia::tool Source: https://docs.rs/aquaregia/latest/aquaregia/tool/fn.tool.html Use this function to start the builder pattern for defining a tool. It accepts any type that implements Into for the tool name. ```rust pub fn tool(name: impl Into) -> ToolBuilder ``` -------------------------------- ### Build and Run an Agent with Tools Source: https://docs.rs/aquaregia/latest/aquaregia/agent/index.html Demonstrates how to build an agent with a specific LLM client, define custom tools, and run the agent with a prompt. Ensure the LLM client is correctly initialized and the tools are properly defined with descriptions. ```rust use aquaregia::{Agent, LlmClient, tool}; use serde_json::{Value, json}; #[tool(description = "Get weather by city")] async fn get_weather(city: String) -> Result { Ok(json!({ "city": city, "temp_c": 23, "condition": "sunny" })) } let client = LlmClient::openai("api-key").build()?; let agent = Agent::builder(client, "gpt-4o") .instructions("You can call tools before answering.") .tools([get_weather]) .max_steps(4) .build()?; let out = agent.run("What is the weather in Shanghai?").await?; println!("{}", out.output_text); ``` -------------------------------- ### Pin::as_mut Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextStream.html Gets a mutable reference to the pinned value. ```APIDOC ## GET /pin/as_mut ### Description Gets a mutable reference to the pinned value this `Pin` points to. This is a generic method to go from `&mut Pin>` to `Pin<&mut T>`. It is safe because, as part of the contract of `Pin::new_unchecked`, the pointee cannot move after `Pin>` got created. “Malicious” implementations of `Pointer::DerefMut` are likewise ruled out by the contract of `Pin::new_unchecked`. This method is useful when doing multiple calls to functions that consume the pinning pointer. ### Method GET ### Endpoint `/pin/as_mut` ### Parameters #### Query Parameters - **ptr** (Pin) - Required - The mutable pinned pointer to get a mutable reference from. ### Request Example ```rust use std::pin::Pin; // Assuming 'Type' is a struct with a method that takes Pin<&mut Self> // impl Type { // fn method(self: Pin<&mut Self>) { // // do something // } // } // let mut instance: Type = ...; // let mut pinned_instance: Pin<&mut Type> = Pin::new(&mut instance); // pinned_instance.as_mut().method(); // pinned_instance.as_mut().method(); ``` ### Response #### Success Response (200) - **Pin<&mut T>** (Pin) - A mutable reference to the pinned value. ``` -------------------------------- ### Pin::as_ref Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextStream.html Gets a shared reference to the pinned value. ```APIDOC ## GET /pin/as_ref ### Description Gets a shared reference to the pinned value this `Pin` points to. This is a generic method to go from `&Pin>` to `Pin<&T>`. It is safe because, as part of the contract of `Pin::new_unchecked`, the pointee cannot move after `Pin>` got created. “Malicious” implementations of `Pointer::Deref` are likewise ruled out by the contract of `Pin::new_unchecked`. ### Method GET ### Endpoint `/pin/as_ref` ### Parameters #### Query Parameters - **ptr** (Pin) - Required - The pinned pointer to get a shared reference from. ### Response #### Success Response (200) - **Pin<&T>** (Pin) - A shared reference to the pinned value. ``` -------------------------------- ### OpenAI-Compatible Adapter Initialization and Usage Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/openai_compatible/index.html Demonstrates how to initialize the LlmClient with an OpenAI-compatible endpoint and make a text generation request. ```APIDOC ## POST /v1/chat/completions (Example Endpoint) ### Description This example demonstrates initializing the `LlmClient` for an OpenAI-compatible endpoint and performing a text generation task. ### Method POST (Implied by `generate` method) ### Endpoint (Not explicitly defined, but typically `/v1/chat/completions` for OpenAI-compatible APIs) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body (Implicitly handled by `GenerateTextRequest`) - **model** (string) - Required - The model to use for generation (e.g., "deepseek-chat"). - **messages** (array) - Required - The conversation history. - **role** (string) - Required - The role of the message sender (e.g., "user", "system", "assistant"). - **content** (string) - Required - The content of the message. ### Request Example ```rust use aquaregia::{LlmClient, GenerateTextRequest}; let client = LlmClient::openai_compatible("https://api.deepseek.com") .api_key("api-key") .build()?; let response = client .generate(GenerateTextRequest::from_user_prompt("deepseek-chat", "Hello!")) .await?; println!("{}", response.output_text); ``` ### Response #### Success Response (200) - **output_text** (string) - The generated text output from the model. #### Response Example ```json { "output_text": "Hello there! How can I help you today?" } ``` ``` -------------------------------- ### Get Message Role Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.Message.html Returns the role of the message sender. ```rust pub fn role(&self) -> MessageRole ``` -------------------------------- ### Create New OpenAiCompatibleAdapterSettings Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/openai_compatible/struct.OpenAiCompatibleAdapterSettings.html Initializes OpenAiCompatibleAdapterSettings with a base URL. Uses default path and no API key. ```rust pub fn new(base_url: impl Into) -> Self ``` -------------------------------- ### Get Message Name Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.Message.html Returns the optional name attached to the message. ```rust pub fn name(&self) -> Option<&str> ``` -------------------------------- ### Get Provider Kind Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.ModelRef.html Returns the provider family marker for the model reference. ```rust pub fn provider_kind(&self) -> ProviderKind ``` -------------------------------- ### Initialize and use an OpenAI-compatible LLM client Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/openai_compatible/index.html Demonstrates how to configure an LlmClient with an OpenAI-compatible endpoint and perform a text generation request. ```rust use aquaregia::{LlmClient, GenerateTextRequest}; let client = LlmClient::openai_compatible("https://api.deepseek.com") .api_key("api-key") .build()?; let response = client .generate(GenerateTextRequest::from_user_prompt("deepseek-chat", "Hello!")) .await?; println!("{}", response.output_text); ``` -------------------------------- ### Get Message Parts Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.Message.html Returns a slice of the message's content parts. ```rust pub fn parts(&self) -> &[ContentPart] ``` -------------------------------- ### Initialize Anthropic Client and Generate Text Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/anthropic/index.html Demonstrates how to initialize the LlmClient for the Anthropic provider and generate text using a user prompt. Ensure you have the necessary API key and dependencies. ```rust use aquaregia::{LlmClient, GenerateTextRequest}; let client = LlmClient::anthropic("api-key").build()?; let response = client .generate(GenerateTextRequest::from_user_prompt("claude-sonnet-4-5", "Hello!")) .await?; println!("{}", response.output_text); ``` -------------------------------- ### Client Initialization Source: https://docs.rs/aquaregia/latest/aquaregia/client/index.html Configuring and building a provider-bound client using the builder pattern. ```APIDOC ## Client Initialization ### Description Initializes a client using LlmClient, configures runtime behavior via ClientBuilder, and produces a BoundClient. ### Parameters #### Configuration - **timeout** (Duration) - Optional - Sets the HTTP request timeout. - **max_retries** (u32) - Optional - Sets the maximum number of retry attempts for failed requests. ### Request Example let client = LlmClient::openai("api-key") .timeout(std::time::Duration::from_secs(60)) .max_retries(3) .build()?; ``` -------------------------------- ### Pin::as_deref_mut Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextStream.html Gets `Pin<&mut T>` to the underlying pinned value from a nested `Pin`-pointer. ```APIDOC ## GET /pin/as_deref_mut ### Description Gets `Pin<&mut T>` to the underlying pinned value from this nested `Pin`-pointer. This is a generic method to go from `Pin<&mut Pin>>` to `Pin<&mut T>`. It is safe because the existence of a `Pin>` ensures that the pointee, `T`, cannot move in the future, and this method does not enable the pointee to move. “Malicious” implementations of `Ptr::DerefMut` are likewise ruled out by the contract of `Pin::new_unchecked`. ### Method GET ### Endpoint `/pin/as_deref_mut` ### Parameters #### Query Parameters - **nested_pin** (Pin<&mut Pin>) - Required - The nested pinned pointer. ### Response #### Success Response (200) - **Pin<&mut T>** (Pin) - A mutable reference to the underlying pinned value. ``` -------------------------------- ### OpenAiAdapter Constructor Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/openai/struct.OpenAiAdapter.html This snippet shows how to create an instance of the OpenAiAdapter using provided settings and an HTTP client. ```APIDOC ## POST /api/openai/adapter ### Description Creates an adapter from validated settings and shared HTTP client. ### Method POST ### Endpoint /api/openai/adapter ### Parameters #### Request Body - **settings** (OpenAiAdapterSettings) - Required - The settings for the OpenAI adapter. - **http** (Arc) - Required - A shared HTTP client instance. ### Request Example ```json { "settings": { "api_key": "YOUR_API_KEY", "model": "gpt-3.5-turbo" }, "http": " representation>" } ``` ### Response #### Success Response (200) - **OpenAiAdapter** (OpenAiAdapter) - The newly created OpenAI adapter instance. #### Response Example ```json { "adapter": "" } ``` ``` -------------------------------- ### Get Provider Slug Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.ModelRef.html Returns the static string slice representing the provider's slug. ```rust pub fn provider_slug(&self) -> &'static str ``` -------------------------------- ### Create OpenAiAdapter from Settings Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/openai/struct.OpenAiAdapter.html Constructs an OpenAiAdapter instance using provided settings and an HTTP client. Ensure settings are validated before use. ```rust pub fn from_settings(settings: OpenAiAdapterSettings, http: Arc) -> Self> ``` -------------------------------- ### Get Agent Model ID Source: https://docs.rs/aquaregia/latest/aquaregia/agent/struct.Agent.html Retrieves the fully qualified model identifier, formatted as '/'. ```rust pub fn model_id(&self) -> String ``` -------------------------------- ### Initialize LLM Clients with Aquaregia Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/index.html Demonstrates how to instantiate various LLM provider clients using the LlmClient builder pattern. ```rust use aquaregia::LlmClient; // OpenAI adapter let openai_client = LlmClient::openai("api-key").build()?; // Anthropic adapter let anthropic_client = LlmClient::anthropic("api-key").build()?; // Google adapter let google_client = LlmClient::google("api-key").build()?; // OpenAI-compatible adapter (e.g., DeepSeek, local LLMs) let compatible_client = LlmClient::openai_compatible("https://api.example.com") .api_key("api-key") .build()?; ``` -------------------------------- ### Get Type ID Source: https://docs.rs/aquaregia/latest/aquaregia/client/struct.BoundClient.html Retrieves the unique TypeId of the current type. Useful for runtime type identification. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### Initialize and Use Aquaregia Client Source: https://docs.rs/aquaregia/latest/aquaregia/client/index.html Demonstrates the builder pattern to configure an OpenAI client with timeouts and retries, followed by a text generation request. ```rust use aquaregia::{GenerateTextRequest, LlmClient}; // Create and build client let client = LlmClient::openai("api-key") .timeout(std::time::Duration::from_secs(60)) .max_retries(3) .build()?; // Use client for generation let response = client .generate(GenerateTextRequest::from_user_prompt("gpt-4o", "Hello!")) .await?; println!("{}", response.output_text); ``` -------------------------------- ### Create Google Client Builder Source: https://docs.rs/aquaregia/latest/aquaregia/client/struct.LlmClient.html Use this function to create a builder for a Google client. Requires an API key. ```rust pub fn google(api_key: impl Into) -> ClientBuilder ``` -------------------------------- ### Generate text with GoogleAdapter Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/google/index.html Initializes the Google client and performs a text generation request using the Gemini 2.0 Flash model. ```rust use aquaregia::{LlmClient, GenerateTextRequest}; let client = LlmClient::google("api-key").build()?; let response = client .generate(GenerateTextRequest::from_user_prompt("gemini-2.0-flash", "Hello!")) .await?; println!("{}", response.output_text); ``` -------------------------------- ### Get Canonical Provider Slug Source: https://docs.rs/aquaregia/latest/aquaregia/types/enum.ProviderKind.html Returns the normalized string identifier for the provider, suitable for use in URLs, logging, or configuration. ```rust pub fn as_slug(&self) -> &'static str ``` -------------------------------- ### Create OpenAI-Compatible Client Builder Source: https://docs.rs/aquaregia/latest/aquaregia/client/struct.LlmClient.html Use this function to create a builder for an OpenAI-compatible client. Requires a base URL. ```rust pub fn openai_compatible( base_url: impl Into, ) -> ClientBuilder ``` -------------------------------- ### Implement ToString for T Source: https://docs.rs/aquaregia/latest/aquaregia/tool/enum.ToolExecError.html Provides a method to convert any type implementing the Display trait into a String. This is a convenient way to get a string representation. ```rust fn to_string(&self) -> String ``` -------------------------------- ### Create new AnthropicAdapterSettings Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/anthropic/struct.AnthropicAdapterSettings.html Constructor for initializing settings with a provided API key and default values for base URL and API version. ```rust pub fn new(api_key: impl Into) -> Self ``` -------------------------------- ### Get All Registered Tool Names Source: https://docs.rs/aquaregia/latest/aquaregia/tool/struct.ToolRegistry.html Returns a vector containing the names of all tools currently registered in the ToolRegistry. The names are returned as string slices. ```rust pub fn names(&self) -> Vec<&str> ``` -------------------------------- ### Get Tool by Name Source: https://docs.rs/aquaregia/latest/aquaregia/tool/struct.ToolRegistry.html Retrieves a registered tool from the ToolRegistry by its name. Returns an Option<&Tool>, which is Some(&Tool) if the tool is found, or None otherwise. ```rust pub fn get(&self, name: &str) -> Option<&Tool> ``` -------------------------------- ### Get Provider-Local Model ID Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.ModelRef.html Retrieves the model identifier as used by the specific provider, without the provider prefix. This is typically used in API requests. ```rust pub fn model(&self) -> &str ``` -------------------------------- ### AgentStart Data Structure Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.AgentStart.html Definition and fields for the AgentStart object. ```APIDOC ## AgentStart Structure ### Description Emitted once before the first agent step to initialize the run context. ### Fields - **model_id** (String) - Fully-qualified model id used by the run. - **messages** (Vec) - Initial messages passed into the run. - **tool_count** (usize) - Number of registered tools. - **max_steps** (u8) - Effective max step cap for this run. ### Request Example { "model_id": "gpt-4-turbo", "messages": [], "tool_count": 5, "max_steps": 10 } ``` -------------------------------- ### PolicyExt::or Source: https://docs.rs/aquaregia/latest/aquaregia/struct.CancellationToken.html Creates a new Policy that returns Action::Follow if either policy returns Action::Follow. ```APIDOC ## POST /policy/or ### Description Create a new `Policy` that returns `Action::Follow` if either `self` or `other` returns `Action::Follow`. ### Method POST ### Endpoint /policy/or ### Parameters #### Request Body - **other** (Policy) - Required - The other policy to combine. - **self** (Policy) - Required - The first policy. ### Request Example ```json { "other": "", "self": "" } ``` ### Response #### Success Response (200) - **Or** - A new policy representing the logical OR of the two input policies. #### Response Example ```json { "policy": "" } ``` ``` -------------------------------- ### Get Fully-Qualified Model ID Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.ModelRef.html Retrieves the complete model identifier, including the provider prefix (e.g., "provider/model"). This is useful for logging or display purposes. ```rust pub fn id(&self) -> String ``` -------------------------------- ### Unwrapping a Pin to Get the Underlying Pointer Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextDeltaStream.html Safely unwraps a `Pin` to return the original pointer `Ptr`. This operation is `unsafe` and should only be used when the pinning invariants are guaranteed to be upheld. ```rust pub const unsafe fn into_inner_unchecked(pin: Pin) -> Ptr ``` -------------------------------- ### Create OpenAI Client Builder Source: https://docs.rs/aquaregia/latest/aquaregia/client/struct.LlmClient.html Use this function to create a builder for an OpenAI client. Requires an API key. ```rust pub fn openai(api_key: impl Into) -> ClientBuilder ``` -------------------------------- ### Getting Nested Mutable Reference from Pin Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextDeltaStream.html Extracts a `Pin<&mut T>` from a nested `Pin<&mut Pin>>`. This operation is safe because the outer `Pin` guarantees the inner pointee cannot move. ```rust pub fn as_deref_mut( self: Pin<&mut Pin>, ) -> Pin<&mut ::Target> where Ptr: DerefMut ``` -------------------------------- ### OpenAiAdapterSettings Configuration Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/openai/struct.OpenAiAdapterSettings.html Defines the structure and initialization for OpenAI adapter settings. ```APIDOC ## OpenAiAdapterSettings ### Description Runtime settings for the OpenAI adapter, containing configuration for the API endpoint and authentication. ### Fields - **base_url** (String) - Base URL for API requests. - **api_key** (String) - API key sent as a bearer token. ### Initialization #### pub fn new(api_key: impl Into) -> Self Creates settings with a default base URL. ``` -------------------------------- ### Getting a Shared Reference to Pinned Data Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextDeltaStream.html Retrieves a shared reference (`Pin<&T>`) to the data pointed to by a `Pin>`. This operation is safe due to the pinning contract ensuring the data does not move. ```rust pub fn as_ref(&self) -> Pin<&::Target> where Ptr: Deref ``` -------------------------------- ### GoogleAdapterSettings Configuration Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/google/struct.GoogleAdapterSettings.html Defines the structure and initialization for Google adapter settings. ```APIDOC ## GoogleAdapterSettings ### Description Runtime settings for the Google adapter, used to configure API requests. ### Fields - **base_url** (String) - Base URL for API requests. - **api_key** (String) - API key sent via the x-goog-api-key header. ### Initialization - **new(api_key: impl Into) -> Self** - Creates settings with a default base URL. ``` -------------------------------- ### Provider-Specific Settings Source: https://docs.rs/aquaregia/latest/aquaregia/client/trait.ProviderBinding.html Illustrates the different configuration options for various AI providers. Each provider requires specific settings such as base URL and API key. ```rust OpenAI: `base_url`, `api_key` Anthropic: `base_url`, `api_key`, `api_version` Google: `base_url`, `api_key` OpenAI-compatible: `base_url`, optional `api_key`, custom headers/query params ``` -------------------------------- ### Formatting Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextStream.html Implementation of the `fmt::Display` trait for Pin. ```APIDOC ## Formatting ### `fmt` - **Description**: Formats the value using the given formatter. - **Method**: N/A (Method on `Pin`) - **Parameters**: `f: &mut Formatter<'_>` - **Returns**: `Result<(), Error>` ``` -------------------------------- ### Getting a Mutable Reference to Pinned Data Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextDeltaStream.html Retrieves a mutable reference (`Pin<&mut T>`) to the data pointed to by a `Pin>`. This is useful when multiple operations need to be performed on the pinned data, and each operation requires a mutable borrow. ```rust pub fn as_mut(&mut self) -> Pin<&mut ::Target> where Ptr: DerefMut ``` -------------------------------- ### Demonstrate UB with `Pin::new_unchecked` on `&mut T` Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextStream.html This example shows how calling `Pin::new_unchecked` on a mutable reference can lead to undefined behavior if the underlying data is moved after pinning. This violates the API contract that pinned data must not be moved. ```rust use std::mem; use std::pin::Pin; fn move_pinned_ref(mut a: T, mut b: T) { unsafe { let p: Pin<&mut T> = Pin::new_unchecked(&mut a); // This should mean the pointee `a` can never move again. } mem::swap(&mut a, &mut b); // Potential UB down the road ⚠️ // The address of `a` changed to `b`'s stack slot, so `a` got moved even // though we have previously pinned it! We have violated the pinning API contract. } ``` -------------------------------- ### OpenAiCompatibleAdapterSettings Configuration Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/openai_compatible/struct.OpenAiCompatibleAdapterSettings.html Methods for configuring the OpenAI-compatible adapter settings, including base URL, authentication, and parsing options. ```APIDOC ## Configuration Methods ### Description Methods to configure the behavior of the OpenAI-compatible adapter. ### Methods - **new(base_url)**: Creates settings with a default path and no API key. - **api_key(api_key)**: Sets a bearer token for authentication. - **no_api_key()**: Clears the bearer token. - **header(name, value)**: Adds or replaces a custom HTTP header. - **query_param(name, value)**: Adds or replaces a query parameter. - **chat_completions_path(path)**: Overrides the default chat completions path. - **think_tag_parsing(enabled)**: Enables or disables / tag parsing from content. - **think_tag_case_insensitive(case_insensitive)**: Controls case sensitivity for think tag parsing. ``` -------------------------------- ### Agent Run Methods Source: https://docs.rs/aquaregia/latest/aquaregia/agent/struct.Agent.html Details the different methods for running the agent, including single prompt, message list, and cancellable operations. ```APIDOC ### pub async fn run( &self, prompt: impl Into, ) -> Result Runs the agent with a single user prompt. If `instructions` were configured, they are inserted as an initial system message. ### pub async fn run_messages( &self, messages: Vec, ) -> Result Runs the agent with an explicit message list. ### pub async fn run_cancellable( &self, prompt: impl Into, token: CancellationToken, ) -> Result Runs the agent with a prompt and cancellation support. ### pub async fn run_messages_cancellable( &self, messages: Vec, token: CancellationToken, ) -> Result Runs the agent with explicit messages and cancellation support. ``` -------------------------------- ### Demonstrate UB with `Pin::new_unchecked` on `Rc` Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextStream.html This example illustrates undefined behavior when using `Pin::new_unchecked` with `Rc`. If other references to the same data exist, they are not subject to pinning restrictions, allowing the data to be moved while still considered pinned, thus violating the API contract. ```rust use std::rc::Rc; use std::pin::Pin; fn move_pinned_rc(mut x: Rc) { // This should mean the pointee can never move again. let pin = unsafe { Pin::new_unchecked(Rc::clone(&x)) }; { let p: Pin<&T> = pin.as_ref(); // ... } drop(pin); let content = Rc::get_mut(&mut x).unwrap(); // Potential UB down the road ⚠️ // Now, if `x` was the only reference, we have a mutable reference to // data that we pinned above, which we could use to move it as we have // seen in the previous example. We have violated the pinning API contract. } ``` -------------------------------- ### Policy::or Source: https://docs.rs/aquaregia/latest/aquaregia/client/struct.ClientBuilder.html Creates a new Policy that returns Action::Follow if either the current or the provided policy returns Action::Follow. ```APIDOC ## fn or(self, other: P) -> Or ### Description Create a new `Policy` that returns `Action::Follow` if either `self` or `other` returns `Action::Follow`. ### Parameters #### Path Parameters - **other** (P) - Required - The other policy to evaluate. ``` -------------------------------- ### Clone Implementation for AgentStart Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.AgentStart.html Provides methods to duplicate or copy-assign AgentStart values. Ensures that AgentStart instances can be cloned. ```rust fn clone(&self) -> AgentStart ``` ```rust fn clone_from(&mut self, source: &Self) ``` -------------------------------- ### Build BoundClient Source: https://docs.rs/aquaregia/latest/aquaregia/client/struct.ClientBuilder.html Builds a provider-bound client with the configured settings. This method validates the settings before returning the client. ```rust pub fn build(self) -> Result, Error> ``` -------------------------------- ### Run Agent with Prompt Source: https://docs.rs/aquaregia/latest/aquaregia/agent/struct.Agent.html Executes the agent with a single user prompt. If configured, instructions are prepended as a system message. ```rust pub async fn run( &self, prompt: impl Into, ) -> Result ``` -------------------------------- ### Clone Implementation for AgentPreparedStep Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.AgentPreparedStep.html Provides the `clone` and `clone_from` methods for the AgentPreparedStep struct, allowing for duplication of its state. Requires the generic type P to implement Clone and ProviderMarker. ```rust impl Clone for AgentPreparedStep

``` -------------------------------- ### Create AnthropicAdapter from Settings Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/anthropic/struct.AnthropicAdapter.html Constructs an AnthropicAdapter instance using provided settings and a shared HTTP client. Ensure settings are validated before use. ```rust pub fn from_settings( settings: AnthropicAdapterSettings, http: Arc, ) -> Self ``` -------------------------------- ### DispatchFromDyn Implementation Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextStream.html Implementation of `DispatchFromDyn` for `Pin` to `Pin`. ```APIDOC ## DispatchFromDyn Implementation ### `DispatchFromDyn>` - **Description**: Allows dispatching from `Pin` to `Pin` under specific trait bounds. - **Method**: N/A (Implementation for `Pin`) - **Bounds**: `Ptr: DispatchFromDyn + PinCoerceUnsized`, `U: PinCoerceUnsized` ``` -------------------------------- ### Implement ProviderBinding for OpenAi Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.OpenAi.html Binds the `OpenAi` provider with its specific settings and adapter. Use `into_adapter` to convert settings into a runtime adapter. ```rust type Settings = OpenAiAdapterSettings ``` ```rust fn into_adapter( settings: Self::Settings, http: Arc, ) -> Arc> ``` -------------------------------- ### Clone Implementation for Pin Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextStream.html Details the `clone` and `clone_from` methods for `Pin` when `Ptr` implements `Clone`. ```APIDOC ## impl Clone for Pin where Ptr: Clone, ### fn clone(&self) -> Pin Returns a duplicate of the value. Read more ### fn clone_from(&mut self, source: &Self) Performs copy-assignment from `source`. Read more ``` -------------------------------- ### AsyncSeek Implementation for Pin Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextStream.html Details the `start_seek` and `poll_complete` methods for `Pin

` when `P` implements `AsyncSeek`. ```APIDOC ## impl

AsyncSeek for Pin

where P: DerefMut,

::Target: AsyncSeek, ### fn start_seek(self: Pin<&mut Pin

>, pos: SeekFrom) -> Result<(), Error> Attempts to seek to an offset, in bytes, in a stream. Read more ### fn poll_complete( self: Pin<&mut Pin

>, cx: &mut Context<'_>, ) -> Poll> Waits for a seek operation to complete. Read more ``` -------------------------------- ### TryFrom Implementation Source: https://docs.rs/aquaregia/latest/aquaregia/agent/struct.AgentBuilder.html Provides a mechanism to attempt conversion from one type to another, with a potential error. ```APIDOC ### impl TryFrom for T #### type Error = Infallible ### Description The type returned in the event of a conversion error. #### fn try_from(value: U) -> Result>::Error> ### Description Performs the conversion. ### Method try_from ### Endpoint N/A ``` -------------------------------- ### Tool::from_parts Source: https://docs.rs/aquaregia/latest/aquaregia/tool/struct.Tool.html Constructor for creating a Tool instance from its components. ```APIDOC ## impl Tool ### pub fn from_parts( descriptor: ToolDescriptor, executor: Arc, ) -> Self Creates a tool from explicit parts. ``` -------------------------------- ### AgentPreparedStep Struct Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.AgentPreparedStep.html Represents a finalized step input for an agent, containing model, messages, tools, and generation parameters. ```APIDOC ## Struct AgentPreparedStep ### Description Finalized step input returned by `prepare_step`. ### Fields - **model** (ModelRef

) - Model selected for this step. - **messages** (Vec) - Messages to send for this step. - **tools** (Vec) - Tools available for this step. - **temperature** (Option) - Sampling temperature for this step. - **max_output_tokens** (Option) - Max output token budget for this step. - **stop_sequences** (Vec) - Stop sequences for this step. ### Trait Implementations #### Clone - `clone(&self) -> AgentPreparedStep

`: Returns a duplicate of the value. - `clone_from(&mut self, source: &Self)`: Performs copy-assignment from `source`. #### Debug - `fmt(&self, f: &mut Formatter<'_>) -> Result`: Formats the value using the given formatter. ### Auto Trait Implementations - Freeze - !RefUnwindSafe - Send - Sync - Unpin - UnsafeUnpin - !UnwindSafe ### Blanket Implementations - Any - Borrow - BorrowMut - CloneToUninit - DynClone - From - Instrument - Into - PolicyExt - ToOwned - TryFrom - TryInto - WithSubscriber ``` -------------------------------- ### POST /stream Source: https://docs.rs/aquaregia/latest/aquaregia/client/struct.BoundClient.html Runs a streaming generation request using the bound provider. ```APIDOC ## POST /stream ### Description Runs a streaming generation request. The request is validated locally and retried on retryable failures. ### Method POST ### Parameters #### Request Body - **req** (GenerateTextRequest

) - Required - The generation request configuration. ### Response #### Success Response (200) - **stream** (TextStream) - A stream of text responses. ``` -------------------------------- ### TryInto Implementation Source: https://docs.rs/aquaregia/latest/aquaregia/agent/struct.AgentBuilder.html Provides a mechanism to attempt conversion into another type, with a potential error. ```APIDOC ### impl TryInto for T #### type Error = >::Error ### Description The type returned in the event of a conversion error. #### fn try_into(self) -> Result>::Error> ### Description Performs the conversion. ### Method try_into ### Endpoint N/A ``` -------------------------------- ### Clone Into AgentPrepareStep Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.AgentPrepareStep.html Uses borrowed data to replace owned data, usually by cloning. Requires `T` to implement `Clone`. ```rust fn clone_into(&self, target: &mut T) ``` -------------------------------- ### Create Anthropic Client Builder Source: https://docs.rs/aquaregia/latest/aquaregia/client/struct.LlmClient.html Use this function to create a builder for an Anthropic client. Requires an API key. ```rust pub fn anthropic(api_key: impl Into) -> ClientBuilder ``` -------------------------------- ### Function: tool Source: https://docs.rs/aquaregia/latest/aquaregia/tool/fn.tool.html Initializes a ToolBuilder for defining tool descriptors and executors. ```APIDOC ## tool ### Description Starts building a tool descriptor and executor. ### Signature `pub fn tool(name: impl Into) -> ToolBuilder` ### Parameters - **name** (impl Into) - Required - The name of the tool to be created. ``` -------------------------------- ### Define GoogleAdapterSettings struct Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/google/struct.GoogleAdapterSettings.html The structure used to hold runtime settings for the Google adapter. ```rust pub struct GoogleAdapterSettings { pub base_url: String, pub api_key: String, } ``` -------------------------------- ### Combine Policies with And Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/anthropic/struct.AnthropicAdapter.html Creates a new `Policy` that requires both `self` and `other` policies to return `Action::Follow`. Used for combining policy logic. ```rust fn and(self, other: P) -> And where T: Policy, P: Policy, ``` -------------------------------- ### Agent Runtime and Builder API Source: https://docs.rs/aquaregia/latest/aquaregia/agent/index.html Overview of the Agent architecture and usage for creating and executing tool-using agents. ```APIDOC ## Agent Runtime and Builder ### Description The Agent module provides the core abstraction for multi-step tool-using agents. It manages the interaction loop between the LLM and available tools. ### Components - **Agent

**: The main runtime for executing tool loops. - **AgentBuilder

**: Used to configure agent behavior, including instructions, tools, and model parameters. - **AgentRunPlan

**: A mutable plan used to customize specific agent runs. ### Usage Example ```rust use aquaregia::{Agent, LlmClient, tool}; use serde_json::{Value, json}; #[tool(description = "Get weather by city")] async fn get_weather(city: String) -> Result { Ok(json!({ "city": city, "temp_c": 23, "condition": "sunny" })) } let client = LlmClient::openai("api-key").build()?; let agent = Agent::builder(client, "gpt-4o") .instructions("You can call tools before answering.") .tools([get_weather]) .max_steps(4) .build()?; let out = agent.run("What is the weather in Shanghai?").await?; println!("{}", out.output_text); ``` ``` -------------------------------- ### Conversion Traits (Into, TryFrom, TryInto) Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.ModelRef.html Documentation for type conversion traits. ```APIDOC ### impl Into for T where U: From, #### fn into(self) -> U ### Description Calls `U::from(self)`. That is, this conversion is whatever the implementation of `From for U` chooses to do. ### Method `into` ### Endpoint N/A (Method Implementation) ### impl TryFrom for T where U: Into, #### type Error = Infallible ### Description The type returned in the event of a conversion error. #### fn try_from(value: U) -> Result>::Error> ### Description Performs the conversion. ### Method `try_from` ### Endpoint N/A (Method Implementation) ### impl TryInto for T where U: TryFrom, #### type Error = >::Error ### Description The type returned in the event of a conversion error. #### fn try_into(self) -> Result>::Error> ### Description Performs the conversion. ### Method `try_into` ### Endpoint N/A (Method Implementation) ``` -------------------------------- ### Implement ProviderMarker for Google Source: https://docs.rs/aquaregia/latest/aquaregia/types/trait.ProviderMarker.html Implementation of the ProviderMarker trait for the Google provider. ```rust impl ProviderMarker for Google { const KIND: ProviderKind = ProviderKind::Google } ``` -------------------------------- ### Policy AND Operation Source: https://docs.rs/aquaregia/latest/aquaregia/model_adapters/openai_compatible/struct.OpenAiCompatibleAdapterSettings.html Creates a new `Policy` that returns `Action::Follow` only if both `self` and `other` policies return `Action::Follow`. Part of `PolicyExt`. ```rust fn and(self, other: P) -> And where T: Policy, P: Policy ``` -------------------------------- ### Define a tool using the #[tool] macro Source: https://docs.rs/aquaregia/latest/aquaregia/tool/index.html The recommended approach for defining tools using the procedural macro for concise syntax. ```rust use aquaregia::tool; use serde_json::{Value, json}; #[tool(description = "Get weather by city")] async fn get_weather(city: String) -> Result { Ok(json!({ "city": city, "temp_c": 23, "condition": "sunny" })) } ``` -------------------------------- ### Comparison Methods Source: https://docs.rs/aquaregia/latest/aquaregia/types/type.TextStream.html Methods for comparing Pin instances. ```APIDOC ## Comparison Methods ### `partial_cmp` - **Description**: Returns an ordering between `self` and `other` values if one exists. - **Method**: N/A (Method on `Pin`) - **Parameters**: `other: &Pin` - **Returns**: `Option` ### `lt` - **Description**: Tests less than (for `self` and `other`) and is used by the `<` operator. - **Method**: N/A (Method on `Pin`) - **Parameters**: `other: &Pin` - **Returns**: `bool` ### `le` - **Description**: Tests less than or equal to (for `self` and `other`) and is used by the `<=` operator. - **Method**: N/A (Method on `Pin`) - **Parameters**: `other: &Pin` - **Returns**: `bool` ### `gt` - **Description**: Tests greater than (for `self` and `other`) and is used by the `>` operator. - **Method**: N/A (Method on `Pin`) - **Parameters**: `other: &Pin` - **Returns**: `bool` ### `ge` - **Description**: Tests greater than or equal to (for `self` and `other`) and is used by the `>=` operator. - **Method**: N/A (Method on `Pin`) - **Parameters**: `other: &Pin` - **Returns**: `bool` ``` -------------------------------- ### AgentPrepareStep Struct Definition Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.AgentPrepareStep.html Defines the structure for per-step mutable input passed to `prepare_step`. It includes fields for step details, model, messages, tools, and generation parameters. ```rust pub struct AgentPrepareStep { pub step: u8, pub model: ModelRef

, pub messages: Vec, pub tools: Vec, pub temperature: Option, pub max_output_tokens: Option, pub stop_sequences: Vec, pub previous_steps: Vec, } ``` -------------------------------- ### Usage Struct Methods Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.Usage.html Methods for creating and modifying Usage instances. ```APIDOC ## impl Usage ### `from_totals` #### Signature `pub fn from_totals(input_tokens: u32, output_tokens: u32, reasoning_tokens: u32, total_tokens: Option) -> Self` ### Description Builds usage from provider totals and back-fills derived counters. ``` ```APIDOC ### `with_input_cache_split` #### Signature `pub fn with_input_cache_split(self, cache_read_tokens: u32, cache_write_tokens: u32) -> Self` ### Description Sets input cache split and recomputes no-cache input tokens. ``` ```APIDOC ### `with_output_split` #### Signature `pub fn with_output_split(self, output_text_tokens: u32, reasoning_tokens: u32) -> Self` ### Description Sets output text/reasoning split and recomputes total output tokens. ``` ```APIDOC ### `with_raw_usage` #### Signature `pub fn with_raw_usage(self, raw_usage: Value) -> Self` ### Description Attaches raw provider usage payload. ``` -------------------------------- ### Create a User Message with Text Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.Message.html Creates a user message containing a single text part. User messages represent prompts or questions from the end user. ```rust pub fn user_text(text: impl Into) -> Self ``` -------------------------------- ### Create ModelRef Instance Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.ModelRef.html Instantiates a ModelRef for a specific provider. Requires importing the provider type (e.g., `OpenAi`) and the `ModelRef` struct. The model ID is a String. ```rust use aquaregia::{ModelRef, OpenAi}; let model = ModelRef::::new("gpt-4o"); assert_eq!(model.id(), "openai/gpt-4o"); assert_eq!(model.model(), "gpt-4o"); ``` -------------------------------- ### Policy::or Source: https://docs.rs/aquaregia/latest/aquaregia/types/enum.ProviderKind.html Combines two policies into a new policy that returns Action::Follow if either policy succeeds. ```APIDOC ## fn or(self, other: P) -> Or ### Description Creates a new `Policy` that returns `Action::Follow` if either `self` or `other` returns `Action::Follow`. ### Parameters #### Path Parameters - **other** (P) - Required - The secondary policy to evaluate. ``` -------------------------------- ### Create User Message with Text and Image URL Source: https://docs.rs/aquaregia/latest/aquaregia/types/struct.Message.html Creates a user message that includes both text and an image URL. ```rust pub fn user_text_and_image_url( text: impl Into, url: impl Into, ) -> Self ```