Skip to main content

Simple Chat

Basic example of chatting with LangChat:
import asyncio
from langchat import LangChat, LangChatConfig

async def main():
    # Create configuration
    config = LangChatConfig.from_env()
    
    # Initialize LangChat
    langchat = LangChat(config=config)
    
    # Chat with the AI
    # Note: The response is automatically displayed in a Rich panel box in the console
    # You don't need to print it manually
    result = await langchat.chat(
        query="Hello! What can you help me with?",
        user_id="user123",
        domain="general"
    )
    
    # The response is already shown in a panel above
    # Access response data programmatically if needed:
    print(f"Status: {result['status']}")
    print(f"Time: {result['response_time']:.2f}s")

asyncio.run(main())

Multi-Turn Conversation

Handle conversation context automatically:
import asyncio
from langchat import LangChat, LangChatConfig

async def conversation():
    config = LangChatConfig.from_env()
    langchat = LangChat(config=config)
    
    user_id = "user123"
    domain = "education"
    
    # First message
    # Responses are automatically displayed in Rich panels
    result1 = await langchat.chat(
        query="What universities offer computer science?",
        user_id=user_id,
        domain=domain
    )
    # Response shown in panel above
    
    # Second message (has context from first)
    result2 = await langchat.chat(
        query="What about in Europe?",
        user_id=user_id,
        domain=domain
    )
    # Response shown in panel above
    
    # Third message (continues conversation)
    result3 = await langchat.chat(
        query="Which ones accept IELTS 6.5?",
        user_id=user_id,
        domain=domain
    )
    # Response shown in panel above

asyncio.run(conversation())

Error Handling

Proper error handling:
import asyncio
from langchat import LangChat, LangChatConfig

async def chat_with_error_handling():
    try:
        config = LangChatConfig.from_env()
        langchat = LangChat(config=config)
        
        result = await langchat.chat(
            query="Hello!",
            user_id="user123",
            domain="general"
        )
        
        if result["status"] == "success":
            print(f"Response: {result['response']}")
        else:
            print(f"Error: {result.get('error', 'Unknown error')}")
            
    except ValueError as e:
        print(f"Configuration error: {e}")
    except Exception as e:
        print(f"Unexpected error: {e}")

asyncio.run(chat_with_error_handling())

Next Steps