Runner

El tiempo de ejecución de adk-runner que orquesta la ejecución del agent.

Descripción general

El Runner gestiona el ciclo de vida completo de la ejecución del agent:

  • Gestión de Session (crear/recuperar Sessions)
  • Inyección de Memory (buscar e inyectar Memories relevantes)
  • Manejo de Artifact (acceso a Artifact con ámbito)
  • Transmisión de Event (procesar y reenviar Events)
  • Transferencias de Agent (manejar traspasos entre múltiples Agents)

Instalación

[dependencies]
adk-runner = "0.2.0"

RunnerConfig

Configura el runner con los servicios requeridos:

use adk_runner::{Runner, RunnerConfig};
use adk_session::InMemorySessionService;
use adk_artifact::InMemoryArtifactService;
use std::sync::Arc;

let config = RunnerConfig {
    app_name: "my_app".to_string(),
    agent: Arc::new(my_agent),
    session_service: Arc::new(InMemorySessionService::new()),
    artifact_service: Some(Arc::new(InMemoryArtifactService::new())),
    memory_service: None,
    run_config: None,
};

let runner = Runner::new(config)?;

Campos de configuración

CampoTipoRequeridoDescripción
app_nameStringIdentificador de la aplicación
agentArc<dyn Agent>Agent raíz a ejecutar
session_serviceArc<dyn SessionService>Backend de almacenamiento de Session
artifact_serviceOption<Arc<dyn ArtifactService>>NoAlmacenamiento de Artifact
memory_serviceOption<Arc<dyn Memory>>NoMemory a largo plazo
run_configOption<RunConfig>NoOpciones de ejecución

Ejecutando Agents

Ejecuta un agent con entrada de usuario:

use adk_core::Content;
use futures::StreamExt;

let user_content = Content::new("user").with_text("Hello!");

let mut stream = runner.run(
    "user-123".to_string(),
    "session-456".to_string(),
    user_content,
).await?;

while let Some(event) = stream.next().await {
    match event {
        Ok(e) => {
            if let Some(content) = e.content() {
                for part in &content.parts {
                    if let Some(text) = part.text() {
                        print!("{}", text);
                    }
                }
            }
        }
        Err(e) => eprintln!("Error: {}", e),
    }
}

Flujo de Ejecución

┌─────────────────────────────────────────────────────────────┐
│                     Runner.run()                            │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                  1. Recuperación de Sesión                  │
│                                                             │
│   SessionService.get(app_name, user_id, session_id)        │
│   → Crea una nueva sesión si no existe                      │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                  2. Selección de Agent                      │
│                                                             │
│   Verifica el estado de la sesión para el Agent activo      │
│   → Usa el Agent raíz o el Agent transferido                │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                3. Creación de Contexto                      │
│                                                             │
│   InvocationContext con:                                   │
│   - Session (mutable)                                       │
│   - Artifacts (con ámbito de sesión)                       │
│   - Memory (si está configurada)                            │
│   - Run config                                              │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                  4. Ejecución del Agent                     │
│                                                             │
│   agent.run(ctx) → EventStream                             │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                 5. Procesamiento de Eventos                 │
│                                                             │
│   Para cada evento:                                         │
│   - Actualiza el estado de la sesión                        │
│   - Maneja las transferencias                               │
│   - Reenvía al llamador                                     │
└─────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────┐
│                  6. Guardado de Sesión                      │
│                                                             │
│   SessionService.append_event(session, events)             │
└─────────────────────────────────────────────────────────────┘

InvocationContext

El contexto proporcionado a los Agent durante la ejecución:

pub trait InvocationContext: CallbackContext {
    /// The agent being executed
    fn agent(&self) -> Arc<dyn Agent>;
    
    /// Memory service (if configured)
    fn memory(&self) -> Option<Arc<dyn Memory>>;
    
    /// Current session
    fn session(&self) -> &dyn Session;
    
    /// Execution configuration
    fn run_config(&self) -> &RunConfig;
    
    /// Signal end of invocation
    fn end_invocation(&self);
    
    /// Check if invocation has ended
    fn ended(&self) -> bool;
}

RunConfig

Opciones de ejecución:

pub struct RunConfig {
    /// Streaming mode for responses
    pub streaming_mode: StreamingMode,
}

pub enum StreamingMode {
    /// No streaming, return complete response
    None,
    /// Server-Sent Events (default)
    SSE,
    /// Bidirectional streaming (realtime)
    Bidi,
}

Nota: Se planean campos adicionales como max_turns e include_history para futuras versiones.

Transferencias de Agent

El Runner maneja las transferencias multi-Agent automáticamente:

// In an agent's tool or callback
if should_transfer {
    // Set transfer in event actions
    ctx.set_actions(EventActions {
        transfer_to_agent: Some("specialist_agent".to_string()),
        ..Default::default()
    });
}

El Runner hará lo siguiente:

  1. Detectar la solicitud de transferencia en el evento.
  2. Encontrar el Agent de destino en sub_agents.
  3. Actualizar el estado de Session con el nuevo Agent activo.
  4. Continuar la ejecución con el nuevo Agent.

Integración con Launcher

El Launcher utiliza un Runner internamente:

// Launcher creates Runner with default services
Launcher::new(agent)
    .app_name("my_app")
    .run()
    .await?;

// Equivalent to:
let runner = Runner::new(RunnerConfig {
    app_name: "my_app".to_string(),
    agent,
    session_service: Arc::new(InMemorySessionService::new()),
    artifact_service: Some(Arc::new(FileArtifactService::new("./artifacts")?)),
    memory_service: None,
    run_config: None,
})?;

Uso Personalizado del Runner

Para escenarios avanzados, use Runner directamente:

use adk_runner::{Runner, RunnerConfig};
use adk_session::DatabaseSessionService;
use adk_artifact::S3ArtifactService;
use adk_memory::QdrantMemoryService;

// Production configuration
let config = RunnerConfig {
    app_name: "production_app".to_string(),
    agent: my_agent,
    session_service: Arc::new(DatabaseSessionService::new(db_pool)),
    artifact_service: Some(Arc::new(S3ArtifactService::new(s3_client))),
    memory_service: Some(Arc::new(QdrantMemoryService::new(qdrant_client))),
    run_config: None,  // Uses default SSE streaming
};

let runner = Runner::new(config)?;

// Use in HTTP handler
async fn chat_handler(runner: &Runner, request: ChatRequest) -> Response {
    let stream = runner.run(
        request.user_id,
        request.session_id,
        request.content,
    ).await?;
    
    // Stream events to client
    Response::sse(stream)
}

Anterior: ← Core Types | Siguiente: Launcher →