Skip to content

Context

The Context object is the shared memory of your application. It holds variables, conversation history, and state that flows between agents.

Purpose

Use Context to: - Pass initial data to an Agent or Workflow. - Store conversation history (messages). - Share state between multiple agents in a workflow.

Usage

Basic Usage

Initialize context with variables that your Agent's instructions might reference (e.g., {{ topic }}).

from yosrai import Context

# Create context with initial variables
ctx = Context(topic="AI Agents", user_name="Alice")

# Access variables
print(ctx.get("topic"))

# Add conversation messages manually
ctx.add_message("user", "Hello there!")

Typed Context

You can enforce strict typing by passing a Pydantic model class to the constructor.

from pydantic import BaseModel
from yosrai import Context

class MyState(BaseModel):
    count: int
    name: str

ctx = Context(schema=MyState, count=1, name="test")

# Valid
ctx.count = 2

# Raises ValueError
# ctx.count = "invalid" 

Serialization

You can save and load context to persist conversation state.

# Save to dictionary
state = ctx.to_dict()

# Restore from dictionary
new_ctx = Context.from_dict(state)

API Reference

yosrai.engine.core.context.Context

Bases: Generic[T]

A state container for the Workflow. Can be loosely typed (dict-like) or strictly typed (Pydantic model). Supports time-travel (snapshot/rollback).

__init__(schema=None, **kwargs)

get(key, default=None)

to_dict()