openai_agents_rust/agent/
runtime.rs

1use crate::agent::traits::{Agent, AgentContext};
2use crate::client::OpenAiClient;
3use crate::config::Config;
4use crate::error::AgentError;
5use crate::plugin::loader::PluginRegistry;
6use crate::tools::registry::ToolRegistry;
7use std::sync::Arc;
8
9/// Runtime that holds a collection of agents and executes them.
10pub struct AgentRuntime {
11    pub agents: Vec<Arc<dyn Agent>>,
12    pub config: Arc<Config>,
13    pub client: Arc<OpenAiClient>,
14    pub plugins: Arc<PluginRegistry>,
15    pub tools: Arc<ToolRegistry>,
16}
17
18impl AgentRuntime {
19    /// Create a new runtime from a configuration.
20    pub fn new(config: Config) -> Self {
21        let config = Arc::new(config);
22        let client = Arc::new(OpenAiClient::new((*config).clone()));
23        let plugins = Arc::new(
24            PluginRegistry::load_from_dir(&config.plugins_path)
25                .unwrap_or_else(|_| PluginRegistry::new()),
26        );
27        let mut tools = ToolRegistry::new();
28        // Demo tool – uppercase
29        tools.register(crate::tools::function::FunctionTool::new(
30            "uppercase",
31            "Uppercase the input string. Expects JSON: {\"text\": string}",
32            |s| {
33                // Try to parse OpenAI tool call args as JSON: {"text": "..."}
34                let text = serde_json::from_str::<serde_json::Value>(s)
35                    .ok()
36                    .and_then(|v| {
37                        v.get("text")
38                            .and_then(|t| t.as_str())
39                            .map(|t| t.to_string())
40                    })
41                    .unwrap_or_else(|| s.to_string());
42                Ok(text.to_uppercase())
43            },
44        ));
45
46        Self {
47            agents: Vec::new(),
48            config,
49            client,
50            plugins,
51            tools: Arc::new(tools),
52        }
53    }
54
55    /// Register an agent with the runtime.
56    pub fn register<A: Agent + 'static>(&mut self, agent: A) {
57        self.agents.push(Arc::new(agent));
58    }
59
60    /// Start all registered agents.
61    pub async fn start(&self) -> Result<(), AgentError> {
62        let ctx = AgentContext {
63            config: Arc::clone(&self.config),
64            client: Arc::clone(&self.client),
65            plugins: Arc::clone(&self.plugins),
66            tools: Arc::clone(&self.tools),
67        };
68        for agent in &self.agents {
69            agent.run(&ctx).await?;
70        }
71        Ok(())
72    }
73}