API Call → Memory → JSON → Streaming → Embeddings → RAG → Tools → MCP → Agents → Evals
The Easy Master: Learn. Build. Grow.
Level: Beginner → Intermediate
Tested on: Ollama 0.40 (llama3.2, qwen2.5:7b, nomic-embed-text), Node.js 24, MCP SDK 1.32
Goal: Copy-paste code jo chalta hai — theory के लिए हर section में cheat sheet का link है
यह cheat sheet AI Engineering series का सारा code एक जगह है। हर snippet इस page पर डालने से पहले चलाकर जाँचा गया है। Theory चाहिए? हर section में उसकी theory वाली cheat sheet का link है।
1. Setup – Free AI Apne Laptop Par#
ollama pull llama3.2 # chhota, tez (2 GB)
ollama pull qwen2.5:7b # samajhdar, tools ke liye (4.7 GB, ~16 GB RAM)
ollama pull nomic-embed-text # embeddings ke liye (~270 MB)| Endpoint | Kaam |
|---|---|
POST /api/chat | Chat – messages bhejo, jawab lo |
POST /api/embed | Text → numbers (embeddings) |
GET /api/tags | Kaun se models download hain |
Node.js 18+ में fetch पहले से है। package.json में "type": "module" रखिए ताकि top-level await चले। पूरा setup: Part 2।
2. Ek Helper – Har Jagah Kaam Aata Hai#
// Ek helper jo har jagah kaam aata hai
const OLLAMA = 'http://localhost:11434';
async function chat(messages, extra = {}) {
const res = await fetch(`${OLLAMA}/api/chat`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: 'llama3.2', messages, stream: false, ...extra }),
});
const data = await res.json();
return data.message; // { role: 'assistant', content: '...' }
}
const reply = await chat([
{ role: 'system', content: 'Reply in one short line.' },
{ role: 'user', content: 'Git kya hai?' },
]);
console.log(reply.content);| Role | Kaun bol raha hai |
|---|---|
system | आप – AI के नियम और role |
user | आपकी app का user |
assistant | AI ने पहले क्या कहा |
tool | आपके function का result |
Theory: LLMs Cheat Sheet
3. Memory – Chat History Aur Trim#
AI कुछ याद नहीं रखता। हर call में history आप भेजते हैं – और history जितनी लंबी, bill उतना बड़ा।
// Memory = history array; har call mein system + aakhri N messages
const messages = [{ role: 'system', content: 'Tum helpful ho.' }];
function remember(role, content) {
messages.push({ role, content });
}
function trim(list, keep = 6) {
const [system, ...rest] = list;
return [system, ...rest.slice(-keep)];
}
for (let i = 1; i <= 10; i++) remember(i % 2 ? 'user' : 'assistant', `message ${i}`);
console.log(messages.length, '->', trim(messages).length); // 11 -> 7Detail: Part 2 – chatbot · Part 4 – tokens
4. JSON Output – Structured Jawab#
// Jawab hamesha isi shape ka JSON
const schema = {
type: 'object',
properties: {
sentiment: { type: 'string', enum: ['positive', 'negative', 'mixed'] },
problems: { type: 'array', items: { type: 'string' } },
},
required: ['sentiment', 'problems'],
};
const res = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'llama3.2',
stream: false,
format: schema, // structured output
options: { temperature: 0 }, // har baar ek jaisa
messages: [{ role: 'user', content: 'Battery jaldi khatam hoti hai, camera blurry hai.' }],
}),
});
const data = JSON.parse((await res.json()).message.content);
console.log(data.sentiment, data.problems.length);| Setting | Kab |
|---|---|
format: schema | जवाब को code में use करना है |
temperature: 0 | Extract, classify – हर बार एक जैसा |
temperature: 0.7–1 | Ideas, stories – हर बार नया |
Schema shape पक्की करता है, सच नहीं – ज़रूरी fields code में जाँचिए। Detail: Part 3 · Theory: Prompt Engineering Cheat Sheet
5. Tokens – Har Call Ka Meter#
// Har call ka meter
const res = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'llama3.2',
stream: false,
options: { num_predict: 50 }, // safety limit — chhota jawab prompt mein maangiye
messages: [{ role: 'user', content: 'React kya hai? 1 line mein.' }],
}),
});
const data = await res.json();
console.log('input:', data.prompt_eval_count, 'output:', data.eval_count);| Field (Ollama) | Matlab |
|---|---|
prompt_eval_count | Input tokens |
eval_count | Output tokens |
options.num_predict | जवाब की ऊपरी limit (बीच शब्द में काट सकती है) |
options.num_ctx | Context window का size |
Detail: Part 4
6. Streaming – Word-by-Word#
// NDJSON stream padhna — adhuri line buffer mein rukti hai
async function* streamChat(messages) {
const res = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: 'llama3.2', messages, stream: true }),
});
const decoder = new TextDecoder();
let buffer = '';
for await (const chunk of res.body) {
buffer += decoder.decode(chunk, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) if (line.trim()) yield JSON.parse(line).message.content;
}
}
for await (const piece of streamChat([{ role: 'user', content: 'Docker 1 line mein' }])) {
process.stdout.write(piece);
}
console.log();Sabse aam bug: हर chunk को सीधे JSON.parse करना। Chunk बीच line में ख़त्म हो सकता है – इसलिए buffer और lines.pop()।
Express se browser tak (SSE)
// Express: AI ka jawab browser tak (Server-Sent Events)
import express from 'express';
const app = express();
app.use(express.json());
app.post('/api/ask', async (req, res) => {
res.setHeader('Content-Type', 'text/event-stream');
res.setHeader('Cache-Control', 'no-cache');
const send = (data) => res.write(`data: ${JSON.stringify(data)}\n\n`); // \n\n zaroori
const ai = await fetch('http://localhost:11434/api/chat', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: 'llama3.2', messages: [{ role: 'user', content: req.body.question }], stream: true }),
});
const decoder = new TextDecoder();
let buffer = '';
for await (const chunk of ai.body) {
buffer += decoder.decode(chunk, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop();
for (const line of lines) if (line.trim()) send({ text: JSON.parse(line).message.content });
}
res.write('data: [DONE]\n\n');
res.end();
});
app.listen(3000);| SSE niyam | Kyun |
|---|---|
Content-Type: text/event-stream | Browser को पता चले कि यह stream है |
हर event के बाद \n\n | वरना browser इंतज़ार करता रहेगा |
JSON.stringify({ text }) | Text में newline event न तोड़े |
res.write() + res.end() | res.json() एक बार भेजकर बंद कर देता है |
Browser वाला code और पूरा flow: Part 5
7. Embeddings – Matlab Se Search#
// Embeddings + cosine similarity
async function embed(texts) {
const res = await fetch('http://localhost:11434/api/embed', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: 'nomic-embed-text', input: texts }),
});
return (await res.json()).embeddings;
}
function similarity(a, b) {
let dot = 0, na = 0, nb = 0;
for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; }
return dot / (Math.sqrt(na) * Math.sqrt(nb)); // 1 = same matlab, 0 = koi rishta nahi
}
const [q, a, b] = await embed(['I forgot my login', 'How can I reset my password?', 'How long does shipping take?']);
console.log(similarity(q, a).toFixed(2), similarity(q, b).toFixed(2));"I forgot my login" → password reset FAQ 0.65, shipping FAQ 0.29 – एक भी शब्द common नहीं, फिर भी सही match।
- Documents और सवाल – एक ही embedding model से
- Model बदला → सारे vectors दोबारा बनाइए
- Documents के vectors एक बार बनाकर save कीजिए
Detail: Part 6 (21 Nov को आएगा) · Theory: Embeddings & Vector DB Cheat Sheet
8. RAG – Apne Data Se Jawab#
// RAG: dhoondo (MIN_SCORE ke saath) -> number do -> sirf usi se jawab
const OLLAMA = 'http://localhost:11434';
const MIN_SCORE = 0.5;
async function embed(texts) {
const res = await fetch(`${OLLAMA}/api/embed`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: 'nomic-embed-text', input: texts }),
});
return (await res.json()).embeddings;
}
function similarity(a, b) {
let dot = 0, na = 0, nb = 0;
for (let i = 0; i < a.length; i++) { dot += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; }
return dot / (Math.sqrt(na) * Math.sqrt(nb));
}
const chunks = [
'Refund: Joining ke 7 din ke andar course chhodne par poori fees wapas milti hai.',
'Classes: Monday se Friday, shaam 6 se 8 baje.',
'Attendance: Certificate ke liye kam se kam 75% attendance zaroori hai.',
];
const vectors = await embed(chunks); // asli app mein ek baar bana kar save karo
async function ask(question) {
const [q] = await embed([question]);
const found = chunks
.map((text, i) => ({ text, score: similarity(q, vectors[i]) }))
.filter((c) => c.score >= MIN_SCORE)
.sort((a, b) => b.score - a.score)
.slice(0, 3);
if (!found.length) return 'Notes mein yeh nahi hai.'; // AI call hi nahi
const context = found.map((c, i) => `[${i + 1}] ${c.text}`).join('\n');
const res = await fetch(`${OLLAMA}/api/chat`, {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
model: 'qwen2.5:7b', stream: false, options: { temperature: 0 },
messages: [
{ role: 'system', content: 'Answer only from the NOTES. Put the source number after each fact, like [1]. If the answer is not in the notes, say "Notes mein yeh nahi hai." Reply in short Hinglish.' },
{ role: 'user', content: `NOTES:\n${context}\n\nQUESTION: ${question}` },
],
}),
});
return (await res.json()).message.content;
}
console.log(await ask('Refund kab milta hai?'));
console.log(await ask('What is the capital of France?'));| Hissa | Kaam |
|---|---|
MIN_SCORE | बेकार सवाल AI तक पहुँचे ही नहीं – पैसा और hallucination दोनों बचे |
[1], [2] | जवाब के साथ source – user जाँच सके |
| "Notes mein nahi hai" का नियम | सबसे ज़रूरी – वरना AI जवाब बना देगा |
qwen2.5:7b | छोटे model ने सही chunk मिलने पर भी "nahi hai" कहा था |
Galat jawab? पहले retrieved chunks print कीजिए। सही जानकारी chunks में नहीं → chunking/search ठीक कीजिए। Chunks में है → prompt/model ठीक कीजिए।
Detail: Part 7 (22 Nov को आएगा) · Part 8 – chunking, index, debugging (23 Nov को आएगा) · Theory: RAG Cheat Sheet
9. Tool Calling – AI Se Functions Chalwana#
// Tool calling loop: AI maangta hai, aapka code chalata hai
const functions = {
getOrderStatus: ({ orderId }) => ({ 4521: { status: 'shipped', delivery: 'kal' } })[orderId] ?? { error: 'Order nahi mila' },
};
const tools = [{
type: 'function',
function: {
name: 'getOrderStatus',
description: 'Order ID se order ka status aur delivery ka samay batata hai',
parameters: { type: 'object', properties: { orderId: { type: 'number' } }, required: ['orderId'] },
},
}];
async function chat(messages) {
const res = await fetch('http://localhost:11434/api/chat', {
method: 'POST', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ model: 'qwen2.5:7b', messages, tools, stream: false, options: { temperature: 0 } }),
});
return (await res.json()).message;
}
const messages = [
{ role: 'system', content: 'You are a shop support assistant. Use the tools. If a tool does not give the answer, say you do not know — never guess. Reply in short Hinglish.' },
{ role: 'user', content: 'Mera order 4521 kahan hai?' },
];
let reply = await chat(messages);
while (reply.tool_calls?.length) {
messages.push(reply); // AI ki maang history mein
for (const call of reply.tool_calls) {
const result = functions[call.function.name](call.function.arguments);
messages.push({ role: 'tool', tool_name: call.function.name, content: JSON.stringify(result) });
}
reply = await chat(messages);
}
console.log(reply.content);- AI माँगता है, आपका code चलाता है
descriptionसबसे ज़रूरी – AI उसी से तय करता है कि tool कब चाहिएmessages.push(reply)भूले तो AI को पता नहीं कि उसने tool माँगा था- User का ID session/token से, AI के arguments से कभी नहीं
- Data बदलने वाले tools से पहले user से confirmation
Detail: Part 9 (24 Nov को आएगा)
10. MCP – Server Aur Client#
// Sabse chhota MCP server (stdio)
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { z } from 'zod';
const server = new McpServer({ name: 'my-tools', version: '1.0.0' });
server.registerTool(
'add',
{ title: 'Add', description: 'Do numbers jodta hai', inputSchema: { a: z.number(), b: z.number() } },
async ({ a, b }) => ({ content: [{ type: 'text', text: String(a + b) }] }),
);
await server.connect(new StdioServerTransport());
console.error('server ready'); // console.log NAHI — stdout MCP ka raasta hai// MCP client: tools poochho, chalao — aur Ollama ki tool list mein badlo
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
const mcp = new Client({ name: 'tester', version: '1.0.0' });
await mcp.connect(new StdioClientTransport({ command: 'node', args: ['10-mcp-server.js'] }));
const { tools } = await mcp.listTools();
const ollamaTools = tools.map((t) => ({
type: 'function',
function: { name: t.name, description: t.description, parameters: t.inputSchema },
}));
const result = await mcp.callTool({ name: 'add', arguments: { a: 2, b: 3 } });
console.log(ollamaTools[0].function.name, result.content[0].text);
await mcp.close();npm install @modelcontextprotocol/sdk zod| Hissa | Kaam |
|---|---|
| MCP Server | Tools और data देता है |
| MCP Client | Server से बात करता है (listTools, callTool) |
| Host | वो AI app जो user खोलता है |
Server में console.log कभी नहीं – stdout पर MCP के messages चलते हैं। Detail: Part 10 (25 Nov को आएगा) · Theory: AI Agents & MCP Cheat Sheet
11. Agent Loop + MAX_STEPS#
// Agent = tools ke saath loop + MAX_STEPS
const MAX_STEPS = 6;
async function runAgent(task, { chat, functions }) {
const messages = [
{ role: 'system', content: 'Get every fact you need from the tools; never make up data.' },
{ role: 'user', content: task },
];
for (let step = 1; step <= MAX_STEPS; step++) {
const reply = await chat(messages);
messages.push(reply);
if (!reply.tool_calls?.length) return reply.content; // kaam pura
for (const call of reply.tool_calls) {
const result = await functions[call.function.name](call.function.arguments);
messages.push({ role: 'tool', tool_name: call.function.name, content: JSON.stringify(result) });
}
}
return 'Bahut zyada steps — agent ruk gaya.';
}
// Bina model ke check: ek nakli chat jo pehle tool maange, phir jawab de
let turn = 0;
const fakeChat = async () => (turn++ === 0
? { role: 'assistant', tool_calls: [{ function: { name: 'getRemainingTopics', arguments: {} } }] }
: { role: 'assistant', content: 'Plan: React, Node.js' });
console.log(await runAgent('Plan bana do', { chat: fakeChat, functions: { getRemainingTopics: () => ['React', 'Node.js'] } }));chat और functions बाहर से आते हैं – इसीलिए यह loop बिना model के भी test हो जाता है। असली chat के लिए section 9 वाला function use कीजिए।
Detail: Part 11 (26 Nov को आएगा)
12. Evals – Har Baar Sahi?#
// Eval: AI ke jawab par code ke checks, kai baar
const checks = [
{ name: 'saare bache topics hain', test: (plan) => ['React', 'Node.js'].every((t) => plan.includes(t)) },
{ name: 'pure topics nahi hain', test: (plan) => !['HTML/CSS', 'JavaScript'].some((t) => plan.includes(t)) },
];
async function runEvals(getAnswer, runs = 3) {
let passed = 0, total = 0;
for (let run = 1; run <= runs; run++) {
const answer = await getAnswer();
for (const c of checks) { total++; if (c.test(answer)) passed++; else console.log(`run ${run} FAIL ${c.name}`); }
}
console.log(`Score: ${passed}/${total}`);
}
await runEvals(async () => 'Week 1: React, Week 2: Node.js');- एक बार pass होना काफ़ी नहीं – AI हर run में अलग जवाब दे सकता है
- Prompt, model या code बदला → evals दोबारा
- हिसाब (filter, गिनती, तारीख़) code में कीजिए, AI से नहीं – Part 11 में इसी से 6/9 → 9/9 हुआ
- Checks भी ग़लत हो सकते हैं – उन्हें भी पढ़ते रहिए
13. Kaunsa Tareeka Kab?#
| Kaam | Tareeka | Part |
|---|---|---|
| एक सवाल का जवाब | Section 2 का chat() | 2 |
| App के लिए data | JSON schema | 3 |
| अपने documents से जवाब | RAG | 7 (22 Nov को आएगा), 8 (23 Nov को आएगा) |
| Live data या कोई काम | Tool calling | 9 (24 Nov को आएगा) |
| Tool कई apps में | MCP server | 10 (25 Nov को आएगा) |
| बड़ा काम, steps पता नहीं | Agent | 11 (26 Nov को आएगा) |
सबसे simple तरीका जो काम करे – वही सबसे अच्छा।
14. Common Errors#
| Error / problem | Wajah | Fix |
|---|---|---|
fetch failed | Ollama चल नहीं रहा | ollama serve या Ollama app खोलिए |
model not found | Model download नहीं हुआ | ollama pull <model> |
await is only valid in async functions | ES module नहीं | "type": "module" |
Unexpected end of JSON input (stream) | Chunk बीच line में कटा | Buffer + lines.pop() |
SyntaxError on JSON.parse | AI ने JSON के बाहर text लिखा | format: schema |
| AI जवाब बना देता है | "पता नहीं" कहने का नियम नहीं | System prompt: "never guess" |
| AI tool use नहीं करता | छोटा model, उलझा prompt | System prompt English में, जवाब Hinglish में |
| MCP server चुपचाप टूटता है | console.log | console.error |
| Chatbot नाम भूल जाता है | AI का जवाब history में नहीं गया | messages.push(data.message) |