Skip to main content

Overview

Chat enables you to build stateful conversational sessions with automatic memory management, cost tracking, and session analytics. It wraps an Agent with session persistence, memory integration, and usage metrics.

Key Features

  • Session Management: Unique session/user identification with state tracking
  • Memory Integration: Conversation history, summarization, and user profile analysis
  • Cost Tracking: Real-time token usage and cost monitoring
  • Streaming Support: Both blocking and streaming response modes
  • History Manipulation: Delete messages, remove attachments
  • Error Handling: Built-in retry mechanisms with exponential backoff

Example

import asyncio
from upsonic import Agent, Chat


async def main():
    agent = Agent("anthropic/claude-sonnet-4-5")

    chat = Chat(
        session_id="user123_session1",
        user_id="user123",
        agent=agent
    )

    response = await chat.invoke("Hello, how are you?")
    print(response)

    print(f"Total cost: ${chat.total_cost:.4f}")
    print(f"Messages: {len(chat.all_messages)}")


if __name__ == "__main__":
    asyncio.run(main())