Session Metrics
Accumulate metrics across multiple runs within a session using SessionMetrics.
1"""Session-level metrics that accumulate across multiple runs."""23from kern.agent import Agent4from kern.db.postgres import PostgresDb5from kern.models.openai import OpenAIChat6from rich.pretty import pprint78db_url = "postgresql+psycopg://ai:ai@localhost:5532/ai"9db = PostgresDb(db_url=db_url, session_table="agent_metrics_sessions")1011agent = Agent(12 model=OpenAIChat(id="gpt-4o-mini"),13 db=db,14 session_id="session_metrics_demo",15 add_history_to_context=True,16)1718if __name__ == "__main__":19 # First run20 run_output_1 = agent.run("What is the capital of France?")21 print("=" * 50)22 print("RUN 1 METRICS")23 print("=" * 50)24 pprint(run_output_1.metrics)2526 # Second run on the same session27 run_output_2 = agent.run("What about Germany?")28 print("=" * 50)29 print("RUN 2 METRICS")30 print("=" * 50)31 pprint(run_output_2.metrics)3233 # Session metrics aggregate both runs34 print("=" * 50)35 print("SESSION METRICS (accumulated)")36 print("=" * 50)37 session_metrics = agent.get_session_metrics()38 pprint(session_metrics)Run the Example
1# Clone and setup repo2git clone https://github.com/kern-ai/kern.git3cd kern/cookbook/02_agents/14_advanced45# Create and activate virtual environment6./scripts/demo_setup.sh7source .venvs/demo/bin/activate89python session_metrics.py