Skip to main content

Overview

The InvocationContext class represents the data and state of a single agent invocation. It tracks the execution lifecycle, manages services, handles cost tracking, and provides context propagation for multi-agent workflows. Location: @iqai/adk package, exported from packages/adk/src/agents/invocation-context.ts:124

Key Concepts

Invocation Hierarchy

An invocation:
  1. Starts with a user message and ends with a final response
  2. Can contain one or multiple agent calls
  3. Is handled by runner.runAsync()
  4. Runs an agent until it doesn’t request transfer to another agent
An agent call:
  1. Is handled by agent.run()
  2. Ends when agent.run() completes
An LLM agent call:
  • Contains one or multiple steps
  • Runs steps in a loop until:
    • A final response is generated
    • The agent transfers to another agent
    • endInvocation is set to true
A step:
  1. Calls the LLM once and yields its response
  2. Calls tools if requested and yields their responses
  3. Ends when done calling LLM and tools, or if endInvocation is set to true
┌─────────────────────── invocation ──────────────────────────┐
┌──────────── llm_agent_call_1 ────────────┐ ┌─ agent_call_2 ─┐
┌──── step_1 ────────┐ ┌───── step_2 ──────┐
[llm_generate] [execute_tool] [llm_generate] [transfer]

Constructor

options
object
required
Configuration options for the invocation context
Constructor Options:
options.sessionService
BaseSessionService
required
Session service for managing conversation state
options.agent
BaseAgent
required
The current agent for this context
options.session
Session
required
The current session instance
options.pluginManager
PluginManager
required
Plugin manager for lifecycle hooks
options.invocationId
string
Unique invocation ID (auto-generated if not provided)
options.branch
string
Branch identifier for multi-agent workflows (format: “agent_1.agent_2.agent_3”)
options.userContent
Content
The user content that started this invocation
options.memoryService
MemoryService
Memory service for long-term storage
options.artifactService
BaseArtifactService
Artifact service for file management
options.endInvocation
boolean
default:"false"
Whether to end this invocation
options.liveRequestQueue
LiveRequestQueue
Queue for receiving live requests
options.activeStreamingTools
Record<string, ActiveStreamingTool>
Running streaming tools of this invocation
options.transcriptionCache
TranscriptionEntry[]
Cache for audio/video transcription data
options.runConfig
RunConfig
Runtime configuration for this invocation
options.contextCacheConfig
ContextCacheConfig
Context caching configuration
options.transferContext
TransferContext
Transfer context for multi-agent workflows
options.spanCounters
SpanCounters
Telemetry span counters (llm, tool, agent)
import { InvocationContext, PluginManager } from "@iqai/adk";

const context = new InvocationContext({
  sessionService: mySessionService,
  agent: myAgent,
  session: mySession,
  pluginManager: new PluginManager(plugins),
  invocationId: "e-123abc",
  branch: "coordinator.researcher"
});
Location: packages/adk/src/agents/invocation-context.ts:221

Properties

Readonly Properties

invocationId
string
Unique identifier for this invocation.
sessionService
BaseSessionService
Session service instance.
memoryService
MemoryService | undefined
Memory service instance if configured.
artifactService
BaseArtifactService | undefined
Artifact service instance if configured.
pluginManager
PluginManager
Plugin manager for lifecycle hooks.
branch
string | undefined
Branch identifier showing the agent hierarchy path (e.g., “agent_1.agent_2.agent_3”). Used when sub-agents shouldn’t see peer agents’ conversation history.
session
Session
Current session instance containing conversation history and state.
userContent
Content | undefined
The user content that started this invocation.
contextCacheConfig
ContextCacheConfig | undefined
Context caching configuration. When present, enables reuse of cached LLM context across agent calls.

Mutable Properties

agent
BaseAgent
The current agent for this context.
endInvocation
boolean
Set to true in callbacks or tools to terminate this invocation.
// In a tool or callback
context.endInvocation = true; // Stops the invocation
liveRequestQueue
LiveRequestQueue | undefined
Queue to receive live audio/video requests.
activeStreamingTools
Record<string, ActiveStreamingTool> | undefined
Currently running streaming tools.
transcriptionCache
TranscriptionEntry[] | undefined
Cache for audio/video transcription data.
runConfig
RunConfig | undefined
Runtime configuration for this invocation.
transferContext
TransferContext | undefined
Transfer context tracking agent transfer chain for multi-agent workflows.

Computed Properties

appName (getter)

Gets the application name from the session. Returns: string
const appName = context.appName;
Location: packages/adk/src/agents/invocation-context.ts:266

userId (getter)

Gets the user ID from the session. Returns: string
const userId = context.userId;
Location: packages/adk/src/agents/invocation-context.ts:273

Methods

incrementLlmCallCount()

Tracks the number of LLM calls made and enforces the limit if configured. Throws: LlmCallsLimitExceededError if the limit is exceeded.
context.incrementLlmCallCount();
// Increments counter and checks against runConfig.maxLlmCalls
Location: packages/adk/src/agents/invocation-context.ts:282

nextLlmSpanIndex()

Returns the next LLM span index for telemetry. Returns: number
const spanIndex = context.nextLlmSpanIndex();
// Returns: 1, 2, 3, ...
Location: packages/adk/src/agents/invocation-context.ts:291

nextToolSpanIndex()

Returns the next tool span index for telemetry. Returns: number
const spanIndex = context.nextToolSpanIndex();
Location: packages/adk/src/agents/invocation-context.ts:298

nextAgentSpanIndex()

Returns the next agent span index for telemetry. Returns: number
const spanIndex = context.nextAgentSpanIndex();
Location: packages/adk/src/agents/invocation-context.ts:305

getSpanCounters()

Exposes shared span counters for child contexts. Returns: SpanCounters
const counters = context.getSpanCounters();
// { llm: 3, tool: 5, agent: 2 }
Location: packages/adk/src/agents/invocation-context.ts:312

createChildContext()

Creates a child invocation context for a sub-agent. Inherits most properties from parent while updating agent-specific fields.
agent
BaseAgent
required
The sub-agent for the child context
Returns: InvocationContext
const childContext = parentContext.createChildContext(subAgent);
// childContext.branch = "parent.subAgent"
// childContext.invocationId = same as parent
// childContext.agent = subAgent
Location: packages/adk/src/agents/invocation-context.ts:319

Transfer Context

The TransferContext interface tracks multi-agent workflows:
interface TransferContext {
  /** Array of agent names in transfer order */
  transferChain: string[];
  
  /** Current depth in transfer chain (0 = root) */
  transferDepth: number;
  
  /** Name of the root agent that started the chain */
  rootAgentName: string;
  
  /** Span context of the root agent for linking */
  rootSpanContext?: SpanContext;
  
  /** Span context of the previous agent in the chain */
  previousSpanContext?: SpanContext;
}
Example:
// Root agent starts invocation
context.transferContext = {
  transferChain: ["coordinator"],
  transferDepth: 0,
  rootAgentName: "coordinator"
};

// After transfer to researcher
childContext.transferContext = {
  transferChain: ["coordinator", "researcher"],
  transferDepth: 1,
  rootAgentName: "coordinator"
};

// After researcher transfers to analyst
grandchildContext.transferContext = {
  transferChain: ["coordinator", "researcher", "analyst"],
  transferDepth: 2,
  rootAgentName: "coordinator"
};

Cost Management

The internal InvocationCostManager tracks invocation costs:
class InvocationCostManager {
  private _numberOfLlmCalls = 0;
  
  incrementAndEnforceLlmCallsLimit(runConfig?: RunConfig): void {
    this._numberOfLlmCalls += 1;
    
    if (runConfig?.maxLlmCalls > 0 && 
        this._numberOfLlmCalls > runConfig.maxLlmCalls) {
      throw new LlmCallsLimitExceededError(
        `Max number of llm calls limit of ${runConfig.maxLlmCalls} exceeded`
      );
    }
  }
}

Utility Functions

newInvocationContextId()

Generates a new invocation context ID. Returns: string
import { newInvocationContextId } from "@iqai/adk";

const id = newInvocationContextId();
// Returns: "e-550e8400-e29b-41d4-a716-446655440000"
Location: packages/adk/src/agents/invocation-context.ts:80

Exceptions

LlmCallsLimitExceededError

Thrown when the number of LLM calls exceeds the configured limit.
class LlmCallsLimitExceededError extends Error {
  constructor(message: string) {
    super(message);
    this.name = "LlmCallsLimitExceededError";
  }
}
Location: packages/adk/src/agents/invocation-context.ts:37

Usage Examples

import { InvocationContext, PluginManager } from "@iqai/adk";

const context = new InvocationContext({
  sessionService,
  agent: myAgent,
  session: mySession,
  pluginManager: new PluginManager([]),
  userContent: { parts: [{ text: "Hello" }] }
});

// Access session data
console.log(context.appName);
console.log(context.userId);
console.log(context.session.state);

// Track costs
context.incrementLlmCallCount();

Type Definitions

type SpanCounters = { 
  llm: number; 
  tool: number; 
  agent: number; 
};

interface TransferContext {
  transferChain: string[];
  transferDepth: number;
  rootAgentName: string;
  rootSpanContext?: SpanContext;
  previousSpanContext?: SpanContext;
}

See Also

  • BaseAgent - Base class that uses InvocationContext
  • AgentBuilder - Creates agents that run with InvocationContext
  • LlmAgent - LLM agent that uses InvocationContext

Build docs developers (and LLMs) love