adk_core/agent_invoker.rs
1use std::sync::Arc;
2
3use crate::{Agent, Content, EventStream, Result};
4use async_trait::async_trait;
5
6/// Starts an agent turn for a session, creating the session when it does not exist.
7///
8/// Callers that hand work to an agent from outside a conversation — a background trigger, a
9/// queue consumer, a scheduler — need one operation: "run this content through the agent and
10/// give me the events." They should not have to know which session service holds the session, or
11/// that a session must be registered before a turn can start.
12///
13/// `adk-runner` implements this for `Runner`, so a caller can accept `Arc<dyn AgentInvoker>` and
14/// stay independent of the runner's construction. Implementations are responsible for creating a
15/// missing session rather than failing, because an external event has no opportunity to register
16/// one first. Implementations that permit concurrent calls should also serialize turns targeting
17/// the same session until the returned event stream completes or is dropped.
18///
19/// # Example
20///
21/// ```rust,ignore
22/// use std::sync::Arc;
23/// use adk_core::{AgentInvoker, Content};
24///
25/// async fn on_event(invoker: Arc<dyn AgentInvoker>) -> adk_core::Result<()> {
26/// let mut events = invoker
27/// .invoke("system", "nightly-sweep", Content::new("user").with_text("run the sweep"))
28/// .await?;
29/// while let Some(event) = futures::StreamExt::next(&mut events).await {
30/// let _ = event?;
31/// }
32/// Ok(())
33/// }
34/// ```
35#[async_trait]
36pub trait AgentInvoker: Send + Sync {
37 /// Returns the agent this invoker executes when it can expose one.
38 ///
39 /// Wrappers that do not own an in-process agent may keep the default. Consumers use this to
40 /// align diagnostics and lifecycle metadata with the executable root without coupling to a
41 /// concrete runner type.
42 fn agent(&self) -> Option<Arc<dyn Agent>> {
43 None
44 }
45
46 /// Starts a turn for `(user_id, session_id)` with `content` and returns the event stream.
47 ///
48 /// # Errors
49 ///
50 /// Returns an error if either identifier fails validation, if the session cannot be created
51 /// or retrieved, or if invocation setup fails. Failures during agent execution are yielded
52 /// by the returned stream rather than returned here.
53 async fn invoke(
54 &self,
55 user_id: &str,
56 session_id: &str,
57 content: Content,
58 ) -> Result<EventStream>;
59}