Chuyển tới nội dung chính

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())
<PlaygroundButton code={"import asyncio\nfrom faos import FaosClient\n\nasync def chat():\n client = FaosClient(api_key=\"faos_sk_your_key_here\")\n\n while True:\n query = input(\"\\nYou: \")\n if query.lower() in (\"quit\", \"exit\"):\n break\n\n print(\"Agent: \", end=\"\", flush=True)\n async for chunk in client.agents.stream(\n \"credit-risk-analyst\",\n {\"query\": query}\n ):\n if chunk.type == \"text\":\n print(chunk.data, end=\"\", flush=True)\n elif chunk.type == \"error\":\n print(f\"\\n[Error: {chunk.data}]\")\n print() # newline after stream completes\n\nasyncio.run(chat())"} lang="python" />

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;
}
<PlaygroundButton code={"import { FaosClient, type StreamChunk } from '@faos/sdk';\n\nconst client = new FaosClient({ apiKey: 'faos_sk_your_key_here' });\n\nasync function sendMessage(query: string) {\n const outputEl = document.getElementById('chat-output')!;\n const bubble = document.createElement('div');\n bubble.className = 'agent-message';\n outputEl.appendChild(bubble);\n\n for await (const chunk of client.agents.stream(\n 'credit-risk-analyst',\n { query },\n )) {\n switch (chunk.type) {\n case 'text':\n bubble.textContent += chunk.data;\n break;\n case 'error':\n bubble.classList.add('error');\n bubble.textContent += `[Error: ${chunk.data.message}]`;\n break;\n case 'done':\n console.log('Tokens:', chunk.data.usage);\n break;\n }\n }\n\n // Scroll to bottom\n outputEl.scrollTop = outputEl.scrollHeight;\n}"} lang="typescript" />

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>
);
}
<PlaygroundButton code={"import { useState, useCallback } from 'react';\nimport { FaosClient } from '@faos/sdk';\n\nconst client = new FaosClient({ apiKey: 'faos_sk_your_key_here' });\n\nfunction ChatAgent({ agentId }: { agentId: string }) {\n const [messages, setMessages] = useState<string[]>([]);\n const [streaming, setStreaming] = useState(false);\n\n const sendMessage = useCallback(async (query: string) => {\n setStreaming(true);\n let response = '';\n\n for await (const text of client.agents.streamText(agentId, { query })) {\n response += text;\n setMessages((prev) => [...prev.slice(0, -1), response]);\n }\n\n setStreaming(false);\n }, [agentId]);\n\n return (\n <div>\n {messages.map((msg, i) => (\n <div key={i}>{msg}</div>\n ))}\n {streaming && <div>Streaming...</div>}\n </div>\n );\n}"} lang="typescript" />