Skip to main content

Basic Chat Example

A complete example of creating and using a Chat session.

Complete Example

import asyncio
from upsonic import Agent, Task, Chat

async def main():
    # Create agent
    agent = Agent("openai/gpt-4o")
    
    # Create chat session
    chat = Chat(
        session_id="example_session",
        user_id="example_user",
        agent=agent
    )
    
    # Send messages
    response1 = await chat.invoke("Hello, my name is Alice")
    print(f"Assistant: {response1}")
    
    response2 = await chat.invoke("What's my name?")
    print(f"Assistant: {response2}")
    
    # Access history
    print(f"\nTotal messages: {len(chat.all_messages)}")
    print(f"Total cost: ${chat.total_cost:.4f}")
    
    # Clean up
    await chat.close()

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

With Task Objects

import asyncio
from upsonic import Agent, Task, Chat

async def main():
    agent = Agent("openai/gpt-4o")
    chat = Chat(session_id="session1", user_id="user1", agent=agent)
    
    # Use Task objects
    task1 = Task(description="Explain quantum computing")
    response1 = await chat.invoke(task1)
    print(response1)
    
    task2 = Task(description="Give me a summary")
    response2 = await chat.invoke(task2)
    print(response2)
    
    await chat.close()

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

Streaming Example

import asyncio
from upsonic import Agent, Chat

async def main():
    agent = Agent("openai/gpt-4o")
    chat = Chat(session_id="session1", user_id="user1", agent=agent)
    
    # Stream response
    print("Assistant: ", end="")
    async for chunk in chat.invoke("Tell me a story", stream=True):
        print(chunk, end="", flush=True)
    print()
    
    await chat.close()

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