전체 그래프
Agno

Agno Session State

aiagent-frameworkagnostate

상위: Agno

요약

Agno의 Session State는 에이전트와 워크플로우에서 실행 간 상태를 유지하는 딕셔너리이다. 인스트럭션에서 {key} 템플릿으로 참조하고, 도구에서 RunContext로 읽기/쓰기하며, DB 연결 시 세션 종료 후에도 영속화된다. Agent, Workflow, Team 모두 동일한 패턴을 사용한다.

Agent Session State

from agno.agent import Agent
from agno.db.sqlite import SqliteDb
from agno.run import RunContext

def add_item(run_context: RunContext, item: str) -> str:
    """Add an item to the shopping list."""
    run_context.session_state["shopping_list"].append(item)
    return f"Added {item}"

agent = Agent(
    db=SqliteDb(db_file="tmp/state.db"),
    session_state={"shopping_list": []},       # 초기 상태
    tools=[add_item],
    instructions="Shopping list: {shopping_list}",  # 템플릿 참조
)

agent.print_response("Add milk and eggs")
print(agent.get_session_state())  # {'shopping_list': ['milk', 'eggs']}

Workflow Session State

워크플로우 수준의 딕셔너리로 스텝 간 상태를 공유한다. Condition evaluator와 executor 함수에서 session_state 파라미터로 접근:

from agno.workflow.workflow import Workflow
from agno.workflow.step import Step
from agno.workflow.types import StepInput, StepOutput

def mark_greeted(step_input: StepInput, session_state: dict) -> StepOutput:
    session_state["has_been_greeted"] = True
    session_state["greeting_count"] = session_state.get("greeting_count", 0) + 1
    return StepOutput(content="User greeted")

# Condition에서도 session_state 접근 가능
def check_greeted(step_input: StepInput, session_state: dict) -> bool:
    return session_state.get("has_been_greeted", False)

workflow = Workflow(
    name="Stateful Workflow",
    session_state={
        "has_been_greeted": False,
        "greeting_count": 0,
    },
    steps=[...],
)

특징

특징설명
초기화session_state={...}로 기본값 설정
인스트럭션 참조{key} 템플릿으로 시스템 메시지에 자동 주입
도구에서 접근run_context.session_state로 읽기/쓰기
외부 조회agent.get_session_state(session_id=...)로 조회
영속화db 설정 시 세션 종료 후에도 유지
Workflow 공유모든 스텝, Condition evaluator에서 공유

RunContext — 런타임 정보 접근

도구와 인스트럭션 함수에서 RunContext를 통해 런타임 정보에 접근한다:

필드설명
session_state세션 상태 딕셔너리
user_id현재 사용자 ID
session_id현재 세션 ID
dependencies주입된 의존성 딕셔너리

동적 인스트럭션에서 활용

from agno.run.context import RunContext

def get_instructions(run_context: RunContext) -> str:
    user_id = run_context.session_state.get("current_user_id")
    if user_id:
        return f"You are assisting user {user_id}. Be personalized."
    return "You are a general assistant."

agent = Agent(instructions=get_instructions)

Tool Hooks에서 활용

from agno.run import RunContext
from typing import Any, Dict

def customer_hook(run_context: RunContext, arguments: Dict[str, Any]):
    if run_context.session_state is None:
        run_context.session_state = {}
    cust_id = arguments.get("customer_id")
    run_context.session_state["customer_profiles"][cust_id] = {"name": arguments.get("name")}
    return f"Customer {cust_id} created"

agent = Agent(
    tool_hooks=[customer_hook],
    session_state={"customer_profiles": {}},
)

Session State vs Memory vs Storage

Session StateMemoryStorage
범위세션 내 실행 간세션 간 사용자 정보세션 상태 DB 영속화
접근run_context.session_stateMemoryTools / 자동db 설정
용도임시 상태, 카운터, 플래그사용자 선호도, 사실대화 히스토리, 세션 복원
생명주기세션 동안 (DB 없으면 휘발)영구 보존영구 보존

관련 개념