Streaming Chat UI
This example shows how to build a chat UI with streaming agent responses.
Python (Terminal)
import asyncio
from faos import FaosClient
async def chat():
client = FaosClient(api_key="faos_sk_your_key_here")
while True:
query = input("\nYou: ")
if query.lower() in ("quit", "exit"):
break
print("Agent: ", end="", flush=True)
async for chunk in client.agents.stream(
"credit-risk-analyst",
{"query": query}
):
if chunk.type == "text":
print(chunk.data, end="", flush=True)
elif chunk.type == "error":
print(f"\n[Error: {chunk.data}]")
print() # newline after stream completes
asyncio.run(chat())
TypeScript (Browser)
import { FaosClient, type StreamChunk } from '@faos/sdk';
const client = new FaosClient({ apiKey: 'faos_sk_your_key_here' });
async function sendMessage(query: string) {
const outputEl = document.getElementById('chat-output')!;
const bubble = document.createElement('div');
bubble.className = 'agent-message';
outputEl.appendChild(bubble);
for await (const chunk of client.agents.stream(
'credit-risk-analyst',
{ query },
)) {
switch (chunk.type) {
case 'text':
bubble.textContent += chunk.data;
break;
case 'error':
bubble.classList.add('error');
bubble.textContent += `[Error: ${chunk.data.message}]`;
break;
case 'done':
console.log('Tokens:', chunk.data.usage);
break;
}
}
// Scroll to bottom
outputEl.scrollTop = outputEl.scrollHeight;
}
TypeScript (React)
import { useState, useCallback } from 'react';
import { FaosClient } from '@faos/sdk';
const client = new FaosClient({ apiKey: 'faos_sk_your_key_here' });
function ChatAgent({ agentId }: { agentId: string }) {
const [messages, setMessages] = useState<string[]>([]);
const [streaming, setStreaming] = useState(false);
const sendMessage = useCallback(async (query: string) => {
setStreaming(true);
let response = '';
for await (const text of client.agents.streamText(agentId, { query })) {
response += text;
setMessages((prev) => [...prev.slice(0, -1), response]);
}
setStreaming(false);
}, [agentId]);
return (
<div>
{messages.map((msg, i) => (
<div key={i}>{msg}</div>
))}
{streaming && <div>Streaming...</div>}
</div>
);
}