### CLI Example for Local Server Source: https://yologdev.github.io/yoagent/providers/openai-compat.html Shows the command-line interface command to run the CLI example, connecting to a local OpenAI-compatible server with a specified API URL and model. ```bash cargo run --example cli -- --api-url http://localhost:1234/v1 --model my-model ``` -------------------------------- ### Example CLI Output Source: https://yologdev.github.io/yoagent/concepts/tools.html The expected console output when running the streaming deployment tool. ```text šŸš€ Starting deploy... [1/4] Building image... [2/4] Running tests... [3/4] Pushing to registry... [4/4] Rolling out... āœ… deploy complete Successfully deployed to production. The deployment completed all 4 stages. ``` -------------------------------- ### Configure Authentication Methods Source: https://yologdev.github.io/yoagent/guides/openapi.html Examples of setting up different authentication schemes for OpenAPI requests. ```rust #![allow(unused)] fn main() { // Bearer token let config = OpenApiConfig::new().with_bearer_token("token"); // API key in a custom header let config = OpenApiConfig::new().with_api_key("X-API-Key", "key-value"); // No auth let config = OpenApiConfig::new(); // default } ``` -------------------------------- ### Agent loop with OpenAiCompatProvider Source: https://yologdev.github.io/yoagent/print.html This example shows how to use the OpenAiCompatProvider for OpenAI, xAI, Groq, DeepSeek, Mistral, MiniMax, Z.ai, or any compatible API. It configures the agent with a system prompt, model, API key, and default tools, then initiates a prompt and processes the events. ```rust use yoagent::{Agent, AgentEvent}; use yoagent::provider::OpenAiCompatProvider; use yoagent::tools::default_tools; #[tokio::main] async fn main() { let mut agent = Agent::new(OpenAiCompatProvider) .with_system_prompt("You are a helpful assistant.") .with_model("gpt-4o") .with_api_key(std::env::var("OPENAI_API_KEY").unwrap()) .with_tools(default_tools()); let mut rx = agent.prompt("What is 2 + 2?").await; while let Some(event) = rx.recv().await { match event { AgentEvent::MessageUpdate { delta, .. } => { if let yoagent::StreamDelta::Text { delta } = delta { print!("{}", delta); } } AgentEvent::AgentEnd { .. } => println!(), _ => {} } } } ``` -------------------------------- ### Basic agent loop with AnthropicProvider Source: https://yologdev.github.io/yoagent/print.html This example demonstrates a basic agent loop using the AnthropicProvider. It sets up the agent with a system prompt, model, API key, and default tools, then prompts the agent and streams the events. ```rust use yoagent::{Agent, AgentEvent, StreamDelta}; use yoagent::provider::AnthropicProvider; use yoagent::tools::default_tools; #[tokio::main] async fn main() { let mut agent = Agent::new(AnthropicProvider) .with_system_prompt("You are a helpful coding assistant.") .with_model("claude-sonnet-4-20250514") .with_api_key(std::env::var("ANTHROPIC_API_KEY").unwrap()) .with_tools(default_tools()); let mut rx = agent.prompt("List the files in the current directory").await; while let Some(event) = rx.recv().await { match event { AgentEvent::MessageUpdate { delta, .. } => match delta { StreamDelta::Text { delta } => print!("{}", delta), StreamDelta::Thinking { delta } => print!("[thinking] {}", delta), _ => {} }, AgentEvent::ToolExecutionStart { tool_name, .. } => { println!("\n→ Running tool: {}", tool_name); } AgentEvent::ToolExecutionEnd { tool_name, result, is_error, .. } => { if is_error { println!(" āœ— {} failed", tool_name); } else { println!(" āœ“ {} done", tool_name); } } AgentEvent::AgentEnd { .. } => { println!("\n\nDone."); } _ => {} } } } ``` -------------------------------- ### Start an agent run with agent_loop() Source: https://yologdev.github.io/yoagent/concepts/agent-loop.html Initializes a new agent run by adding prompts to the context and executing the agent loop. ```rust #![allow(unused)] fn main() { pub async fn agent_loop( prompts: Vec, context: &mut AgentContext, config: &AgentLoopConfig, tx: mpsc::UnboundedSender, cancel: CancellationToken, ) -> Vec } ``` -------------------------------- ### Configure SKILL.md Frontmatter Source: https://yologdev.github.io/yoagent/concepts/skills.html Example of the YAML frontmatter and instruction format required within a SKILL.md file. ```yaml --- name: git description: Git operations — commit, branch, merge, rebase. Use when the user mentions version control. --- # Git Skill ## Workflow 1. Run `git status` first 2. Stage changes, write conventional commit messages 3. For merges, check for conflicts first ## Scripts For complex diffs: `bash {baseDir}/scripts/diff_summary.sh` ``` -------------------------------- ### Get all default tools Source: https://yologdev.github.io/yoagent/reference/tools.html Use `default_tools()` to import all available coding-oriented tools. ```rust #![allow(unused)] fn main() { use yoagent::tools::default_tools; let tools = default_tools(); } ``` -------------------------------- ### Initialize Local OpenAI Compatible Agent Source: https://yologdev.github.io/yoagent/providers/openai-compat.html Demonstrates initializing an agent for a local OpenAI-compatible server, specifying the local base URL and model name. No API key is required for local setups. ```rust use yoagent::agent::Agent; use yoagent::provider::{OpenAiCompatProvider, ModelConfig}; let agent = Agent::new(OpenAiCompatProvider) .with_model_config(ModelConfig::local("http://localhost:1234/v1", "my-model")) .with_model("my-model") .with_api_key(""); // empty string OK for local ``` -------------------------------- ### Implement a Custom WeatherTool Source: https://yologdev.github.io/yoagent/concepts/tools.html Example implementation of a tool that retrieves weather data based on a city parameter. ```rust #![allow(unused)] fn main() { use yoagent::types::*; use async_trait::async_trait; pub struct WeatherTool; #[async_trait] impl AgentTool for WeatherTool { fn name(&self) -> &str { "get_weather" } fn label(&self) -> &str { "Weather" } fn description(&self) -> &str { "Get current weather for a city." } fn parameters_schema(&self) -> serde_json::Value { serde_json::json!({ "type": "object", "properties": { "city": { "type": "string", "description": "City name" } }, "required": ["city"] }) } async fn execute( &self, params: serde_json::Value, _ctx: ToolContext, ) -> Result { let city = params["city"].as_str() .ok_or(ToolError::InvalidArgs("missing city".into()))?; // Call weather API... Ok(ToolResult { content: vec![Content::Text { text: format!("Weather in {}: 72°F, sunny", city), }], details: serde_json::Value::Null, }) } } } ``` -------------------------------- ### Implement Tool with Progress Updates Source: https://yologdev.github.io/yoagent/concepts/tools.html Example of a tool that fetches rows, processes them, and streams progress updates using the `on_update` callback every 100 rows. It also includes cancellation checks. ```rust #![allow(unused)] fn main() { use yoagent::types::*; struct DataProcessorTool; #[async_trait] impl AgentTool for DataProcessorTool { // ... name, label, description, parameters_schema ... async fn execute( &self, params: serde_json::Value, ctx: ToolContext, ) -> Result { let rows = fetch_rows(¶ms)?; let total = rows.len(); for (i, row) in rows.iter().enumerate() { // Check for cancellation if ctx.cancel.is_cancelled() { return Err(ToolError::Cancelled); } process_row(row); // Stream progress every 100 rows if i % 100 == 0 { if let Some(ref cb) = &ctx.on_update { cb(ToolResult { content: vec![Content::Text { text: format!("Processed {}/{} rows", i, total), }], details: serde_json::json!({{"progress": i as f64 / total as f64}}), }); } } } Ok(ToolResult { content: vec![Content::Text { text: format!("Processed all {} rows", total), }], details: serde_json::Value::Null, }) } } } ``` -------------------------------- ### Retry Configuration Example Source: https://yologdev.github.io/yoagent/concepts/retry.html Defines the configuration for retry attempts, including maximum retries, initial delay, backoff multiplier, and maximum delay. ```rust #![allow(unused)] fn main() { RetryConfig { max_retries: 3, // Up to 3 retry attempts initial_delay_ms: 1000, // 1 second before first retry backoff_multiplier: 2.0, // Double the delay each attempt max_delay_ms: 30_000, // Cap at 30 seconds } } ``` -------------------------------- ### Configure Agent System Prompt Source: https://yologdev.github.io/yoagent/reference/api.html Sets the system prompt for the agent, which guides its overall behavior and persona. ```rust with_system_prompt(prompt) -> Self ``` -------------------------------- ### Agent Loop Functions Source: https://yologdev.github.io/yoagent/print.html Functions for starting or continuing an agent execution loop. ```rust #![allow(unused)] fn main() { pub async fn agent_loop( prompts: Vec, context: &mut AgentContext, config: &AgentLoopConfig, tx: mpsc::UnboundedSender, cancel: CancellationToken, ) -> Vec } ``` ```rust #![allow(unused)] fn main() { pub async fn agent_loop_continue( context: &mut AgentContext, config: &AgentLoopConfig, tx: mpsc::UnboundedSender, cancel: CancellationToken, ) -> Vec } ``` -------------------------------- ### BedrockProvider Initialization Source: https://yologdev.github.io/yoagent/providers/bedrock.html Demonstrates how to initialize the BedrockProvider with a model and API key. ```APIDOC ## BedrockProvider Initialization ### Description Initialize the `BedrockProvider` with a specific AWS Bedrock model and your API credentials. ### Method Instantiation and Configuration ### Endpoint N/A (Provider level configuration) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use yoagent::provider::BedrockProvider; use yoagent::Agent; let agent = Agent::new(BedrockProvider) .with_model("anthropic.claude-3-sonnet-20240229-v1:0") .with_api_key("ACCESS_KEY:SECRET_KEY"); // or ACCESS_KEY:SECRET_KEY:SESSION_TOKEN ``` ### Response N/A (Initialization does not return a response) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Pre-load Agent Messages Source: https://yologdev.github.io/yoagent/reference/api.html Loads a history of messages into the agent before starting its execution. ```rust with_messages(msgs: Vec) -> Self ``` -------------------------------- ### Initialize AzureOpenAiProvider Source: https://yologdev.github.io/yoagent/providers/azure-openai.html Instantiate the provider and configure the model and API key. ```rust #![allow(unused)] fn main() { use yoagent::provider::AzureOpenAiProvider; let agent = Agent::new(AzureOpenAiProvider) .with_model("gpt-4o") .with_api_key(std::env::var("AZURE_OPENAI_API_KEY").unwrap()); } ``` -------------------------------- ### Configure Tool Execution Strategy Source: https://yologdev.github.io/yoagent/concepts/tools.html Demonstrates how to initialize an Agent with different ToolExecutionStrategy variants to control concurrency and steering checkpoints. ```rust #![allow(unused)] fn main() { use yoagent::agent::Agent; use yoagent::types::ToolExecutionStrategy; // Default — parallel (fastest) let agent = Agent::new(provider); // Sequential (debug / shared state) let agent = Agent::new(provider) .with_tool_execution(ToolExecutionStrategy::Sequential); // Batched — 3 at a time let agent = Agent::new(provider) .with_tool_execution(ToolExecutionStrategy::Batched { size: 3 }); } ``` -------------------------------- ### Combine multiple lifecycle callbacks Source: https://yologdev.github.io/yoagent/concepts/callbacks.html All callbacks are optional and independent. This example chains before_turn, after_turn, and on_error. ```rust #![allow(unused)] fn main() { let agent = Agent::new(provider) .on_before_turn(|_msgs, turn| turn < 20) .on_after_turn(|msgs, usage| { println!("Messages: {}, Tokens: {}/{}", msgs.len(), usage.input, usage.output); }) .on_error(|err| eprintln!("Error: {}", err)); } ``` -------------------------------- ### Initialize Agent with OpenAPI Source: https://yologdev.github.io/yoagent/guides/openapi.html Demonstrates setting up an agent with an OpenAPI file. Requires the 'openapi' feature enabled in Cargo.toml. ```rust use yoagent::Agent; use yoagent::openapi::{OpenApiToolAdapter, OpenApiConfig, OperationFilter}; use yoagent::provider::AnthropicProvider; #[tokio::main] async fn main() -> Result<(), Box> { let config = OpenApiConfig::new() .with_bearer_token("sk-..."); let agent = Agent::new(AnthropicProvider) .with_system_prompt("You are an API assistant.") .with_model("claude-sonnet-4-20250514") .with_api_key(std::env::var("ANTHROPIC_API_KEY")?) .with_openapi_file("petstore.yaml", config, &OperationFilter::All) .await?; Ok(()) } ``` -------------------------------- ### Initialize OpenAiCompatProvider Source: https://yologdev.github.io/yoagent/print.html Configure the OpenAI-compatible provider for various LLM services. ```rust #![allow(unused)] fn main() { use yoagent::provider::{OpenAiCompatProvider, ModelConfig}; let agent = Agent::new(OpenAiCompatProvider) .with_model("gpt-4o") .with_api_key(std::env::var("OPENAI_API_KEY").unwrap()); } ``` -------------------------------- ### Create Manual OpenAPI Adapters Source: https://yologdev.github.io/yoagent/guides/openapi.html Manually create adapters to gain more control over tool generation. ```rust #![allow(unused)] fn main() { let adapters = OpenApiToolAdapter::from_str(&spec, config, &OperationFilter::All)?; let tools: Vec> = adapters.into_iter().map(|a| Box::new(a) as _).collect(); } ``` -------------------------------- ### Agent Loop Functions Source: https://yologdev.github.io/yoagent/print.html Functions for managing the agent's conversational loop, including starting, continuing, and accessing default tools. ```APIDOC ## Agent Loop Functions ### `agent_loop()` #### Description Starts an agent loop with new prompt messages. Returns all messages generated during the run. #### Signature `pub async fn agent_loop( prompts: Vec, context: &mut AgentContext, config: &AgentLoopConfig, tx: mpsc::UnboundedSender, cancel: CancellationToken, ) -> Vec` ### `agent_loop_continue()` #### Description Resumes from an existing context. The last message must not be an assistant message. #### Signature `pub async fn agent_loop_continue( context: &mut AgentContext, config: &AgentLoopConfig, tx: mpsc::UnboundedSender, cancel: CancellationToken, ) -> Vec` ### `default_tools()` #### Description Returns a default set of tools available to the agent. #### Returns `Vec>` - A vector containing `BashTool`, `ReadFileTool`, `WriteFileTool`, `EditFileTool`, `ListFilesTool`, `SearchTool`. ``` -------------------------------- ### Initialize OpenAI Compatible Agent Source: https://yologdev.github.io/yoagent/providers/openai-compat.html Demonstrates how to initialize an agent with an OpenAI-compatible provider, specifying the model and API key. ```rust #![allow(unused)] fn main() { use yoagent::provider::{OpenAiCompatProvider, ModelConfig}; let agent = Agent::new(OpenAiCompatProvider) .with_model("gpt-4o") .with_api_key(std::env::var("OPENAI_API_KEY").unwrap()); } ``` -------------------------------- ### Implement after_turn callback Source: https://yologdev.github.io/yoagent/concepts/callbacks.html Called after each LLM response and tool execution. Receives updated message history and token usage. This example tracks cumulative token usage. ```rust #![allow(unused)] fn main() { use std::sync::{Arc, Mutex}; let total_cost = Arc::new(Mutex::new(0u64)); let cost_tracker = total_cost.clone(); let agent = Agent::new(provider) .on_after_turn(move |_messages, usage| { let mut cost = cost_tracker.lock().unwrap(); *cost += usage.input + usage.output; println!("Cumulative tokens: {}", *cost); }); } ``` -------------------------------- ### Implement before_turn callback Source: https://yologdev.github.io/yoagent/concepts/callbacks.html Called before each LLM call. Receives message history and turn number. Return false to abort the loop. Example stops after 10 turns. ```rust #![allow(unused)] fn main() { let agent = Agent::new(provider) .on_before_turn(|messages, turn| { println!("Turn {} starting with {} messages", turn, messages.len()); turn < 10 // Stop after 10 turns }); } ``` -------------------------------- ### Initialize Agent with Model Configuration Source: https://yologdev.github.io/yoagent/print.html Automatically derive compaction budgets from the model's context window when using specific providers. ```rust #![allow(unused)] fn main() { // MiniMax with 1M context → compacts at 800K (no manual config needed) let agent = Agent::new(OpenAiCompatProvider) .with_model_config(ModelConfig::minimax("MiniMax-Text-01", "MiniMax Text 01")) .with_api_key(api_key); // Anthropic with 200K context → compacts at 160K let agent = Agent::new(AnthropicProvider) .with_model_config(ModelConfig::anthropic("claude-sonnet-4-20250514", "Claude Sonnet 4")) .with_api_key(api_key); } ``` -------------------------------- ### Agent Initialization with Retry Configuration Source: https://yologdev.github.io/yoagent/concepts/retry.html Shows how to initialize an Agent with default retry settings, custom retry configurations, or disable retries entirely. ```rust #![allow(unused)] fn main() { use yoagent::agent::Agent; use yoagent::retry::RetryConfig; // Default — 3 retries, exponential backoff (recommended) let agent = Agent::new(provider); // Custom — more retries, longer initial delay let agent = Agent::new(provider) .with_retry_config(RetryConfig { max_retries: 5, initial_delay_ms: 2000, backoff_multiplier: 2.0, max_delay_ms: 60_000, }); // Disable retries entirely let agent = Agent::new(provider) .with_retry_config(RetryConfig::none()); } ``` -------------------------------- ### Initialize GoogleProvider with Gemini Source: https://yologdev.github.io/yoagent/providers/google.html Initializes the GoogleProvider for Google AI Studio, specifying the model and API key. Ensure the GOOGLE_API_KEY environment variable is set. ```rust #![allow(unused)] fn main() { use yoagent::provider::GoogleProvider; let agent = Agent::new(GoogleProvider) .with_model("gemini-2.0-flash") .with_api_key(std::env::var("GOOGLE_API_KEY").unwrap()); } ``` -------------------------------- ### Extension Message JSON Structure Source: https://yologdev.github.io/yoagent/concepts/persistence.html Provides an example of the JSON structure for extension messages, which are used for custom events like status updates. The `kind` field specifies the type of extension message. ```json { "role": "extension", "kind": "status_update", "data": {"status": "running"} } ``` -------------------------------- ### Interact with Agent State Source: https://yologdev.github.io/yoagent/concepts/messages-events.html Provides examples of checking the agent's streaming status and accessing its message history. It highlights using `steer()` or `follow_up()` when streaming, and warns against using `prompt()` during active streaming. ```rust // Check if the agent is currently streaming a response if agent.is_streaming() { // Use steer() or follow_up() instead of prompt() agent.steer(AgentMessage::Llm(Message::user("New instruction"))); } // Access the full message history let messages: &[AgentMessage] = agent.messages(); // Check the last message if let Some(last) = messages.last() { println!("Last message role: {}", last.role()); } ``` -------------------------------- ### Initialize AnthropicProvider Agent Source: https://yologdev.github.io/yoagent/providers/anthropic.html Demonstrates how to initialize an Agent with AnthropicProvider, specifying the model and API key. Ensure the ANTHROPIC_API_KEY environment variable is set. ```rust #![allow(unused)] fn main() { use yoagent::provider::AnthropicProvider; let agent = Agent::new(AnthropicProvider) .with_model("claude-sonnet-4-20250514") .with_api_key(std::env::var("ANTHROPIC_API_KEY").unwrap()); } ``` -------------------------------- ### Initialize an OpenAI Compatible Agent Source: https://yologdev.github.io/yoagent/getting-started/quick-start.html Uses OpenAiCompatProvider for services like OpenAI, xAI, Groq, and others that follow the OpenAI API specification. ```rust use yoagent::{Agent, AgentEvent}; use yoagent::provider::OpenAiCompatProvider; use yoagent::tools::default_tools; #[tokio::main] async fn main() { let mut agent = Agent::new(OpenAiCompatProvider) .with_system_prompt("You are a helpful assistant.") .with_model("gpt-4o") .with_api_key(std::env::var("OPENAI_API_KEY").unwrap()) .with_tools(default_tools()); let mut rx = agent.prompt("What is 2 + 2?").await; while let Some(event) = rx.recv().await { match event { AgentEvent::MessageUpdate { delta, .. } => { if let yoagent::StreamDelta::Text { delta } = delta { print!("{}", delta); } } AgentEvent::AgentEnd { .. } => println!(), _ => {} } } } ``` -------------------------------- ### GoogleProvider Configuration Source: https://yologdev.github.io/yoagent/providers/google.html This snippet shows how to initialize the Agent with the GoogleProvider for Google AI Studio. ```APIDOC ## Initialize Agent with GoogleProvider ### Description This example demonstrates how to create an `Agent` instance using the `GoogleProvider` for Google AI Studio, specifying the model and API key. ### Method Initialization ### Endpoint N/A (Library Usage) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use yoagent::provider::GoogleProvider; use yoagent::Agent; let agent = Agent::new(GoogleProvider) .with_model("gemini-2.0-flash") .with_api_key(std::env::var("GOOGLE_API_KEY").unwrap()); ``` ### Response #### Success Response (200) N/A (Initialization) #### Response Example N/A ``` -------------------------------- ### Initialize BedrockProvider Source: https://yologdev.github.io/yoagent/providers/bedrock.html Configures the agent with the Bedrock provider and specifies the model and authentication credentials. ```rust #![allow(unused)] fn main() { use yoagent::provider::BedrockProvider; let agent = Agent::new(BedrockProvider) .with_model("anthropic.claude-3-sonnet-20240229-v1:0") .with_api_key("ACCESS_KEY:SECRET_KEY"); // or ACCESS_KEY:SECRET_KEY:SESSION_TOKEN } ``` -------------------------------- ### Agent Initialization Source: https://yologdev.github.io/yoagent/print.html Provides a high-level stateful wrapper around the agent loop and details on agent creation. ```APIDOC ## Agent Initialization ### Description High-level stateful wrapper around the agent loop. ### `Agent::new()` #### Description Creates a new agent with the given stream provider. #### Signature `Agent::new(provider: impl StreamProvider + 'static) -> Self` ``` -------------------------------- ### Custom OpenAI Compatible Provider Source: https://yologdev.github.io/yoagent/providers/openai-compat.html Shows how to define a custom provider configuration by implementing `OpenAiCompat` with specific flags and default settings. ```rust #![allow(unused)] fn main() { impl OpenAiCompat { pub fn my_provider() -> Self { Self { supports_usage_in_streaming: true, // set flags as needed... ..Default::default() } } } } ``` -------------------------------- ### Initialize ModelConfig with Convenience Constructors Source: https://yologdev.github.io/yoagent/providers/overview.html Use these constructors to quickly instantiate ModelConfig for various supported LLM providers. ```rust #![allow(unused)] fn main() { let anthropic = ModelConfig::anthropic("claude-sonnet-4-20250514", "Claude Sonnet 4"); let openai = ModelConfig::openai("gpt-4o", "GPT-4o"); let google = ModelConfig::google("gemini-2.0-flash", "Gemini 2.0 Flash"); let xai = ModelConfig::xai("grok-3-mini", "Grok 3 Mini"); let groq = ModelConfig::groq("llama-3.3-70b-versatile", "Llama 3.3 70B"); let deepseek = ModelConfig::deepseek("deepseek-chat", "DeepSeek Chat"); let mistral = ModelConfig::mistral("mistral-large-latest", "Mistral Large"); let minimax = ModelConfig::minimax("MiniMax-Text-01", "MiniMax Text 01"); let zai = ModelConfig::zai("glm-4.7", "GLM 4.7"); let local = ModelConfig::local("http://localhost:1234/v1", "my-model"); } ``` -------------------------------- ### Configure Azure OpenAI Provider Source: https://yologdev.github.io/yoagent/print.html Initialize the AzureOpenAiProvider and configure authentication headers and base URLs. ```rust #![allow(unused)] fn main() { use yoagent::provider::AzureOpenAiProvider; let agent = Agent::new(AzureOpenAiProvider) .with_model("gpt-4o") .with_api_key(std::env::var("AZURE_OPENAI_API_KEY").unwrap()); } ``` ```text api-key: {your_api_key} ``` ```text https://{resource}.openai.azure.com/openai/deployments/{deployment} ``` -------------------------------- ### Configure AWS Bedrock Provider Source: https://yologdev.github.io/yoagent/print.html Initialize the BedrockProvider using colon-separated credentials. ```rust #![allow(unused)] fn main() { use yoagent::provider::BedrockProvider; let agent = Agent::new(BedrockProvider) .with_model("anthropic.claude-3-sonnet-20240229-v1:0") .with_api_key("ACCESS_KEY:SECRET_KEY"); // or ACCESS_KEY:SECRET_KEY:SESSION_TOKEN } ``` ```text {access_key_id}:{secret_access_key} {access_key_id}:{secret_access_key}:{session_token} ``` -------------------------------- ### Model Configuration with Custom Provider Source: https://yologdev.github.io/yoagent/providers/openai-compat.html Illustrates creating a `ModelConfig` that utilizes a custom OpenAI-compatible provider, specifying API protocol, base URL, and compatibility settings. ```rust let config = ModelConfig { id: "my-model".into(), name: "My Model".into(), api: ApiProtocol::OpenAiCompletions, provider: "my-provider".into(), base_url: "https://api.myprovider.com/v1".into(), compat: Some(OpenAiCompat::my_provider()), // ... }; ``` -------------------------------- ### Manual Context Budget Derivation Source: https://yologdev.github.io/yoagent/concepts/context-management.html Manually derive a `ContextConfig` from a specified context window size, automatically calculating the compaction budget. ```rust #![allow(unused)] fn main() { let config = ContextConfig::from_context_window(1_000_000); // config.max_context_tokens == 800_000 } ``` -------------------------------- ### SearchTool Configuration Source: https://yologdev.github.io/yoagent/reference/tools.html Configure `SearchTool` with a root directory, maximum results, and timeout. Defaults are provided for most fields. ```rust #![allow(unused)] fn main() { pub struct SearchTool { pub root: Option, pub max_results: usize, pub timeout: Duration, } } ``` -------------------------------- ### Define OpenAiCompat Configuration Source: https://yologdev.github.io/yoagent/print.html Structure for defining behavioral differences across OpenAI-compatible providers. ```rust #![allow(unused)] fn main() { pub struct OpenAiCompat { pub supports_store: bool, pub supports_developer_role: bool, pub supports_reasoning_effort: bool, pub supports_usage_in_streaming: bool, pub max_tokens_field: MaxTokensField, // MaxTokens or MaxCompletionTokens pub requires_tool_result_name: bool, pub requires_assistant_after_tool_result: bool, pub thinking_format: ThinkingFormat, // OpenAi, Xai, or Qwen } } ``` -------------------------------- ### Implement Custom OpenAiCompat Provider Source: https://yologdev.github.io/yoagent/print.html Add a custom constructor to OpenAiCompat to support new providers. ```rust #![allow(unused)] fn main() { impl OpenAiCompat { pub fn my_provider() -> Self { Self { supports_usage_in_streaming: true, // set flags as needed... ..Default::default() } } } } ``` -------------------------------- ### Implement a Streaming Deployment Tool Source: https://yologdev.github.io/yoagent/concepts/tools.html Defines a custom tool that uses the ToolContext to stream progress updates to the UI while returning a final result to the LLM. ```rust use yoagent::agent::Agent; use yoagent::provider::AnthropicProvider; use yoagent::types::*; /// A tool that deploys an app and streams each step. struct DeployTool; #[async_trait] impl AgentTool for DeployTool { fn name(&self) -> &str { "deploy" } fn label(&self) -> &str { "Deploy App" } fn description(&self) -> &str { "Deploy the application to production." } fn parameters_schema(&self) -> serde_json::Value { serde_json::json!({ "type": "object", "properties": { "env": { "type": "string", "description": "Target environment" } }, "required": ["env"] }) } async fn execute( &self, params: serde_json::Value, ctx: ToolContext, ) -> Result { let env = params["env"].as_str().unwrap_or("staging"); let steps = ["Building image", "Running tests", "Pushing to registry", "Rolling out"]; for (i, step) in steps.iter().enumerate() { if ctx.cancel.is_cancelled() { return Err(ToolError::Cancelled); } // Stream each step to the UI if let Some(ref cb) = &ctx.on_update { cb(ToolResult { content: vec![Content::Text { text: format!("[{}/{}] {}...", i + 1, steps.len(), step), }], details: serde_json::json!({ "step": i + 1, "total": steps.len(), "phase": step, }), }); } // Simulate work tokio::time::sleep(std::time::Duration::from_secs(2)).await; } // Only this final result is sent to the LLM Ok(ToolResult { content: vec![Content::Text { text: format!("Successfully deployed to {}", env), }], details: serde_json::json!({"env": env, "status": "success"}), }) } } #[tokio::main] async fn main() { let mut agent = Agent::new(AnthropicProvider) .with_system_prompt("You are a deployment assistant.") .with_model("claude-sonnet-4-20250514") .with_api_key(std::env::var("ANTHROPIC_API_KEY").unwrap()) .with_tools(vec![Box::new(DeployTool)]); let mut rx = agent.prompt("Deploy to production").await; while let Some(event) = rx.recv().await { match event { // LLM text streaming AgentEvent::MessageUpdate { delta: StreamDelta::Text { delta }, .. } => print!("{}", delta), // Tool progress streaming AgentEvent::ToolExecutionStart { tool_name, .. } => { println!("\nšŸš€ Starting {}...", tool_name); } AgentEvent::ToolExecutionUpdate { partial_result, .. } => { if let Some(Content::Text { text }) = partial_result.content.first() { println!(" {}", text); } } AgentEvent::ToolExecutionEnd { tool_name, is_error, .. } => { if is_error { println!(" āŒ {} failed", tool_name); } else { println!(" āœ… {} complete", tool_name); } } AgentEvent::ProgressMessage { text, .. } => { println!(" šŸ’¬ {}", text); } AgentEvent::AgentEnd { .. } => break, _ => {} } } } ``` -------------------------------- ### Create a User Message Source: https://yologdev.github.io/yoagent/concepts/messages-events.html Demonstrates the convenience constructor for creating a user message with simple text content. ```rust #![allow(unused)] fn main() { let msg = Message::user("Hello, world!"); } ``` -------------------------------- ### Create an Extension Message Source: https://yologdev.github.io/yoagent/concepts/messages-events.html Shows how to create an ExtensionMessage with a specific kind and JSON data, then wrap it in an AgentMessage. ```rust #![allow(unused)] fn main() { let ext = ExtensionMessage::new("status_update", serde_json::json!({"status": "running"})); let msg = AgentMessage::Extension(ext); } ``` -------------------------------- ### Create Extension Messages Source: https://yologdev.github.io/yoagent/print.html Use the convenience constructor to create extension messages and wrap them in AgentMessage. ```rust let ext = ExtensionMessage::new("status_update", serde_json::json!({"status": "running"})); let msg = AgentMessage::Extension(ext); ``` -------------------------------- ### ListFilesTool Configuration Source: https://yologdev.github.io/yoagent/reference/tools.html Configure `ListFilesTool` with maximum results and timeout. Defaults are provided for these fields. ```rust #![allow(unused)] fn main() { pub struct ListFilesTool { pub max_results: usize, pub timeout: Duration, } } ``` -------------------------------- ### Manual Context Compaction Strategy Source: https://yologdev.github.io/yoagent/concepts/context-management.html Provides building blocks for implementing custom context compaction strategies, either proactively before prompting or reactively after catching overflow errors. ```rust #![allow(unused)] fn main() { // Proactive: check before each prompt let tokens = tracker.estimate_context_tokens(agent.messages()); if tokens > context_window - reserve { let compacted = compact_messages(agent.messages().to_vec(), &config); agent.replace_messages(compacted); } // Reactive: catch overflow errors // ... on ContextOverflow or message.is_context_overflow(): // compact, then retry with agent.continue_loop() } ``` -------------------------------- ### Register Custom Tools Source: https://yologdev.github.io/yoagent/concepts/tools.html Shows how to add custom tools to the agent's toolset alongside default tools. ```rust #![allow(unused)] fn main() { use yoagent::tools::default_tools; let mut tools = default_tools(); tools.push(Box::new(WeatherTool)); let agent = Agent::new(provider).with_tools(tools); } ``` -------------------------------- ### Handle Agent Events for Tool Progress Source: https://yologdev.github.io/yoagent/concepts/tools.html Demonstrates how to process different agent events, including `ToolExecutionStart`, `ToolExecutionUpdate` for progress, and `ToolExecutionEnd`, from an event stream. ```rust #![allow(unused)] fn main() { while let Some(event) = rx.recv().await { match event { AgentEvent::ToolExecutionStart { tool_name, .. } => { println!("ā³ {} started", tool_name); } AgentEvent::ToolExecutionUpdate { tool_name, partial_result, .. } => { // Show progress in your UI if let Some(Content::Text { text }) = partial_result.content.first() { println!(" šŸ“Š {}: {}", tool_name, text); } } AgentEvent::ToolExecutionEnd { tool_name, is_error, .. } => { println!("{} {}", if is_error { "āŒ" } else { "āœ…" }, tool_name); } AgentEvent::ProgressMessage { tool_name, text, .. } => { println!(" šŸ’¬ {}: {}", tool_name, text); } _ => {} // Ignore other events } } } ``` -------------------------------- ### Emit Lightweight Progress Messages Source: https://yologdev.github.io/yoagent/concepts/tools.html Shows how to use the `ctx.on_progress` callback to send simple, text-only progress messages during tool execution. ```rust async fn execute(params: serde_json::Value, ctx: ToolContext) -> Result { if let Some(ref progress) = &ctx.on_progress { progress("Starting analysis...".into()); } // ... do work ... if let Some(ref progress) = &ctx.on_progress { progress("Almost done...".into()); } Ok(ToolResult { /* ... */ }) } ``` -------------------------------- ### Initialize an Anthropic Agent Source: https://yologdev.github.io/yoagent/getting-started/quick-start.html Configures an agent using the AnthropicProvider with system prompts, model selection, and default tools. ```rust use yoagent::{Agent, AgentEvent, StreamDelta}; use yoagent::provider::AnthropicProvider; use yoagent::tools::default_tools; #[tokio::main] async fn main() { let mut agent = Agent::new(AnthropicProvider) .with_system_prompt("You are a helpful coding assistant.") .with_model("claude-sonnet-4-20250514") .with_api_key(std::env::var("ANTHROPIC_API_KEY").unwrap()) .with_tools(default_tools()); let mut rx = agent.prompt("List the files in the current directory").await; while let Some(event) = rx.recv().await { match event { AgentEvent::MessageUpdate { delta, .. } => match delta { StreamDelta::Text { delta } => print!("{}", delta), StreamDelta::Thinking { delta } => print!("[thinking] {}", delta), _ => {} }, AgentEvent::ToolExecutionStart { tool_name, .. } => { println!("\n→ Running tool: {}", tool_name); } AgentEvent::ToolExecutionEnd { tool_name, result, is_error, .. } => { if is_error { println!(" āœ— {} failed", tool_name); } else { println!(" āœ“ {} done", tool_name); } } AgentEvent::AgentEnd { .. } => { println!("\n\nDone."); } _ => {} } } } ``` -------------------------------- ### Callbacks Source: https://yologdev.github.io/yoagent/print.html Methods for setting up callbacks that are triggered at different stages of the agent's execution, such as before or after a turn, or on error. ```APIDOC ## Callbacks ### Description Methods for setting up callbacks. ### Methods - `on_before_turn(f: Fn(&[AgentMessage], usize) -> bool) -> Self`: Called before each LLM call; return `false` to abort. - `on_after_turn(f: Fn(&[AgentMessage], &Usage)) -> Self`: Called after each LLM response and tool execution. - `on_error(f: Fn(&str)) -> Self`: Called when the LLM returns `StopReason::Error`. ``` -------------------------------- ### Initialize a SubAgentTool Source: https://yologdev.github.io/yoagent/concepts/sub-agents.html Configures a sub-agent with specific tools, system prompts, and model settings. Requires an API key and provider instance. ```rust #![allow(unused)] fn main() { use std::sync::Arc; use yoagent::sub_agent::SubAgentTool; use yoagent::provider::AnthropicProvider; use yoagent::tools; let researcher = SubAgentTool::new("researcher", Arc::new(AnthropicProvider)) .with_description("Searches and reads files to gather information.") .with_system_prompt("You are a research assistant. Be thorough and concise.") .with_model("claude-sonnet-4-20250514") .with_api_key(&api_key) .with_tools(vec![ Arc::new(tools::ReadFileTool::new()), Arc::new(tools::SearchTool::new()), ]) .with_max_turns(10); } ``` -------------------------------- ### Load Agent Tools from OpenAPI URL Source: https://yologdev.github.io/yoagent/reference/api.html Fetches an OpenAPI specification from a URL and adds its tools. Requires the 'openapi' feature. ```rust async with_openapi_url(url, config, filter) -> Result ``` -------------------------------- ### Connect an MCP server via Stdio Source: https://yologdev.github.io/yoagent/guides/mcp.html Spawns an MCP server process and registers its tools using the Stdio transport. ```rust use yoagent::Agent; use yoagent::provider::AnthropicProvider; #[tokio::main] async fn main() -> Result<(), Box> { let mut agent = Agent::new(AnthropicProvider) .with_system_prompt("You are a helpful assistant with file access.") .with_model("claude-sonnet-4-20250514") .with_api_key(std::env::var("ANTHROPIC_API_KEY")?) .with_mcp_server_stdio( "npx", &["-y", "@modelcontextprotocol/server-filesystem", "/tmp"], None, ) .await?; let rx = agent.prompt("List files in /tmp").await; // handle events... Ok(()) } ``` -------------------------------- ### Combine OpenAPI with Other Tools Source: https://yologdev.github.io/yoagent/guides/openapi.html Integrate OpenAPI tools with built-in tools and MCP servers. ```rust #![allow(unused)] fn main() { use yoagent::tools::default_tools; let agent = Agent::new(provider) .with_tools(default_tools()) .with_openapi_file("github.yaml", github_config, &github_filter).await? .with_mcp_server_stdio("db-server", &[], None).await?; } ``` -------------------------------- ### Agent Prompt Methods Source: https://yologdev.github.io/yoagent/print.html Methods for initiating agent interactions, either by spawning a concurrent loop or providing a custom sender channel. ```APIDOC ## agent.prompt() ### Description Spawns the agent loop concurrently and returns a receiver immediately, allowing events to stream in real-time. ### Method Async ### Parameters #### Request Body - **prompt** (string) - Required - The user input prompt. ### Response - **receiver** (mpsc::UnboundedReceiver) - A receiver for real-time AgentEvent streaming. ``` ```APIDOC ## agent.prompt_with_sender() ### Description Executes a prompt using a provided sender channel, useful for sharing a sender across multiple tasks. ### Method Async ### Parameters #### Request Body - **prompt** (string) - Required - The user input prompt. - **tx** (mpsc::UnboundedSender) - Required - The sender channel for AgentEvent streaming. ``` -------------------------------- ### Convenience Constructors for ModelConfig Source: https://yologdev.github.io/yoagent/print.html Provides convenience constructors for creating ModelConfig instances for various LLM providers like Anthropic, OpenAI, Google, and local models. ```rust let anthropic = ModelConfig::anthropic("claude-sonnet-4-20250514", "Claude Sonnet 4"); let openai = ModelConfig::openai("gpt-4o", "GPT-4o"); let google = ModelConfig::google("gemini-2.0-flash", "Gemini 2.0 Flash"); let xai = ModelConfig::xai("grok-3-mini", "Grok 3 Mini"); let groq = ModelConfig::groq("llama-3.3-70b-versatile", "Llama 3.3 70B"); let deepseek = ModelConfig::deepseek("deepseek-chat", "DeepSeek Chat"); let mistral = ModelConfig::mistral("mistral-large-latest", "Mistral Large"); let minimax = ModelConfig::minimax("MiniMax-Text-01", "MiniMax Text 01"); let zai = ModelConfig::zai("glm-4.7", "GLM 4.7"); let local = ModelConfig::local("http://localhost:1234/v1", "my-model"); ``` -------------------------------- ### OpenAiCompatProvider Integration Source: https://yologdev.github.io/yoagent/print.html Configuration for OpenAI-compatible APIs including xAI, Groq, Cerebras, OpenRouter, Mistral, and DeepSeek. ```APIDOC ## OpenAiCompatProvider Integration ### Description Provides a unified interface for OpenAI-compatible chat completion APIs. Requires a `ModelConfig` with specific compatibility flags defined in `OpenAiCompat`. ### Request Example ```rust use yoagent::provider::{OpenAiCompatProvider, ModelConfig}; let agent = Agent::new(OpenAiCompatProvider) .with_model("gpt-4o") .with_api_key(std::env::var("OPENAI_API_KEY").unwrap()); ``` ### Compatibility Configuration - **supports_store**: bool - **supports_developer_role**: bool - **supports_reasoning_effort**: bool - **thinking_format**: Enum (OpenAi, Xai, Qwen) ``` -------------------------------- ### Context Configuration Source: https://yologdev.github.io/yoagent/print.html Controls context window compaction and provides methods for deriving configuration from model context windows. ```APIDOC ## Context Configuration ### Description Controls context window compaction. ### Struct: ContextConfig - **max_context_tokens** (usize) - Maximum context tokens. Default: 100,000. - **system_prompt_tokens** (usize) - Tokens reserved for the system prompt. Default: 4,000. - **keep_recent** (usize) - Number of recent messages to keep. Default: 10. - **keep_first** (usize) - Number of initial messages to keep. Default: 2. - **tool_output_max_lines** (usize) - Maximum lines for tool output. Default: 50. When `context_config` is not explicitly set, it is automatically derived from `ModelConfig.context_window` (80% for context, 20% reserved for output). If neither is set, `ContextConfig::default()` (100K) is used. ### Methods - **from_context_window(context_window: usize) -> ContextConfig** Derive context configuration from a model's context window size. ``` -------------------------------- ### Register Custom Providers Source: https://yologdev.github.io/yoagent/providers/overview.html Create a custom registry and register specific providers to the ApiProtocol. ```rust #![allow(unused)] fn main() { let mut registry = ProviderRegistry::new(); registry.register(ApiProtocol::AnthropicMessages, AnthropicProvider); } ``` -------------------------------- ### Initialize Agent Source: https://yologdev.github.io/yoagent/print.html Creates a new agent instance using a provided stream provider. ```rust #![allow(unused)] fn main() { let agent = Agent::new(provider); } ``` -------------------------------- ### Context Configuration Options Source: https://yologdev.github.io/yoagent/concepts/context-management.html Defines configuration options for context management, including maximum context tokens, system prompt tokens, and the number of recent/first messages to keep. ```rust #![allow(unused)] fn main() { pub struct ContextConfig { pub max_context_tokens: usize, // Default: 100,000 pub system_prompt_tokens: usize, // Default: 4,000 pub keep_recent: usize, // Default: 10 pub keep_first: usize, // Default: 2 pub tool_output_max_lines: usize, // Default: 50 } } ```