AI agent kaise banaye Python mein: Hindi (Hinglish) guide aur poora code
Agent ek loop hai: model batata hai kaunsa tool chahiye, aapka code use chalata hai aur result wapas bhejta hai, jab tak jawab na mil jaaye.
By Homingo Learn ·
AI agent kya hai: chatbot se farq
Chatbot sirf jawab deta hai. AI agent kaam bhi karta hai: woh tools use karta hai (API, database, files), results dekhta hai aur agla step chunta hai. Is guide mein Python mein ek chhota, chalne wala agent hai, error handling aur step cap ke saath, jiska offline demo bina API key ke chalta hai.
AI agent ke teen hisse: tools, loop, guards
- Tools: Python functions, har ek ke saath ek JSON Schema jo model ko batata hai ki tool kab aur kin arguments ke saath use karna hai.
- Loop: tool calls chalao, results bhejo, final text tak dohrao.
- Guards: step cap (loop kabhi bina ruke na chale), arguments ki jaanch, tool ki galti ko crash ke bajaye error result banana, aur kate hue (max_tokens) ya mana kiye gaye (refusal) jawab ko pehchanna.
Python AI agent ka poora code
import json
MODEL = "claude-sonnet-5-5" # naya model aaye toh ID Anthropic docs se badaliye
# 1) Tools: har tool ek Python function + ek schema jo model ko batata hai ki kab aur kaise use kare.
def get_weather(city: str) -> dict:
return {"city": city, "temp_c": 31, "sky": "haze"} # asli app mein yahan weather API call hogi
def split_bill(total: float, people: int) -> dict:
if people < 1:
raise ValueError("people kam se kam 1 hona chahiye")
return {"each": round(total / people, 2)}
TOOLS = {
"get_weather": (get_weather, {
"name": "get_weather",
"description": "Kisi shehar ka abhi ka mausam (temperature, aasmaan). Aaj/abhi ke mausam ke liye; forecast ke liye nahi.",
"input_schema": {"type": "object", "properties": {"city": {"type": "string"}},
"required": ["city"], "additionalProperties": False},
}),
"split_bill": (split_bill, {
"name": "split_bill",
"description": "Bill ko logon mein barabar baanto (rupaye mein).",
"input_schema": {"type": "object",
"properties": {"total": {"type": "number"}, "people": {"type": "integer"}},
"required": ["total", "people"], "additionalProperties": False},
}),
}
# 2) Tool chalana: galti ho toh crash nahi, model ko padhne layak error wapas.
def run_tool(call: dict) -> dict:
result = {"type": "tool_result", "tool_use_id": call["id"]}
if call["name"] not in TOOLS:
return {**result, "content": f"unknown tool {call['name']}", "is_error": True}
fn, spec = TOOLS[call["name"]]
schema, args = spec["input_schema"], call["input"]
missing = [k for k in schema["required"] if k not in args]
unknown = [k for k in args if k not in schema["properties"]]
if missing or unknown: # chalane se pehle check: model ke arguments par bharosa nahi
return {**result, "content": f"bad arguments: missing={missing} unknown={unknown}", "is_error": True}
try:
return {**result, "content": json.dumps(fn(**args))}
except Exception as e: # galat argument ya tool ki galti: model agle step mein sudhaar sakta hai
return {**result, "content": f"{type(e).__name__}: {e}", "is_error": True}
# 3) Agent loop: model se poochho, jo tools maange woh chalao, results wapas bhejo, dohrao.
def run_agent(call_model, question: str, max_steps: int = 6) -> str:
messages = [{"role": "user", "content": question}]
specs = [spec for _, spec in TOOLS.values()]
for _ in range(max_steps): # step cap: agent kabhi bina ruke na chale
reply = call_model(messages, specs)
if reply["stop_reason"] == "max_tokens":
return "Ruk gaya: jawab beech mein kat gaya (max_tokens)."
if reply["stop_reason"] == "refusal":
return "Ruk gaya: model ne mana kar diya."
messages.append({"role": "assistant", "content": reply["content"]})
calls = [b for b in reply["content"] if b["type"] == "tool_use"]
if not calls: # koi tool nahi maanga: yahi final jawab hai
return "".join(b["text"] for b in reply["content"] if b["type"] == "text")
messages.append({"role": "user", "content": [run_tool(c) for c in calls]}) # saare results ek saath
return "Ruk gaya: bahut zyada tool steps."
# Asli model (Anthropic SDK; ANTHROPIC_API_KEY environment variable mein):
# from anthropic import Anthropic
# client = Anthropic()
# def claude(messages, specs):
# r = client.messages.create(model=MODEL, max_tokens=1024, tools=specs, messages=messages)
# return r.model_dump(exclude_none=True)
# Offline demo ke liye ek nakli model, taaki code bina API key ke chal jaaye:
def fake_model(messages, specs):
last = messages[-1]["content"]
if isinstance(last, str):
return {"stop_reason": "tool_use", "content": [
{"type": "tool_use", "id": "a1", "name": "get_weather", "input": {"city": "Mumbai"}},
{"type": "tool_use", "id": "a2", "name": "split_bill", "input": {"total": 2400, "people": 4}},
]}
r = {x["tool_use_id"]: json.loads(x["content"]) for x in last}
return {"stop_reason": "end_turn", "content": [{"type": "text", "text":
f"Mumbai: {r['a1']['temp_c']}°C, {r['a1']['sky']}. Har ek ke hisse {r['a2']['each']:g} rupaye."}]}
print(run_agent(fake_model, "Mumbai ka mausam kaisa hai? Aur 2400 ka bill 4 logon mein kitna aayega?"))
print(run_tool({"id": "t9", "name": "split_bill", "input": {"total": 100, "people": 0}}))
print(run_tool({"id": "t10", "name": "split_bill", "input": {"total": 100}}))
# Mumbai: 31°C, haze. Har ek ke hisse 600 rupaye.
# {'type': 'tool_result', 'tool_use_id': 't9', 'content': 'ValueError: people kam se kam 1 hona chahiye', 'is_error': True}
# {'type': 'tool_result', 'tool_use_id': 't10', 'content': "bad arguments: missing=['people'] unknown=[]", 'is_error': True}agent.py (Python 3.9+; sirf standard library, asli model ke liye anthropic package). Chalaiye: python agent.py. Aakhri comment lines expected output hain.
Python agent code kaise kaam karta hai
- Tools ka schema:
descriptionko routing rule ki tarah likhiye, yaani tool kab use karna hai, sirf yeh nahi ki woh kya karta hai.additionalProperties: Falsemodel ke liye hint hai; API ise tab tak enforce nahi karti jab tak strict tool use on na ho, isliye asli jaanchrun_toolkarta hai. - run_tool: chalane se pehle chhoote ya anjaan arguments pakadta hai, aur galat tool naam ya tool ki galti par exception loop ko nahi todta; sab
is_error: Truewala result banta hai, jise padhkar model agle step mein sudhaar sakta hai. Types aur ranges bhi check karni hon tohjsonschemalibrary lagaiye. - Ek turn ke saare results ek saath: Anthropic API mein ek assistant turn ke har
tool_usekatool_resultagle user message mein,tool_use_idke saath, ek saath jaata hai. - stop_reason:
max_tokenspar jawab adhoora ho sakta hai, isliye use na chalaya jaata hai na final jawab maana jaata hai; baar baar ho tohmax_tokensbadhaiye.refusalpar bhi loop saaf message ke saath rukta hai. Production mein in stop messages ke bajaye apna exception raise kijiye, taaki caller asli jawab aur ruke hue run ka farq jaane. - max_steps: sabse simple guard. Repeat detection ke liye dekhiye: AI agent infinite loop kaise rokein (English).
Python agent ko asli Claude model (Anthropic API) se chalana
pip install anthropic kijiye, API key ANTHROPIC_API_KEY environment variable mein rakhiye (code mein kabhi nahi), “Asli model” ke neeche ki saari comment lines (import, client aur claude function) un-comment kijiye, aur aakhri lines mein run_agent(fake_model, ...) ki jagah run_agent(claude, ...) likhiye (do run_tool demo lines hata sakte hain). Asli model ke saath jawab ka text alag hoga, aur get_weather tab bhi nakli data deta hai. model_dump(exclude_none=True) SDK ke jawab ko wahi dict bana deta hai jo loop padhta hai. OpenAI ke saath yahi loop kaise chalta hai: tool calling in Python (English).
Agla step: memory, retries aur multi-agent
- Memory: lambi baatcheet aur pichhla kaam yaad rakhne ke liye dekhiye AI agent memory in Python (English).
- Retries: rate limit aur timeout tool layer mein sambhaliye; dekhiye retries aur rate limits (English).
- Multi-agent: planner, researchers aur checker ki team ke liye dekhiye multi-agent research system (English).
Yeh saare hisse, planner aur source checker ke saath, hamare multi-agent research team course mein step by step bante hain (course English mein hai).
AI agent banate waqt aam galtiyan
- Arguments par bharosa: model galat type, chhoota field ya banaya hua tool naam bhej sakta hai. Chalane se pehle check kijiye (is guide ka
run_toolkeys check karta hai; types aur ranges ke liyejsonschema). - Loop ke andar exception: ek error poora run khatam kar deta hai. Runner mein pakadiye aur error result bana kar bhejiye.
- Koi result chhoot jaana: har tool call ka result chahiye, warna API error deti hai.
- Step cap nahi: bina cap ka loop budget khatam hone tak chal sakta hai.
- Badlaav wale tools bina rok ke: send, delete ya pay jaise tools pehle insaan se poochhein ya sandbox mein chalein.
Is guide ka agla level: isi agent ko production tak le jaana, approval queue, reviewer model aur MCP server ke saath, hamare AI agent + MCP server course mein (course English mein hai).