Skip to main content

Session manager for AI applications

Project description

chuk-ai-session-manager

Python 3.11+ License: MIT

The easiest way to add conversation tracking to any AI application.

Track conversations, monitor costs, and manage infinite context with just 3 lines of code. Built for production, designed for simplicity.

๐Ÿš€ 30-Second Start

uv add chuk-ai-session-manager
from chuk_ai_session_manager import track_conversation

# Track any AI conversation in one line
await track_conversation("Hello!", "Hi there! How can I help?")

That's it! ๐ŸŽ‰ Your conversation is now tracked with full observability.

โœจ Why Choose CHUK?

  • ๐Ÿ”ฅ Stupidly Simple: 3 lines to track any conversation
  • ๐Ÿ’ฐ Cost Smart: Automatic token counting and cost tracking
  • โ™พ๏ธ Infinite Context: No more "conversation too long" errors
  • ๐Ÿ”ง Any LLM: Works with OpenAI, Anthropic, local models, anything
  • ๐Ÿ“Š Full Observability: See exactly what's happening in your AI app
  • ๐Ÿš€ Production Ready: Used in real applications, not just demos

๐ŸŽฏ Perfect For

  • Building chatbots that remember conversations
  • Tracking LLM costs across your entire application
  • Managing long conversations without hitting token limits
  • Debugging AI applications with complete audit trails
  • Production AI systems that need reliable session management

๐Ÿ“ฑ Quick Examples

Track Any Conversation

from chuk_ai_session_manager import track_conversation

# Works with any LLM response
session_id = await track_conversation(
    user_message="What's the weather like?",
    ai_response="It's sunny and 75ยฐF in your area.",
    model="gpt-4",
    provider="openai"
)

Persistent Conversations

from chuk_ai_session_manager import SessionManager

# Create a conversation that remembers context
sm = SessionManager()

await sm.user_says("My name is Alice")
await sm.ai_responds("Nice to meet you, Alice!")

await sm.user_says("What's my name?")
await sm.ai_responds("Your name is Alice!")

# Get conversation stats
stats = await sm.get_stats()
print(f"Cost: ${stats['estimated_cost']:.6f}")
print(f"Tokens: {stats['total_tokens']}")

Infinite Context (Never Run Out of Space)

# Automatically handles conversations of any length
sm = SessionManager(
    infinite_context=True,          # ๐Ÿ”ฅ Magic happens here
    token_threshold=4000           # When to create new segment
)

# Keep chatting forever - context is preserved automatically
for i in range(100):  # This would normally hit token limits
    await sm.user_says(f"Question {i}: Tell me about AI")
    await sm.ai_responds("AI is fascinating...")

# Still works! Automatic summarization keeps context alive
conversation = await sm.get_conversation()
print(f"Full conversation: {len(conversation)} exchanges")

Cost Tracking (Know What You're Spending)

# Automatic cost monitoring across all interactions
sm = SessionManager()

await sm.user_says("Write a long story about dragons")
await sm.ai_responds("Once upon a time..." * 500)  # Long response

stats = await sm.get_stats()
print(f"๐Ÿ’ฐ That story cost: ${stats['estimated_cost']:.6f}")
print(f"๐Ÿ“Š Used {stats['total_tokens']} tokens")
print(f"๐Ÿ“ˆ {stats['user_messages']} user messages, {stats['ai_messages']} AI responses")

Multi-Provider Support

# Works with any LLM provider
import openai
import anthropic

sm = SessionManager()

# OpenAI
await sm.user_says("Hello!")
openai_response = await openai.chat.completions.create(...)
await sm.ai_responds(openai_response.choices[0].message.content, model="gpt-4", provider="openai")

# Anthropic
await sm.user_says("How are you?")
anthropic_response = await anthropic.messages.create(...)
await sm.ai_responds(anthropic_response.content[0].text, model="claude-3", provider="anthropic")

# See costs across all providers
stats = await sm.get_stats()
print(f"Total cost across all providers: ${stats['estimated_cost']:.6f}")

๐Ÿ› ๏ธ Advanced Features

Conversation Analytics

# Get detailed insights into your conversations
conversation = await sm.get_conversation()
stats = await sm.get_stats()

print(f"๐Ÿ“Š Conversation Analytics:")
print(f"   Messages: {stats['user_messages']} user, {stats['ai_messages']} AI")
print(f"   Average response length: {stats['avg_response_length']}")
print(f"   Most expensive response: ${stats['max_response_cost']:.6f}")
print(f"   Session duration: {stats['duration_minutes']:.1f} minutes")

Tool Integration

# Track tool usage alongside conversations
await sm.tool_used(
    tool_name="web_search",
    arguments={"query": "latest AI news"},
    result={"articles": ["AI breakthrough...", "New model released..."]},
    cost=0.001
)

stats = await sm.get_stats()
print(f"Tool calls: {stats['tool_calls']}")

Session Export/Import

# Export conversations for analysis
conversation_data = await sm.export_conversation()
with open('conversation.json', 'w') as f:
    json.dump(conversation_data, f)

# Import previous conversations
sm = SessionManager()
await sm.import_conversation('conversation.json')

๐ŸŽจ Real-World Examples

Customer Support Bot

async def handle_support_ticket(user_message: str, ticket_id: str):
    # Each ticket gets its own session
    sm = SessionManager(session_id=ticket_id)
    
    await sm.user_says(user_message)
    
    # Your AI logic here
    ai_response = await your_ai_model(user_message)
    await sm.ai_responds(ai_response, model="gpt-4", provider="openai")
    
    # Automatic cost tracking per ticket
    stats = await sm.get_stats()
    print(f"Ticket {ticket_id} cost: ${stats['estimated_cost']:.6f}")
    
    return ai_response

AI Assistant with Memory

async def ai_assistant():
    sm = SessionManager(infinite_context=True)
    
    while True:
        user_input = input("You: ")
        if user_input.lower() == 'quit':
            break
            
        await sm.user_says(user_input)
        
        # Get conversation context for AI
        conversation = await sm.get_conversation()
        context = "\n".join([f"{turn['role']}: {turn['content']}" for turn in conversation[-5:]])
        
        # Your AI call with context
        ai_response = await your_ai_model(f"Context:\n{context}\n\nUser: {user_input}")
        await sm.ai_responds(ai_response)
        
        print(f"AI: {ai_response}")
    
    # Show final stats
    stats = await sm.get_stats()
    print(f"\n๐Ÿ’ฐ Total conversation cost: ${stats['estimated_cost']:.6f}")

Multi-User Chat Application

class ChatApplication:
    def __init__(self):
        self.user_sessions = {}
    
    async def handle_message(self, user_id: str, message: str):
        # Each user gets their own session
        if user_id not in self.user_sessions:
            self.user_sessions[user_id] = SessionManager(infinite_context=True)
        
        sm = self.user_sessions[user_id]
        await sm.user_says(message)
        
        # AI processes with user's personal context
        ai_response = await self.generate_response(sm, message)
        await sm.ai_responds(ai_response)
        
        return ai_response
    
    async def get_user_stats(self, user_id: str):
        if user_id in self.user_sessions:
            return await self.user_sessions[user_id].get_stats()
        return None

๐Ÿ“Š Monitoring Dashboard

# Get comprehensive analytics across all sessions
from chuk_ai_session_manager import get_global_stats

stats = await get_global_stats()
print(f"""
๐Ÿš€ AI Application Dashboard
==========================
Total Sessions: {stats['total_sessions']}
Total Messages: {stats['total_messages']}
Total Cost: ${stats['total_cost']:.2f}
Average Session Length: {stats['avg_session_length']:.1f} messages
Most Active Hour: {stats['peak_hour']}
Top Models Used: {', '.join(stats['top_models'])}
""")

๐Ÿ”ง Installation Options

# Basic installation
uv add chuk-ai-session-manager

# With Redis support (for production)
uv add chuk-ai-session-manager[redis]

# Full installation (all features)
uv add chuk-ai-session-manager[full]

# Or with pip
pip install chuk-ai-session-manager

๐ŸŒŸ What Makes CHUK Special?

Feature Other Libraries CHUK AI Session Manager
Setup Complexity Complex configuration 3 lines of code
Cost Tracking Manual calculation Automatic across all providers
Long Conversations Token limit errors Infinite context with auto-segmentation
Multi-Provider Provider-specific code Works with any LLM
Production Ready Requires additional work Built for production
Learning Curve Steep 5 minutes to productivity

๐Ÿš€ Migration Guides

From LangChain Memory

# Old LangChain way
from langchain.memory import ConversationBufferMemory
memory = ConversationBufferMemory()
memory.save_context({"input": "Hi"}, {"output": "Hello"})

# New CHUK way (much simpler!)
from chuk_ai_session_manager import track_conversation
await track_conversation("Hi", "Hello")

From Manual Session Management

# Old manual way
conversations = {}
def save_conversation(user_id, message, response):
    if user_id not in conversations:
        conversations[user_id] = []
    conversations[user_id].append({"user": message, "ai": response})

# New CHUK way
from chuk_ai_session_manager import SessionManager
sm = SessionManager(session_id=user_id)
await sm.user_says(message)
await sm.ai_responds(response)

๐Ÿ“– More Examples

Check out the /examples directory for complete working examples:

  • simple_tracking.py - Basic conversation tracking
  • openai_integration.py - OpenAI API integration
  • infinite_context.py - Handling long conversations
  • cost_monitoring.py - Cost tracking and analytics
  • multi_provider.py - Using multiple LLM providers
  • production_app.py - Production-ready application

๐ŸŽฏ Quick Decision Guide

Choose CHUK AI Session Manager if you want:

  • โœ… Simple conversation tracking with zero configuration
  • โœ… Automatic cost monitoring across all LLM providers
  • โœ… Infinite conversation length without token limit errors
  • โœ… Production-ready session management out of the box
  • โœ… Complete conversation analytics and observability
  • โœ… Framework-agnostic solution that works with any LLM library

Consider alternatives if you:

  • โŒ Only need basic in-memory conversation history
  • โŒ Are locked into a specific framework (LangChain, etc.)
  • โŒ Don't need cost tracking or analytics
  • โŒ Are building simple, stateless AI applications

๐Ÿค Community & Support

  • ๐Ÿ“– Documentation: Full docs with tutorials
  • ๐Ÿ’ฌ Discord: Join our community for help and discussions
  • ๐Ÿ› Issues: Report bugs on GitHub
  • ๐Ÿ’ก Feature Requests: Suggest new features
  • ๐Ÿ“ง Support: enterprise@chuk.dev for production support

๐Ÿ“ License

MIT License - build amazing AI applications with confidence!


๐ŸŽ‰ Ready to build better AI applications?

uv add chuk-ai-session-manager

Get started in 30 seconds with one line of code!

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

chuk_ai_session_manager-0.3.tar.gz (47.1 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

chuk_ai_session_manager-0.3-py3-none-any.whl (42.8 kB view details)

Uploaded Python 3

File details

Details for the file chuk_ai_session_manager-0.3.tar.gz.

File metadata

  • Download URL: chuk_ai_session_manager-0.3.tar.gz
  • Upload date:
  • Size: 47.1 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.12.2

File hashes

Hashes for chuk_ai_session_manager-0.3.tar.gz
Algorithm Hash digest
SHA256 d60d9ae84348b471f7e14d7f651515b873fabdbd34a97a3f25dc116235effb0c
MD5 9faa05f2596631f79a6cd94c00b68999
BLAKE2b-256 76ef1223dcbad976000a18e754203f2841811c37072bb26e3175b6b7375b96f2

See more details on using hashes here.

File details

Details for the file chuk_ai_session_manager-0.3-py3-none-any.whl.

File metadata

File hashes

Hashes for chuk_ai_session_manager-0.3-py3-none-any.whl
Algorithm Hash digest
SHA256 bc56027cbecad94814e42fe87176f63e6c9218368e9b984bf0dfef5df058869f
MD5 4b9e96471d2fbd8ed6f8905336606975
BLAKE2b-256 f5875e8f655829898b7b964252063ecd487ad0de63280dc788fa7f9af7072e82

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page