Running a Chat
Chat supports both blocking and streaming interactions. Useinvoke() for blocking responses or stream() for streaming.
Blocking Response
Copy
from upsonic import Agent, Task, Chat
agent = Agent("openai/gpt-4o")
chat = Chat(session_id="session1", user_id="user1", agent=agent)
# Send string message
response = await chat.invoke("What is 2+2?")
print(response)
# Send Task object
task = Task(description="Explain quantum computing")
response = await chat.invoke(task)
print(response)
Streaming Response
Copy
from upsonic import Agent, Chat
agent = Agent("openai/gpt-4o")
chat = Chat(session_id="session1", user_id="user1", agent=agent)
# Stream using invoke with stream=True
async for chunk in chat.invoke("Tell me a story", stream=True):
print(chunk, end='', flush=True)
# Or use dedicated stream method
async for chunk in chat.stream("Tell me a story"):
print(chunk, end='', flush=True)
With Attachments
Copy
from upsonic import Agent, Task, Chat
agent = Agent("openai/gpt-4o")
chat = Chat(session_id="session1", user_id="user1", agent=agent)
# Send message with file attachments
response = await chat.invoke(
"Analyze this document",
attachments=["document.pdf", "data.csv"]
)
Accessing History
Copy
from upsonic import Agent, Chat
agent = Agent("openai/gpt-4o")
chat = Chat(session_id="session1", user_id="user1", agent=agent)
# Send messages
await chat.invoke("Hello")
await chat.invoke("How are you?")
# Access all messages
messages = chat.all_messages
for msg in messages:
print(f"{msg.role}: {msg.content}")
# Get recent messages
recent = chat.get_recent_messages(count=5)
Session Management
Copy
from upsonic import Agent, Chat
agent = Agent("openai/gpt-4o")
chat = Chat(session_id="session1", user_id="user1", agent=agent)
# Check session state
print(chat.state) # IDLE, AWAITING_RESPONSE, STREAMING, or ERROR
# Clear history
chat.clear_history()
# Reset session
chat.reset_session()
# Close session
await chat.close()

