Claude Code के साथ Chatbot कैसे Develop करें
Claude Code का उपयोग करके chatbot develop करना सीखें। Practical code examples और step-by-step guidance शामिल है।
Claude Code से Chatbot Develop करें
AI chatbot development में UI implementation, API integration, conversation management, streaming processing जैसे कई elements हैं। Claude Code से इन सभी को integrate करके chatbot कम समय में बनाया जा सकता है।
Basic Chat UI Implementation
> React में chatbot component बनाओ।
> Streaming response support, conversation history display, input form के साथ।
import { useState, useRef, useEffect } from "react";
interface Message {
id: string;
role: "user" | "assistant";
content: string;
}
export function ChatBot() {
const [messages, setMessages] = useState<Message[]>([]);
const [input, setInput] = useState("");
const [isLoading, setIsLoading] = useState(false);
const messagesEndRef = useRef<HTMLDivElement>(null);
useEffect(() => {
messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
}, [messages]);
const sendMessage = async () => {
if (!input.trim() || isLoading) return;
const userMessage: Message = {
id: crypto.randomUUID(),
role: "user",
content: input,
};
setMessages((prev) => [...prev, userMessage]);
setInput("");
setIsLoading(true);
const assistantId = crypto.randomUUID();
setMessages((prev) => [
...prev,
{ id: assistantId, role: "assistant", content: "" },
]);
try {
const response = await fetch("/api/chat", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
messages: [...messages, userMessage].map(({ role, content }) => ({
role,
content,
})),
}),
});
const reader = response.body!.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
setMessages((prev) =>
prev.map((m) =>
m.id === assistantId
? { ...m, content: m.content + chunk }
: m
)
);
}
} catch (error) {
setMessages((prev) =>
prev.map((m) =>
m.id === assistantId
? { ...m, content: "Error हुई। कृपया दोबारा try करें।" }
: m
)
);
}
setIsLoading(false);
};
return (
<div className="flex flex-col h-[600px] border rounded-lg">
<div className="flex-1 overflow-y-auto p-4 space-y-4">
{messages.map((msg) => (
<div
key={msg.id}
className={`flex ${msg.role === "user" ? "justify-end" : "justify-start"}`}
>
<div
className={`max-w-[70%] p-3 rounded-lg ${
msg.role === "user"
? "bg-blue-600 text-white"
: "bg-gray-100 text-gray-900"
}`}
>
{msg.content}
</div>
</div>
))}
<div ref={messagesEndRef} />
</div>
<div className="border-t p-4 flex gap-2">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && !e.shiftKey && sendMessage()}
placeholder="Message type करें..."
className="flex-1 p-2 border rounded-lg"
disabled={isLoading}
/>
<button
onClick={sendMessage}
disabled={isLoading}
className="px-4 py-2 bg-blue-600 text-white rounded-lg disabled:opacity-50"
>
Send
</button>
</div>
</div>
);
}
Streaming Support API Route
Backend में Anthropic API call करके streaming से return करने वाला API route।
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic();
export async function POST(request: Request) {
const { messages } = await request.json();
const stream = await client.messages.stream({
model: "claude-sonnet-4-20250514",
max_tokens: 1024,
system: "You are a helpful and polite assistant.",
messages,
});
const encoder = new TextEncoder();
const readable = new ReadableStream({
async start(controller) {
for await (const event of stream) {
if (
event.type === "content_block_delta" &&
event.delta.type === "text_delta"
) {
controller.enqueue(encoder.encode(event.delta.text));
}
}
controller.close();
},
});
return new Response(readable, {
headers: { "Content-Type": "text/plain; charset=utf-8" },
});
}
Conversation History Persistence
Conversations database में save करके बाद में continue करने की functionality।
import { db } from "@/lib/database";
export async function saveConversation(
userId: string,
messages: Message[]
) {
return db.conversation.upsert({
where: { id: `${userId}-current` },
update: {
messages: JSON.stringify(messages),
updatedAt: new Date(),
},
create: {
id: `${userId}-current`,
userId,
messages: JSON.stringify(messages),
},
});
}
export async function loadConversation(userId: string): Promise<Message[]> {
const conv = await db.conversation.findUnique({
where: { id: `${userId}-current` },
});
return conv ? JSON.parse(conv.messages as string) : [];
}
RAG (Retrieval-Augmented Generation) Integration
Internal documents based पर answer करने वाला chatbot बनाने के लिए RAG configuration effective है।
import { searchDocuments } from "@/lib/vector-search";
async function generateRAGResponse(query: string, conversationHistory: Message[]) {
// Related documents search करें
const relevantDocs = await searchDocuments(query, { limit: 5 });
const context = relevantDocs
.map((doc) => `---\n${doc.title}\n${doc.content}\n---`)
.join("\n");
const systemPrompt = `Following documents reference करके question का answer दें।
Documents में information नहीं है तो "वह information नहीं मिली" answer करें।
${context}`;
return client.messages.stream({
model: "claude-sonnet-4-20250514",
max_tokens: 1024,
system: systemPrompt,
messages: conversationHistory,
});
}
MCP server integration से functionality extend करने का तरीका MCP Server Guide में देखें, effective prompt design के लिए Prompt Improve करने के 5 Tips देखें।
Summary
Claude Code से chat UI, streaming API, conversation management, RAG configuration तक include करके chatbot efficiently develop किया जा सकता है। Step by step features add करने का approach effective है।
Details के लिए Claude Code Official Documentation और Anthropic API Reference देखें।
मुफ़्त PDF: 5 मिनट में Claude Code चीटशीट
बस अपना ईमेल दर्ज करें और हम तुरंत A4 एक-पृष्ठ चीटशीट PDF भेज देंगे।
हम आपकी व्यक्तिगत जानकारी की सुरक्षा करते हैं और स्पैम नहीं भेजते।
लेखक के बारे में
Masa
Claude Code का गहराई से उपयोग करने वाले इंजीनियर। claudecode-lab.com चलाते हैं, जो 10 भाषाओं में 2,000 से अधिक पेजों वाला टेक मीडिया है।
संबंधित लेख
हर दिन बहुभाषी Claude Code लेख प्रकाशित करने से पहले 7 जांचें
एक व्यावहारिक चेकलिस्ट ताकि आप हर दिन बहुभाषी Claude Code लेख प्रकाशित करते समय कोई भाषा न छोड़ें, CTA न तोड़ें और पुराना पेज लाइव न रहने दें।
Codex Automations क्या है? AI से content ops, analysis और deploy करवाने का तरीका
Codex Automations से analytics, article planning, CTA सुधार, deploy और monetization workflow चलाने की practical guide.
Claude Code × GCP Cloud Functions संपूर्ण गाइड | सर्वरलेस फंक्शन तेज़ी से विकसित करें
Claude Code से GCP Cloud Functions को ऑप्टिमाइज़ करें। HTTP/Pub/Sub/Firestore ट्रिगर, लोकल टेस्टिंग और डिप्लॉयमेंट ऑटोमेशन — Masa के व्यावहारिक अनुभव से रियल कोड उदाहरणों के साथ।