Python बैकएंड के साथ dedalus-react useChat hook का उपयोग करें। यह पैटर्न रियल-टाइम स्ट्रीमिंग, क्लाइंट-साइड tool निष्पादन और model चयन सक्षम बनाता है।
## आर्किटेक्चर
Dedalus Python SDK (सॉफ्टवेयर डेवलपमेंट किट) OpenAI‑अनुकूल चंक्स को स्ट्रीम करता है। React hook उन्हें Server-Sent Events (SSE) के माध्यम से प्राप्त करके प्रोसेस करता है।
## सेटअप
### निर्भरताएँ इंस्टॉल करें
# Backend
pip install fastapi uvicorn dedalus-labs python-dotenv
# Frontend
pnpm add dedalus-react dedalus-labs react
## Python बैकएंड (FastAPI)
एक स्ट्रीमिंग endpoint बनाएँ जो DedalusRunner के आउटपुट को Server-Sent Events (SSE) के रूप में भेजे:
# server.py
import json
from fastapi import FastAPI, Request
from fastapi.responses import StreamingResponse
from fastapi.middleware.cors import CORSMiddleware
from dotenv import load_dotenv
from dedalus_labs import AsyncDedalus
from dedalus_labs.lib.runner import DedalusRunner
load_dotenv()
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000"],
allow_methods=["POST"],
allow_headers=["*"],
)
client = AsyncDedalus()
runner = DedalusRunner(client)
@app.post("/api/chat")
async def chat(request: Request):
body = await request.json()
messages = body.get("messages", [])
model = body.get("model", "openai/gpt-5.2")
stream = runner.run(
messages=messages,
model=model,
stream=True,
)
async def generate():
async for chunk in stream:
yield f"data: {chunk.model_dump_json()}\n\n"
yield "data: [DONE]\n\n"
return StreamingResponse(
generate(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"Connection": "keep-alive",
},
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
## React फ्रंटएंड
संदेशों और स्ट्रीमिंग को प्रबंधित करने के लिए useChat hook का उपयोग करें:
// App.tsx
import { useChat } from "dedalus-react";
import { useState } from "react";
function Chat() {
const [input, setInput] = useState("");
const { messages, sendMessage, status, stop } = useChat({
transport: { api: "http://localhost:8000/api/chat" },
});
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!input.trim()) return;
sendMessage(input);
setInput("");
};
return (
<div>
<div className="messages">
{messages.map((msg, i) => (
<div key={i} className={`message ${msg.role}`}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))}
</div>
<form onSubmit={handleSubmit}>
<input
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Type a message..."
disabled={status === "streaming"}
/>
<button type="submit" disabled={status === "streaming"}>
Send
</button>
{status === "streaming" && (
<button type="button" onClick={stop}>
Stop
</button>
)}
</form>
</div>
);
}
export default Chat;
## Client-साइड Tool Execution
useChat hook onToolCall और addToolResult के माध्यम से Client पर टूल्स चलाने की सुविधा देता है:
import { useChat } from "dedalus-react";
function ChatWithTools() {
const { messages, sendMessage, addToolResult } = useChat({
transport: { api: "/api/chat" },
// जब model किसी tool का अनुरोध करता है तो कॉल किया जाता है
onToolCall: async ({ toolCall }) => {
if (toolCall.function.name === "get_user_location") {
// क्लाइंट-साइड पर निष्पादित करें (उदा., ब्राउज़र जियोलोकेशन)
const position = await new Promise<GeolocationPosition>((resolve) =>
navigator.geolocation.getCurrentPosition(resolve),
);
addToolResult({
toolCallId: toolCall.id,
result: {
lat: position.coords.latitude,
lng: position.coords.longitude,
},
});
}
},
// tool परिणामों के बाद स्वतः जारी रखें
sendAutomaticallyWhen: ({ messages }) => {
const last = messages[messages.length - 1];
return last?.role === "assistant" && last.tool_calls?.length > 0;
},
});
// ... कंपोनेंट का शेष भाग
}
### यह कैसे काम करता है
- Model tool का अनुरोध करता है - बैकएंड प्रतिक्रिया में
tool_calls को स्ट्रीम करता है
- Hook callback को कॉल करता है - हर tool call के लिए
onToolCall चलती है
- Client निष्पादित करता है - आपका कोड tool चलाता है (API (एप्लिकेशन प्रोग्रामिंग इंटरफ़ेस) कॉल, ब्राउज़र API, user prompt, आदि)
- परिणाम वापस भेजा जाता है -
addToolResult इतिहास में एक tool संदेश जोड़ता है
- ऑटो‑कंटिन्यू - अगर
sendAutomaticallyWhen true लौटाता है, तो tool परिणाम के साथ एक और अनुरोध किया जाता है
Python बैकएंड को किसी विशेष हैंडलिंग की ज़रूरत नहीं होती—उसे बस role: "tool" प्रविष्टियों सहित संदेश प्राप्त होते हैं और वह बातचीत जारी रखता है।
## मॉडल चयन
ट्रांसपोर्ट बॉडी में अतिरिक्त डेटा भेजें:
const [model, setModel] = useState("openai/gpt-5.2");
const { messages, sendMessage } = useChat({
transport: {
api: "/api/chat",
body: { model }, // प्रत्येक अनुरोध में मर्ज किया जाता है
},
});
इसे पढ़ने के लिए बैकएंड को अपडेट करें:
@app.post("/api/chat")
async def chat(request: Request):
body = await request.json()
messages = body.get("messages", [])
model = body.get("model", "openai/gpt-5.2") # बॉडी से पढ़ा गया
stream = runner.run(messages=messages, model=model, stream=True)
# ...
## उदाहरण चलाना
# टर्मिनल 1: बैकएंड प्रारंभ करें
python server.py
# टर्मिनल 2: फ्रंटएंड प्रारंभ करें
cd frontend && pnpm dev
## प्रोडक्शन से जुड़ी बातें
| मुद्दा | समाधान |
|---|
| CORS | अपने डोमेन के लिए allowed origins कॉन्फ़िगर करें |
| Authentication | JWT/सेशन middleware जोड़ें, टोकन को headers में भेजें |
| Rate limiting | प्रति-उपयोगकर्ता throttling लागू करें |
| Error handling | स्ट्रीम को try/catch में लपेटें, त्रुटियों को UI में surfaced/दिखाएँ |