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 देखें।
2026 Production Upgrade
Chatbot एक ऐसा छोटा application है जो user का message लेता है, जरूरी context याद रखता है, और conversation की तरह अगला जवाब देता है। सरल भाषा में, यह website या internal tool का बात करने वाला front desk है। इसका काम हर सवाल का जादुई जवाब देना नहीं है; सही काम है repeated support, lead qualification, document search या incident intake को छोटा करना।
Claude Code के साथ first version छोटा रखें। दस common questions का भरोसेमंद bot, एक all-purpose assistant से बेहतर monetize होता है, क्योंकि उसे test करना आसान है। पहले तय करें: bot क्या जवाब देगा, कब “मुझे पक्का नहीं पता” कहेगा, और कब human support या consultation पर भेजेगा।
Architecture Table
| Layer | काम | Production note |
|---|---|---|
| React UI | input, history, loading, retry | state pattern के लिए React useState docs देखें |
| API route | API key server पर रखता है | size limit, auth और timeout जोड़ें |
| Streaming | answer को छोटे chunks में भेजता है | basics के लिए MDN Streams API देखें |
| Storage | conversation resume और audit | personal data कम रखें |
| RAG | docs या policies से evidence खोजता है | evidence न मिले तो guess न करें |
| Webhook | CRM, ticket या Slack event भेजता है | Claude Code Webhook Implementation पढ़ें |
| Analytics | success, escalation, CTA clicks | Claude Code Analytics Implementation जोड़ें |
API shape के लिए Claude Code API Development वाला pattern रखें: frontend role और content भेजे, system instruction server पर रहे, और response stream होकर आए। इससे बाद में UI या channel बदलना आसान रहता है।
Runnable Streaming Demo
इस code को chatbot-stream-demo.mjs नाम से save करें और node chatbot-stream-demo.mjs चलाएँ। यह external API call नहीं करता; इसका उद्देश्य streaming और history flow verify करना है।
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const faq = new Map([
["password", "Open the account page, choose Reset password, and follow the email link."],
["pricing", "The pricing page explains plans. For a custom quote, collect team size and required features."],
["refund", "Refund requests should be routed to support with the order id and purchase email."],
]);
const history = [];
function chooseAnswer(question) {
const normalized = question.toLowerCase();
for (const [keyword, answer] of faq) {
if (normalized.includes(keyword)) return answer;
}
return "I could not find a safe answer in the FAQ. I will hand this to a human operator.";
}
async function* streamText(text) {
for (const token of text.split(/(\s+)/)) {
await new Promise((resolve) => setTimeout(resolve, 15));
yield encoder.encode(token);
}
}
async function ask(question) {
history.push({ role: "user", content: question });
const answer = chooseAnswer(question);
process.stdout.write(`\nUser: ${question}\nAssistant: `);
let fullAnswer = "";
for await (const chunk of streamText(answer)) {
const token = decoder.decode(chunk);
fullAnswer += token;
process.stdout.write(token);
}
history.push({ role: "assistant", content: fullAnswer });
}
await ask("How do I reset my password?");
await ask("Can I see pricing before talking to sales?");
console.log(`\n\nSaved ${history.length} messages.`);
Production में chooseAnswer को Claude API call से replace करें। Sequence वही रखें: user message save करें, answer stream करें, फिर final answer save करें। इससे वह failure mode बचता है जिसमें UI text दिखाता है लेकिन database खाली answer रखता है।
Real Use Case
पहला use case SaaS lead qualification है। Bot pricing, security, integration और procurement questions का जवाब देता है। High intent user को consultation form पर भेजा जाता है, जिससे sales team repetitive सवालों में कम समय लगाती है।
दूसरा use case internal help desk है। Leave, expense, VPN, device replacement और onboarding जैसे सवाल बार-बार आते हैं। RAG policy document दिखा सकता है और जरूरत होने पर webhook ticket बना सकता है।
तीसरा use case learning site है। Reader पूछता है कि API, webhook या analytics में क्या पहले सीखना चाहिए। Bot article recommend कर सकता है और practical help के लिए training पर भेज सकता है। यह workflow banner से ज्यादा natural monetization देता है।
चौथा use case incident intake है। Bot error message, time, browser, account और reproduction steps जमा करता है। Goal तुरंत solve करना नहीं, support team को complete handoff देना है।
Pitfall और Failure
पूरी unlimited history model को न भेजें। Cost बढ़ती है, response slow होता है, और पुराने instruction current question को confuse कर सकते हैं। Old turns summarize करें और relevant facts रखें।
RAG evidence कमजोर हो तो confident answer न दें। Bot को कहना चाहिए कि reliable information नहीं मिली, फिर human route देना चाहिए। Support और compliance के लिए यह बहुत जरूरी है।
Streaming को सिर्फ visual effect न समझें। Network टूट सकता है, double submit हो सकता है, loading अटक सकती है। Disabled button, cancel request, timeout और retry message जोड़ें।
Metrics के बिना launch न करें। Unresolved questions, escalation, CTA clicks और consultation या purchase में बदली conversations track करें। सिर्फ message count business value नहीं बताता।
Monetization CTA
Commercial chatbot को एक clear next action देना चाहिए: implementation review, consultation, template या training। ClaudeCodeLab में high-intent readers को training पर भेजना बेहतर है, क्योंकि वहाँ article से real implementation discussion शुरू होता है।
Suggested path: पहले यह concept समझें, फिर Claude Code API Development से API बनाएं, webhooks से systems connect करें, और analytics से conversion measure करें।
मुफ़्त PDF: Claude Code cheatsheet
Email डालें और commands, review habits तथा safe workflow वाली एक-page PDF पाएँ.
हम आपका data सुरक्षित रखते हैं और spam नहीं भेजते.
लेखक के बारे में
Masa
Claude Code workflow और team adoption पर काम करने वाला engineer.
संबंधित लेख
Claude Code Obsidian to CLAUDE.md workflow: context बार-बार न समझाएं
Obsidian notes को CLAUDE.md operating notes में बदलकर Claude Code sessions को resume करना आसान बनाएं.
Claude Code Revenue CTA Routing: article से PDF, Gumroad और consultation तक
Reader intent के आधार पर free PDF, Gumroad products और consultation तक CTA route करने वाला workflow.
Claude Code टीम हैंडऑफ नियम: review proof, permissions, rollback और revenue path
Claude Code टीम काम के लिए evidence, permission rules, rollback, free PDF, Gumroad और consultation path वाला handoff.