# Pehla Agent: read-only tools se bounded loop tak

> Ek book query se direct function, fixed workflow aur agent loop ko alag karein; action, observation aur stop conditions padhein; standard Python se success, missing aur budget-exhausted replay karein।

- URL: https://dmxsf.com/hi/wiki/applications/first-agent/
- [DMXSF](https://dmxsf.com/hi/about/)
- शुरुआती
- अपडेट किया गया: 2026-11-27
- Tags: Agents, Tool use

## यह पृष्ठ पूरा करने पर आप

- Direct function call, workflow aur dynamically-choosing loop alag karein।
- Bataayein tool, policy, controller aur trace har ek kya karte hain।
- Ek read-only tool loop chalayein aur verify karein woh kab rukta hai।
- Model jodne se pehle minimal tests aur validation conditions likhein।

Ek minimal agent task padhta hai, agla step chunta hai, observation dekhta hai, phir decide karta hai continue karna hai ya nahi. Language model "agla step chunne" wale hisse ko replace kar sakta hai. Tools program se execute hote hain, result wapas selection logic ko jaata hai. Yeh lesson selection logic ko deterministic rules se simulate karke ek poora loop aankhon ke saamne dekhta hai; phir model, tool protocols aur evaluation wale advanced chapters padhein।

## Ek lookup problem se shuru

Imagine karein ek kitab ki jagah dhoondhni hai. Teen alag implementations:

| Tareeka | Flow kaun tay karta hai | Kis ke liye |
| --- | --- | --- |
| Direct function call | Program ek hi baar catalog poochhta hai | Pakka ek hi lookup request |
| Fixed workflow | Program lookup, results expand aur format orchestrate karta hai | Steps clear, branches enumerable |
| Agent loop | Policy task aur observations se action chunta hai | Intermediate results ke aadhar par aage ke steps adjust karne ho |

Ek kitab dhoondhna usually direct function call se ho jaata hai. Yahan wahi chhota task agent ke components todne ke liye use hota hai, taaki har step alag verify ho. Aage jab kai kitabein dhoondhna ho, tags se filter karna ho, ya failure par doosri query path leni ho - tab dynamic selection ka matlab dikhega।

## Pehle tool, action aur observation saaf likhein

Tool application ke allowed operations hain. Is misaal mein sirf ek read-only `lookup`: input book name, output shelf ya clear missing result. Policy task aur ab tak ke observations padh kar requested action return karti hai. Program sirf `lookup` ya `finish` accept karta hai, isliye policy koi doosra naam de bhi de to khud execute nahi hota।

| Concept | Is misaal mein |
| --- | --- |
| Task | atlas kahan hai, dhoondhna |
| Action | `lookup("atlas")` execute karne ki request |
| Observation | Catalog `shelf A` lautaata hai |
| Trace | Book name aur catalog result ki ek record |
| Stop | Policy final answer de deti hai, ya step limit aa gayi |

Tool observations application ko milne wala data hai; final answer policy banati hai. Real systems mein answer se pehle check hota hai ki uske citations ke observations exist karte hain, current user aur task se belong karte hain. Aage LLM lagane par model ke returned tool name aur parameters bhi sirf request hain - application ki allowlist aur validation se guzar kar hi call hona chahiye।

*Figure: Page ke experiment ka loop: policy sirf request bhejta hai, controller validate karke execute karta hai, observations trajectory mein jama hote hain, jab tak policy finish se jawab na de ya step budget rok na de. Neeche ka code yahi loop chalata hai.*

## Experiment: ek bounded read-only loop poora chalayein

[Tool loop aur stop conditions ka experiment script](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/first-agent/run.py)

Misaal policy ke roop mein normal Python function use karti hai. Pehla step catalog lookup maangta hai, result padhne par doosra step finish. Phir non-existent book aur kam steps wale cases bhi try. Tool sirf memory ke demo data tak pahunchta hai - na account, na model. Code Apple M2 Max par Python 3.12.14 se chala।

```python
from __future__ import annotations

from collections.abc import Callable

Action = tuple[str, str]
Observation = tuple[str, str]
Policy = Callable[[str, tuple[Observation, ...]], Action]

def lookup(book: str) -> str:
    catalog = {"atlas": "shelf A", "algebra": "shelf B"}
    return catalog.get(book, "not in the catalog")

def scripted_policy(task: str, history: tuple[Observation, ...]) -> Action:
    """Stand in for a model so each transition is reproducible."""
    if history:
        return "finish", history[-1][1]
    return "lookup", task

def run(
    task: str,
    policy: Policy,
    max_steps: int,
) -> tuple[str, tuple[Observation, ...]]:
    history: list[Observation] = []
    for _ in range(max_steps):
        action, value = policy(task, tuple(history))
        if not isinstance(value, str):
            raise ValueError("tool arguments and final answers must be strings")
        if action == "finish":
            return value, tuple(history)
        if action != "lookup":
            raise ValueError("unrecognized tool or argument")
        history.append((value, lookup(value)))
    raise RuntimeError("step budget exhausted")

answer, trace = run("atlas", scripted_policy, 2)
missing, _ = run("missing", scripted_policy, 2)
assert answer == "shelf A" and trace == (("atlas", "shelf A"),)
assert missing == "not in the catalog"
print("lookup ok:", answer, trace)
print("catalog missing:", missing)
try:
    run("atlas", scripted_policy, 1)
except RuntimeError:
    print("steps exhausted")
else:
    raise AssertionError("expected the step limit to stop the loop")
```

```text
lookup ok: shelf A (('atlas', 'shelf A'),)
catalog missing: not in the catalog
steps exhausted
```

Note: output numbers original run se hain; print labels Latin transliteration mein likhe gaye hain।

Doosri query par dhyan: catalog mein book nahi hai to clear result aata hai, policy usko padh kar ruk jaati hai. Sirf ek step diya ho to program ne catalog poochh liya par final answer ka step nahi pahuncha - isliye explicitly "steps exhausted". Aise failures record karne se "tool ne jawab nahi diya", "jawab dene ka time hi nahi hua" aur "result mein exist hi nahi karta" alag karna aasaan hai।

नीचे का component `run()` को browser में एक-एक step चलाता है: हर step पर policy ने कौन-सी trace देखी और कौन-सा action लौटाया, और program ने उसके साथ क्या किया। Task, step की सीमा और policy बदलकर देखें कि “मिल गया”, “catalog में नहीं”, “step की सीमा खत्म” और “अनजान tool” कैसे आते हैं।

## Minimal loop ko usable application tak

Ek-ek feature badhaayein, har baar replayable test rakhein:

1. **Ek aur read-only tool.** Jaise category se books browse karna. Har ek ke parameters aur return shape define karein; test se check karein call selection task ke fit hai।
2. **Model policy par shift.** Structured actions use karein; tool name, parameter types aur business constraints check karein. Fixed observations ke saath same task replay karein।
3. **Stop conditions badhayein.** Steps, time aur repeated requests par limits; har stop ka reason record. Tool timeout par rules ke mutabiq retry, aur log mein result rakhein।
4. **Final state aur cost se evaluate.** User ko target info mili ya nahi; phir call count, timeouts aur repeated executions record. Aage agar external state badalne wale tools juden, to write operations ko alag validation aur explicit authorization chahiye।

Framework, retrieval, long-term memory aur judge ek saath mat jodein. Pehle chhote loop ko clear inputs, missing data aur budget-exhausted - teeno mein explainable output dilayein; phir [structured output aur function calling](https://dmxsf.com/hi/wiki/applications/structured-output-and-function-calling/), [context aur memory](https://dmxsf.com/hi/wiki/applications/context-and-memory/) aur [agent evaluation](https://dmxsf.com/hi/wiki/applications/agent-evaluation/) se ek-ek karke expand karein।

## Summary aur exercises

- Tools operations execute karte hain, policy actions chunti hai, loop context aur termination control karta hai।
- Har tool call ek observation chhodta hai - aage ke decisions ke paas review-layak aadhar hota hai।
- Ek read-only query se shuru karein; phir tools, model aur evaluation।

### Quick self-test

**1. Catalog lookup ka operation kaun execute karta hai?**

- [x] Application ka read-only tool।
- [ ] Policy ne jo tool naam return kiya।

> Naam sirf request hai; waqai execution program ka kaam hai।

**2. Tool kahe ki book catalog mein nahi - kya hoga?**

- [ ] System seedha mil gaya naqp kar dega।
- [x] Policy observation padhkar missing batayegi।

> Missing data explainable normal tool result hai।

**3. Repeated calls ko infinite jaane se kaun rokta hai?**

- [x] Loop controller ke step ya repeat limits।
- [ ] Book ka naam khud।

> Termination conditions application ki zimmedari hain।

**4. Dynamic decision kab layak hai?**

- [ ] Jab ek fixed lookup kaam kar jaaye।
- [x] Jab aage ke operations intermediate results par nirbhar hon।

> Predictable short flows function ya workflow se shuru ho sakte hain।

### Bataayein unknown book kaun si layer handle kare

Policy se catalog mein na hone wali kitab lookup karwayein. "Catalog mein nahi" ka faisla tool, loop ya final answer kaun kare? Agar policy same kitab baar-baar lookup kare, kaun si layer rokne ki zimmedar hai?

<details>
<summary>Reference answers</summary>

Catalog tool missing return karta hai; policy us observation padhkar finish ho sakti hai aur haal bata sakti hai. Loop ke step limit drain ka kaam karti hai; asli application mein same tool + same parameters ke repeat calls ki ginti bhi rakh sakte hain, aur stop ka reason record।

</details>

## Aage padhein

- [Anthropic ka workflows aur agents design](https://www.anthropic.com/research/building-effective-agents)।
- Aage padhein [structured output aur function calling](https://dmxsf.com/hi/wiki/applications/structured-output-and-function-calling/) aur [agents aur tool calling](https://dmxsf.com/hi/wiki/applications/agents-and-tool-calling/)।

## सहायक कोड

[First agent: a bounded tool loop](https://github.com/dmxsf/dmxsf/tree/main/labs/applications/first-agent): Run a read-only lookup loop and check success, absence, and the step budget.

- सहायक रिपॉज़िटरी में चलाएँ (--quick से तेज़ जाँच): `uv run dmxsf run applications/first-agent`
- [प्रयोग स्क्रिप्ट देखें](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/first-agent/run.py)
- [प्रयोग विवरण](https://github.com/dmxsf/dmxsf/blob/main/labs/applications/first-agent/README.en.md)
- [`first_agent.py`](https://github.com/dmxsf/dmxsf/blob/main/src/dmxsf/applications/first_agent.py)
- [सूची में देखें](https://dmxsf.com/hi/code/#first-agent)

## अक्सर पूछे जाने वाले सवाल

### Ek value lookup ke liye Agent chahiye?

Ek clear lookup usually seedha function call hai. Task ko intermediate results ke aadhar par agla step badalna ho, tab agent loop use hota hai।

### Model bole tool call karna hai - waqai kaun execute karta hai?

Application controller tool name aur parameters verify karke execute karta hai, aur observation save karta hai।

### Minimal misaal mein bhi step limit kyun?

Policy repeat kar sakti hai ya jawab nahi de sakti. Limit cost control karti hai aur failure ko clear reason deti hai।
