# Smolagents

## Docs

- [Agents - गाइडेड टूर](https://huggingface.co/docs/smolagents/v1.22.0/hi/guided_tour.md)
- [`smolagents`](https://huggingface.co/docs/smolagents/v1.22.0/hi/index.md)
- [मल्टी-स्टेप एजेंट्स कैसे काम करते हैं?](https://huggingface.co/docs/smolagents/v1.22.0/hi/conceptual_guides/react.md)
- [Agents का परिचय](https://huggingface.co/docs/smolagents/v1.22.0/hi/conceptual_guides/intro_agents.md)
- [Agents](https://huggingface.co/docs/smolagents/v1.22.0/hi/reference/agents.md)
- [Tools](https://huggingface.co/docs/smolagents/v1.22.0/hi/reference/tools.md)
- [मल्टी-एजेंट सिस्टम का आयोजन करें 🤖🤝🤖](https://huggingface.co/docs/smolagents/v1.22.0/hi/examples/multiagents.md)
- [एजेंटिक RAG](https://huggingface.co/docs/smolagents/v1.22.0/hi/examples/rag.md)
- [Text-to-SQL](https://huggingface.co/docs/smolagents/v1.22.0/hi/examples/text_to_sql.md)
- [सुरक्षित कोड एक्जीक्यूशन](https://huggingface.co/docs/smolagents/v1.22.0/hi/tutorials/secure_code_execution.md)
- [Tools](https://huggingface.co/docs/smolagents/v1.22.0/hi/tutorials/tools.md)
- [अच्छे Agents का निर्माण](https://huggingface.co/docs/smolagents/v1.22.0/hi/tutorials/building_good_agents.md)
- [OpenTelemetry के साथ runs का निरीक्षण](https://huggingface.co/docs/smolagents/v1.22.0/hi/tutorials/inspect_runs.md)

### Agents - गाइडेड टूर
https://huggingface.co/docs/smolagents/v1.22.0/hi/guided_tour.md

# Agents - गाइडेड टूर

<DocNotebookDropdown
  classNames="absolute z-10 right-0 top-0"
  options={[
    {label: "Mixed", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/guided_tour.ipynb"},
    {label: "PyTorch", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/guided_tour.ipynb"},
    {label: "TensorFlow", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/guided_tour.ipynb"},
    {label: "Mixed", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/guided_tour.ipynb"},
    {label: "PyTorch", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/guided_tour.ipynb"},
    {label: "TensorFlow", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/guided_tour.ipynb"},
]} />

इस गाइडेड विजिट में, आप सीखेंगे कि एक एजेंट कैसे बनाएं, इसे कैसे चलाएं, और अपने यूज-केस के लिए बेहतर काम करने के लिए इसे कैसे कस्टमाइज़ करें।

### अपना Agent बनाना

एक मिनिमल एजेंट को इनिशियलाइज़ करने के लिए, आपको कम से कम इन दो आर्ग्यूमेंट्स की आवश्यकता है:

- `model`, आपके एजेंट को पावर देने के लिए एक टेक्स्ट-जनरेशन मॉडल - क्योंकि एजेंट एक सिंपल LLM से अलग है, यह एक सिस्टम है जो LLM को अपने इंजन के रूप में उपयोग करता है। आप इनमें से कोई भी विकल्प उपयोग कर सकते हैं:
    - [TransformersModel](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.TransformersModel) `transformers` पाइपलाइन को पहले से इनिशियलाइज़ करता है जो `transformers` का उपयोग करके आपकी लोकल मशीन पर इन्फरेंस चलाने के लिए होता है।
    - [InferenceClientModel](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.InferenceClientModel) अंदर से `huggingface_hub.InferenceClient` का लाभ उठाता है।
    - [LiteLLMModel](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.LiteLLMModel) आपको [LiteLLM](https://docs.litellm.ai/) के माध्यम से 100+ अलग-अलग मॉडल्स को कॉल करने देता है!

- `tools`, `Tools` की एक लिस्ट जिसे एजेंट टास्क को हल करने के लिए उपयोग कर सकता है। यह एक खाली लिस्ट हो सकती है। आप ऑप्शनल आर्ग्यूमेंट `add_base_tools=True` को परिभाषित करके अपनी `tools` लिस्ट के ऊपर डिफ़ॉल्ट टूलबॉक्स भी जोड़ सकते हैं।

एक बार जब आपके पास ये दो आर्ग्यूमेंट्स, `tools` और `model` हैं, तो आप एक एजेंट बना सकते हैं और इसे चला सकते हैं। आप कोई भी LLM उपयोग कर सकते हैं, या तो [Hugging Face API](https://huggingface.co/docs/api-inference/en/index), [transformers](https://github.com/huggingface/transformers/), [ollama](https://ollama.com/), या [LiteLLM](https://www.litellm.ai/) के माध्यम से।

<hfoptions id="एक LLM चुनें">
<hfoption id="Hugging Face API">

Hugging Face API टोकन के बिना उपयोग करने के लिए मुफ्त है, लेकिन फिर इसमें रेट लिमिटेशन होगी।

गेटेड मॉडल्स तक पहुंचने या PRO अकाउंट के साथ अपनी रेट लिमिट्स बढ़ाने के लिए, आपको एनवायरनमेंट वेरिएबल `HF_TOKEN` सेट करना होगा या `InferenceClientModel` के इनिशियलाइजेशन पर `token` वेरिएबल पास करना होगा।

```python
from smolagents import CodeAgent, InferenceClientModel

model_id = "meta-llama/Llama-3.3-70B-Instruct"

model = InferenceClientModel(model_id=model_id, token="<YOUR_HUGGINGFACEHUB_API_TOKEN>")
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
<hfoption id="Local Transformers Model">

```python
from smolagents import CodeAgent, TransformersModel

model_id = "meta-llama/Llama-3.2-3B-Instruct"

model = TransformersModel(model_id=model_id)
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
<hfoption id="OpenAI या Anthropic API">

`LiteLLMModel` का उपयोग करने के लिए, आपको एनवायरनमेंट वेरिएबल `ANTHROPIC_API_KEY` या `OPENAI_API_KEY` सेट करना होगा, या इनिशियलाइजेशन पर `api_key` वेरिएबल पास करना होगा।

```python
from smolagents import CodeAgent, LiteLLMModel

model = LiteLLMModel(model_id="anthropic/claude-3-5-sonnet-latest", api_key="YOUR_ANTHROPIC_API_KEY") # Could use 'gpt-4o'
agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
<hfoption id="Ollama">

```python
from smolagents import CodeAgent, LiteLLMModel

model = LiteLLMModel(
    model_id="ollama_chat/llama3.2", # This model is a bit weak for agentic behaviours though
    api_base="http://localhost:11434", # replace with 127.0.0.1:11434 or remote open-ai compatible server if necessary
    api_key="YOUR_API_KEY" # replace with API key if necessary
    num_ctx=8192 # ollama default is 2048 which will fail horribly. 8192 works for easy tasks, more is better. Check https://huggingface.co/spaces/NyxKrage/LLM-Model-VRAM-Calculator to calculate how much VRAM this will need for the selected model.
)

agent = CodeAgent(tools=[], model=model, add_base_tools=True)

agent.run(
    "Could you give me the 118th number in the Fibonacci sequence?",
)
```
</hfoption>
</hfoptions>

#### CodeAgent और ToolCallingAgent

[CodeAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.CodeAgent) हमारा डिफ़ॉल्ट एजेंट है। यह हर स्टेप पर पायथन कोड स्निपेट्स लिखेगा और एक्जीक्यूट करेगा।

डिफ़ॉल्ट रूप से, एक्जीक्यूशन आपके लोकल एनवायरनमेंट में किया जाता है।
यह सुरक्षित होना चाहिए क्योंकि केवल वही फ़ंक्शंस कॉल किए जा सकते हैं जो आपने प्रदान किए हैं (विशेष रूप से यदि यह केवल Hugging Face टूल्स हैं) और पूर्व-परिभाषित सुरक्षित फ़ंक्शंस जैसे `print` या `math` मॉड्यूल से फ़ंक्शंस, इसलिए आप पहले से ही सीमित हैं कि क्या एक्जीक्यूट किया जा सकता है।

पायथन इंटरप्रेटर डिफ़ॉल्ट रूप से सेफ लिस्ट के बाहर इम्पोर्ट की अनुमति नहीं देता है, इसलिए सबसे स्पष्ट अटैक समस्या नहीं होनी चाहिए।
आप अपने [CodeAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.CodeAgent) के इनिशियलाइजेशन पर आर्ग्यूमेंट `additional_authorized_imports` में स्ट्रिंग्स की लिस्ट के रूप में अतिरिक्त मॉड्यूल्स को अधिकृत कर सकते हैं।

```py
model = InferenceClientModel()
agent = CodeAgent(tools=[], model=model, additional_authorized_imports=['requests', 'bs4'])
agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?")
```

> [!WARNING]
> LLM आर्बिट्ररी कोड जनरेट कर सकता है जो फिर एक्जीक्यूट किया जाएगा: कोई असुरक्षित इम्पोर्ट न जोड़ें!

एक्जीक्यूशन किसी भी कोड पर रुक जाएगा जो एक अवैध ऑपरेशन करने का प्रयास करता है या यदि एजेंट द्वारा जनरेट किए गए कोड में एक रेगुलर पायथन एरर है।

आप [E2B कोड एक्जीक्यूटर](https://e2b.dev/docs#what-is-e2-b) या Docker का उपयोग लोकल पायथन इंटरप्रेटर के बजाय कर सकते हैं। E2B के लिए, पहले [`E2B_API_KEY` एनवायरनमेंट वेरिएबल सेट करें](https://e2b.dev/dashboard?tab=keys) और फिर एजेंट इनिशियलाइजेशन पर `executor_type="e2b"` पास करें। Docker के लिए, इनिशियलाइजेशन के दौरान `executor_type="docker"` पास करें।

> [!TIP]
> कोड एक्जीक्यूशन के बारे में और जानें [इस ट्यूटोरियल में](tutorials/secure_code_execution)।

हम JSON-जैसे ब्लॉब्स के रूप में एक्शन लिखने के व्यापक रूप से उपयोग किए जाने वाले तरीके का भी समर्थन करते हैं: यह [ToolCallingAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.ToolCallingAgent) है, यह बहुत कुछ [CodeAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.CodeAgent) की तरह ही काम करता है, बेशक `additional_authorized_imports` के बिना क्योंकि यह कोड एक्जीक्यूट नहीं करता।

```py
from smolagents import ToolCallingAgent

agent = ToolCallingAgent(tools=[], model=model)
agent.run("Could you get me the title of the page at url 'https://huggingface.co/blog'?")
```

### एजेंट रन का निरीक्षण

रन के बाद क्या हुआ यह जांचने के लिए यहाँ कुछ उपयोगी एट्रिब्यूट्स हैं:
- `agent.logs` एजेंट के फाइन-ग्रेन्ड लॉग्स को स्टोर करता है। एजेंट के रन के हर स्टेप पर, सब कुछ एक डिक्शनरी में स्टोर किया जाता है जो फिर `agent.logs` में जोड़ा जाता है।
- `agent.write_memory_to_messages()` चलाने से LLM के लिए एजेंट के लॉग्स की एक इनर मेमोरी बनती है, चैट मैसेज की लिस्ट के रूप में। यह मेथड लॉग के प्रत्येक स्टेप पर जाता है और केवल वही स्टोर करता है जिसमें यह एक मैसेज के रूप में रुचि रखता है: उदाहरण के लिए, यह सिस्टम प्रॉम्प्ट और टास्क को अलग-अलग मैसेज के रूप में सेव करेगा, फिर प्रत्येक स्टेप के लिए यह LLM आउटपुट को एक मैसेज के रूप में और टूल कॉल आउटपुट को दूसरे मैसेज के रूप में स्टोर करेगा।

## टूल्स

टूल एक एटॉमिक फ़ंक्शन है जिसे एजेंट द्वारा उपयोग किया जाता है। LLM द्वारा उपयोग किए जाने के लिए, इसे कुछ एट्रिब्यूट्स की भी आवश्यकता होती है जो इसकी API बनाते हैं और LLM को यह बताने के लिए उपयोग किए जाएंगे कि इस टूल को कैसे कॉल करें:
- एक नाम
- एक विवरण
- इनपुट प्रकार और विवरण
- एक आउटपुट प्रकार

आप उदाहरण के लिए [PythonInterpreterTool](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.PythonInterpreterTool) को चेक कर सकते हैं: इसमें एक नाम, विवरण, इनपुट विवरण, एक आउटपुट प्रकार, और एक्शन करने के लिए एक `forward` मेथड है।

जब एजेंट इनिशियलाइज़ किया जाता है, टूल एट्रिब्यूट्स का उपयोग एक टूल विवरण जनरेट करने के लिए किया जाता है जो एजेंट के सिस्टम प्रॉम्प्ट में बेक किया जाता है। यह एजेंट को बताता है कि वह कौन से टूल्स उपयोग कर सकता है और क्यों।

### डिफ़ॉल्ट टूलबॉक्स

`smolagents` एजेंट्स को सशक्त बनाने के लिए एक डिफ़ॉल्ट टूलबॉक्स के साथ आता है, जिसे आप आर्ग्यूमेंट `add_base_tools=True` के साथ अपने एजेंट में इनिशियलाइजेशन पर जोड़ सकते हैं:

- **DuckDuckGo वेब सर्च**: DuckDuckGo ब्राउज़र का उपयोग करके वेब सर्च करता है।
- **पायथन कोड इंटरप्रेटर**: आपका LLM जनरेटेड पायथन कोड एक सुरक्षित एनवायरनमेंट में चलाता है। यह टूल [ToolCallingAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.ToolCallingAgent) में केवल तभी जोड़ा जाएगा जब आप इसे `add_base_tools=True` के साथ इनिशियलाइज़ करते हैं, क्योंकि कोड-बेस्ड एजेंट पहले से ही नेटिव रूप से पायथन कोड एक्जीक्यूट कर सकता है
- **ट्रांसक्राइबर**: Whisper-Turbo पर बनाया गया एक स्पीच-टू-टेक्स्ट पाइपलाइन जो ऑडियो को टेक्स्ट में ट्रांसक्राइब करता है।

आप मैन्युअल रूप से एक टूल का उपयोग उसके आर्ग्यूमेंट्स के साथ कॉल करके कर सकते हैं।

```python
from smolagents import WebSearchTool

search_tool = WebSearchTool()
print(search_tool("Who's the current president of Russia?"))
```

### अपने कस्टम टूल बनाएं  

आप ऐसे उपयोग के मामलों के लिए अपने खुद के टूल बना सकते हैं जो Hugging Face के डिफ़ॉल्ट टूल्स द्वारा कवर नहीं किए गए हैं।  
उदाहरण के लिए, चलिए एक टूल बनाते हैं जो दिए गए कार्य (task) के लिए हब से सबसे अधिक डाउनलोड किए गए मॉडल को रिटर्न करता है।  

आप नीचे दिए गए कोड से शुरुआत करेंगे। 

```python
from huggingface_hub import list_models

task = "text-classification"

most_downloaded_model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
print(most_downloaded_model.id)
```

यह कोड आसानी से टूल में बदला जा सकता है, बस इसे एक फ़ंक्शन में रैप करें और `tool` डेकोरेटर जोड़ें:  
यह टूल बनाने का एकमात्र तरीका नहीं है: आप इसे सीधे [Tool](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool) का सबक्लास बनाकर भी परिभाषित कर सकते हैं, जो आपको अधिक लचीलापन प्रदान करता है, जैसे भारी क्लास एट्रिब्यूट्स को इनिशियलाइज़ करने की संभावना।  

चलो देखते हैं कि यह दोनों विकल्पों के लिए कैसे काम करता है:

<hfoptions id="build-a-tool">
<hfoption id="@tool के साथ एक फ़ंक्शन को डेकोरेट करें">

```py
from smolagents import tool

@tool
def model_download_tool(task: str) -> str:
    """
    This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub.
    It returns the name of the checkpoint.

    Args:
        task: The task for which to get the download count.
    """
    most_downloaded_model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
    return most_downloaded_model.id
```

फ़ंक्शन को चाहिए:  
- एक स्पष्ट नाम: नाम टूल के कार्य को स्पष्ट रूप से बताने वाला होना चाहिए ताकि इसे चलाने वाले LLM को आसानी हो। चूंकि यह टूल कार्य के लिए सबसे अधिक डाउनलोड किए गए मॉडल को लौटाता है, इसका नाम `model_download_tool` रखा गया है।  
- इनपुट और आउटपुट पर टाइप हिंट्स।
- एक विवरण: इसमें 'Args:' भाग शामिल होना चाहिए, जिसमें प्रत्येक आर्ग्युमेंट का वर्णन (बिना टाइप संकेत के) किया गया हो। यह विवरण एक निर्देश मैनुअल की तरह होता है जो LLM को टूल चलाने में मदद करता है। इसे अनदेखा न करें।  
इन सभी तत्वों को एजेंट की सिस्टम प्रॉम्प्ट में स्वचालित रूप से शामिल किया जाएगा: इसलिए इन्हें यथासंभव स्पष्ट बनाने का प्रयास करें!  

> [!TIP]  
> यह परिभाषा प्रारूप `apply_chat_template` में उपयोग की गई टूल स्कीमा जैसा ही है, केवल अतिरिक्त `tool` डेकोरेटर जोड़ा गया है: हमारे टूल उपयोग API के बारे में अधिक पढ़ें [यहाँ](https://huggingface.co/blog/unified-tool-use#passing-tools-to-a-chat-template)।  
</hfoption>
<hfoption id="सबक्लास टूल">

```py
from smolagents import Tool

class ModelDownloadTool(Tool):
    name = "model_download_tool"
    description = "This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub. It returns the name of the checkpoint."
    inputs = {"task": {"type": "string", "description": "The task for which to get the download count."}}
    output_type = "string"

    def forward(self, task: str) -> str:
        most_downloaded_model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
        return most_downloaded_model.id
```

सबक्लास को निम्नलिखित एट्रिब्यूट्स की आवश्यकता होती है:  
- एक स्पष्ट `name`: नाम टूल के कार्य को स्पष्ट रूप से बताने वाला होना चाहिए।  
- एक `description`: यह भी LLM के लिए निर्देश मैनुअल की तरह काम करता है।  
- इनपुट प्रकार और उनके विवरण।  
- आउटपुट प्रकार।  
इन सभी एट्रिब्यूट्स को एजेंट की सिस्टम प्रॉम्प्ट में स्वचालित रूप से शामिल किया जाएगा, इन्हें स्पष्ट और विस्तृत बनाएं।  
</hfoption>
</hfoptions>


आप सीधे अपने एजेंट को इनिशियलाइज़ कर सकते हैं:  
```py
from smolagents import CodeAgent, InferenceClientModel
agent = CodeAgent(tools=[model_download_tool], model=InferenceClientModel())
agent.run(
    "Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub?"
)
```

लॉग्स इस प्रकार होंगे:  
```text
╭──────────────────────────────────────── New run ─────────────────────────────────────────╮
│                                                                                          │
│ Can you give me the name of the model that has the most downloads in the 'text-to-video' │
│ task on the Hugging Face Hub?                                                            │
│                                                                                          │
╰─ InferenceClientModel - Qwen/Qwen2.5-Coder-32B-Instruct ───────────────────────────────────────────╯
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 0 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
╭─ Executing this code: ───────────────────────────────────────────────────────────────────╮
│   1 model_name = model_download_tool(task="text-to-video")                               │
│   2 print(model_name)                                                                    │
╰──────────────────────────────────────────────────────────────────────────────────────────╯
Execution logs:
ByteDance/AnimateDiff-Lightning

Out: None
[Step 0: Duration 0.27 seconds| Input tokens: 2,069 | Output tokens: 60]
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ Step 1 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
╭─ Executing this code: ───────────────────────────────────────────────────────────────────╮
│   1 final_answer("ByteDance/AnimateDiff-Lightning")                                      │
╰──────────────────────────────────────────────────────────────────────────────────────────╯
Out - Final answer: ByteDance/AnimateDiff-Lightning
[Step 1: Duration 0.10 seconds| Input tokens: 4,288 | Output tokens: 148]
Out[20]: 'ByteDance/AnimateDiff-Lightning'
```

 [!TIP]  
> टूल्स के बारे में अधिक पढ़ें [dedicated tutorial](./tutorials/tools#टूल-क्या-है-और-इसे-कैसे-बनाएं) में।  

## मल्टी-एजेंट्स  

Microsoft के फ्रेमवर्क [Autogen](https://huggingface.co/papers/2308.08155) के साथ मल्टी-एजेंट सिस्टम्स की शुरुआत हुई।  

इस प्रकार के फ्रेमवर्क में, आपके कार्य को हल करने के लिए कई एजेंट्स एक साथ काम करते हैं, न कि केवल एक।  
यह अधिकांश बेंचमार्क्स पर बेहतर प्रदर्शन देता है। इसका कारण यह है कि कई कार्यों के लिए, एक सर्व-समावेशी प्रणाली के बजाय, आप उप-कार्यों पर विशेषज्ञता रखने वाली इकाइयों को पसंद करेंगे।  इस तरह, अलग-अलग टूल सेट्स और मेमोरी वाले एजेंट्स के पास विशेषकरण की अधिक कुशलता होती है। उदाहरण के लिए, कोड उत्पन्न करने वाले एजेंट की मेमोरी को वेब सर्च एजेंट द्वारा देखे गए वेबपेजों की सभी सामग्री से क्यों भरें? इन्हें अलग रखना बेहतर है।  

आप `smolagents` का उपयोग करके आसानी से श्रेणीबद्ध मल्टी-एजेंट सिस्टम्स बना सकते हैं।  

ऐसा करने के लिए, एजेंट को `ManagedAgent` ऑब्जेक्ट में समाहित करें। यह ऑब्जेक्ट `agent`, `name`, और एक `description` जैसे तर्कों की आवश्यकता होती है, जो फिर मैनेजर एजेंट की सिस्टम प्रॉम्प्ट में एम्बेड किया जाता है  

यहां एक एजेंट बनाने का उदाहरण दिया गया है जो हमारे `WebSearchTool` का उपयोग करके एक विशिष्ट वेब खोज एजेंट को प्रबंधित करता है।

```py
from smolagents import CodeAgent, InferenceClientModel, WebSearchTool, ManagedAgent

model = InferenceClientModel()

web_agent = CodeAgent(tools=[WebSearchTool()], model=model)

managed_web_agent = ManagedAgent(
    agent=web_agent,
    name="web_search",
    description="Runs web searches for you. Give it your query as an argument."
)

manager_agent = CodeAgent(
    tools=[], model=model, managed_agents=[managed_web_agent]
)

manager_agent.run("Who is the CEO of Hugging Face?")
```

> [!TIP]
> कुशल मल्टी-एजेंट इंप्लीमेंटेशन का एक विस्तृत उदाहरण देखने के लिए, [कैसे हमने अपने मल्टी-एजेंट सिस्टम को GAIA लीडरबोर्ड के शीर्ष पर पहुंचाया](https://huggingface.co/blog/beating-gaia) पर जाएं।  


## अपने एजेंट से बात करें और उसके विचारों को एक शानदार Gradio इंटरफेस में विज़ुअलाइज़ करें  

आप `GradioUI` का उपयोग करके अपने एजेंट को इंटरैक्टिव तरीके से कार्य सौंप सकते हैं और उसके सोचने और निष्पादन की प्रक्रिया को देख सकते हैं। नीचे एक उदाहरण दिया गया है:

```py
from smolagents import (
    load_tool,
    CodeAgent,
    InferenceClientModel,
    GradioUI
)

# Import tool from Hub
image_generation_tool = load_tool("m-ric/text-to-image", trust_remote_code=True)

model = InferenceClientModel(model_id=model_id)

# Initialize the agent with the image generation tool
agent = CodeAgent(tools=[image_generation_tool], model=model)

GradioUI(agent).launch()
```

अंदरूनी तौर पर, जब यूजर एक नया उत्तर टाइप करता है, तो एजेंट को `agent.run(user_request, reset=False)` के साथ लॉन्च किया जाता है।  
यहाँ `reset=False` फ्लैग का मतलब है कि एजेंट की मेमोरी इस नए कार्य को लॉन्च करने से पहले क्लियर नहीं होती, जिससे बातचीत जारी रहती है।  

आप इस `reset=False` आर्ग्युमेंट का उपयोग किसी भी अन्य एजेंटिक एप्लिकेशन में बातचीत जारी रखने के लिए कर सकते हैं।  

## अगले कदम  

अधिक गहन उपयोग के लिए, आप हमारे ट्यूटोरियल्स देख सकते हैं:  
- [हमारे कोड एजेंट्स कैसे काम करते हैं इसका विवरण](./tutorials/secure_code_execution)  
- [अच्छे एजेंट्स बनाने के लिए यह गाइड](./tutorials/building_good_agents)  
- [टूल उपयोग के लिए इन-डेप्थ गाइड ](./tutorials/building_good_agents)।  


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/guided_tour.md" />

### `smolagents`
https://huggingface.co/docs/smolagents/v1.22.0/hi/index.md

# `smolagents`

<div class="flex justify-center">
    <img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/license_to_call.png" width=100%/>
</div>

यह लाइब्रेरी पावरफुल एजेंट्स बनाने के लिए सबसे सरल फ्रेमवर्क है! वैसे, "एजेंट्स" हैं क्या? हम अपनी परिभाषा [इस पेज पर](conceptual_guides/intro_agents) प्रदान करते हैं, जहाँ आपको यह भी पता चलेगा कि इन्हें कब उपयोग करें या न करें (स्पॉइलर: आप अक्सर एजेंट्स के बिना बेहतर काम कर सकते हैं)।

यह लाइब्रेरी प्रदान करती है:

✨ **सरलता**: Agents का लॉजिक लगभग एक हजार लाइन्स ऑफ़ कोड में समाहित है। हमने रॉ कोड के ऊपर एब्स्ट्रैक्शन को न्यूनतम आकार में रखा है!

🌐 **सभी LLM के लिए सपोर्ट**: यह हब पर होस्ट किए गए मॉडल्स को उनके `transformers` वर्जन में या हमारे इन्फरेंस API के माध्यम से सपोर्ट करता है, साथ ही OpenAI, Anthropic से भी... किसी भी LLM से एजेंट को पावर करना वास्तव में आसान है।

🧑‍💻 **कोड Agents के लिए फर्स्ट-क्लास सपोर्ट**, यानी ऐसे एजेंट्स जो अपनी एक्शन्स को कोड में लिखते हैं (कोड लिखने के लिए उपयोग किए जाने वाले एजेंट्स के विपरीत), [यहाँ और पढ़ें](tutorials/secure_code_execution)।

🤗 **हब इंटीग्रेशन**: आप टूल्स को हब पर शेयर और लोड कर सकते हैं, और आगे और भी बहुत कुछ आने वाला है!
!

<div class="mt-10">
  <div class="w-full flex flex-col space-y-4 md:space-y-0 md:grid md:grid-cols-2 md:gap-y-4 md:gap-x-5">
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./guided_tour"
      ><div class="w-full text-center bg-gradient-to-br from-blue-400 to-blue-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">गाइडेड टूर</div>
      <p class="text-gray-700">बेसिक्स सीखें और एजेंट्स का उपयोग करने में परिचित हों। यदि आप पहली बार एजेंट्स का उपयोग कर रहे हैं तो यहाँ से शुरू करें!</p>
    </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./examples/text_to_sql"
      ><div class="w-full text-center bg-gradient-to-br from-indigo-400 to-indigo-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">हाउ-टू गाइड्स</div>
      <p class="text-gray-700">एक विशिष्ट लक्ष्य प्राप्त करने में मदद के लिए गाइड: SQL क्वेरी जनरेट और टेस्ट करने के लिए एजेंट बनाएं!</p>
    </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./conceptual_guides/intro_agents"
      ><div class="w-full text-center bg-gradient-to-br from-pink-400 to-pink-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">कॉन्सेप्चुअल गाइड्स</div>
      <p class="text-gray-700">महत्वपूर्ण विषयों की बेहतर समझ बनाने के लिए उच्च-स्तरीय व्याख्याएं।</p>
   </a>
    <a class="!no-underline border dark:border-gray-700 p-5 rounded-lg shadow hover:shadow-lg" href="./tutorials/building_good_agents"
      ><div class="w-full text-center bg-gradient-to-br from-purple-400 to-purple-500 rounded-lg py-1.5 font-semibold mb-5 text-white text-lg leading-relaxed">ट्यूटोरियल्स</div>
      <p class="text-gray-700">एजेंट्स बनाने के महत्वपूर्ण पहलुओं को कवर करने वाले क्ट्यूटोरियल्स।</p>
    </a>
  </div>
</div>

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/index.md" />

### मल्टी-स्टेप एजेंट्स कैसे काम करते हैं?
https://huggingface.co/docs/smolagents/v1.22.0/hi/conceptual_guides/react.md

# मल्टी-स्टेप एजेंट्स कैसे काम करते हैं?

ReAct फ्रेमवर्क ([Yao et al., 2022](https://huggingface.co/papers/2210.03629)) वर्तमान में एजेंट्स बनाने का मुख्य दृष्टिकोण है।

नाम दो शब्दों, "Reason" (तर्क) और "Act" (क्रिया) के संयोजन पर आधारित है। वास्तव में, इस आर्किटेक्चर का पालन करने वाले एजेंट अपने कार्य को उतने चरणों में हल करेंगे जितने आवश्यक हों, प्रत्येक चरण में एक Reasoning कदम होगा, फिर एक Action कदम होगा, जहाँ यह टूल कॉल्स तैयार करेगा जो उसे कार्य को हल करने के करीब ले जाएंगे।

ReAct प्रक्रिया में पिछले चरणों की मेमोरी रखना शामिल है।

> [!TIP]
> मल्टी-स्टेप एजेंट्स के बारे में अधिक जानने के लिए [Open-source LLMs as LangChain Agents](https://huggingface.co/blog/open-source-llms-as-agents) ब्लॉग पोस्ट पढ़ें।

यहाँ एक वीडियो ओवरव्यू है कि यह कैसे काम करता है:

<div class="flex justify-center">
    <img
        class="block dark:hidden"
        src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Agent_ManimCE.gif"
    />
    <img
        class="hidden dark:block"
        src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/Agent_ManimCE.gif"
    />
</div>

![ReAct एजेंट का फ्रेमवर्क](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/blog/open-source-llms-as-agents/ReAct.png)

हम दो प्रकार के ToolCallingAgent को लागू करते हैं:
- [ToolCallingAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.ToolCallingAgent) अपने आउटपुट में टूल कॉल को JSON के रूप में जनरेट करता है।
- [CodeAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.CodeAgent) ToolCallingAgent का एक नया प्रकार है जो अपने टूल कॉल को कोड के ब्लॉब्स के रूप में जनरेट करता है, जो उन LLM के लिए वास्तव में अच्छी तरह काम करता है जिनका कोडिंग प्रदर्शन मजबूत है।


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/conceptual_guides/react.md" />

### Agents का परिचय
https://huggingface.co/docs/smolagents/v1.22.0/hi/conceptual_guides/intro_agents.md

# Agents का परिचय

## 🤔 Agents क्या हैं?

AI का उपयोग करने वाली किसी भी कुशल प्रणाली को LLM को वास्तविक दुनिया तक किसी प्रकार की पहुंच प्रदान करने की आवश्यकता होगी: उदाहरण के लिए बाहरी जानकारी प्राप्त करने के लिए एक खोज टूल को कॉल करने की संभावना, या किसी कार्य को हल करने के लिए कुछ प्रोग्राम पर कार्य करने की। दूसरे शब्दों में, LLM में ***agency*** होनी चाहिए। एजेंटिक प्रोग्राम LLM के लिए बाहरी दुनिया का प्रवेश द्वार हैं।

> [!TIP]
> AI Agents वे **प्रोग्राम हैं जहां LLM आउटपुट वर्कफ़्लो को नियंत्रित करते हैं**।

LLM का उपयोग करने वाली कोई भी प्रणाली LLM आउटपुट को कोड में एकीकृत करेगी। कोड वर्कफ़्लो पर LLM के इनपुट का प्रभाव सिस्टम में LLM की एजेंसी का स्तर है।

ध्यान दें कि इस परिभाषा के साथ, "agent" एक अलग, 0 या 1 परिभाषा नहीं है: इसके बजाय, "agency" एक निरंतर स्पेक्ट्रम पर विकसित होती है, जैसे-जैसे आप अपने वर्कफ़्लो पर LLM को अधिक या कम शक्ति देते हैं।

नीचे दी गई तालिका में देखें कि कैसे एजेंसी विभिन्न प्रणालियों में भिन्न हो सकती है:

| एजेंसी स्तर | विवरण | इसे क्या कहा जाता है | उदाहरण पैटर्न |
|------------|---------|-------------------|----------------|
| ☆☆☆ | LLM आउटपुट का प्रोग्राम प्रवाह पर कोई प्रभाव नहीं | सरल प्रोसेसर | `process_llm_output(llm_response)` |
| ★☆☆ | LLM आउटपुट if/else स्विच निर्धारित करता है | राउटर | `if llm_decision(): path_a() else: path_b()` |
| ★★☆ | LLM आउटपुट फंक्शन एक्जीक्यूशन निर्धारित करता है | टूल कॉलर | `run_function(llm_chosen_tool, llm_chosen_args)` |
| ★★★ | LLM आउटपुट पुनरावृत्ति और प्रोग्राम की निरंतरता को नियंत्रित करता है | मल्टी-स्टेप एजेंट | `while llm_should_continue(): execute_next_step()` |
| ★★★ | एक एजेंटिक वर्कफ़्लो दूसरे एजेंटिक वर्कफ़्लो को शुरू कर सकता है | मल्टी-एजेंट | `if llm_trigger(): execute_agent()` |

मल्टी-स्टेप agent की यह कोड संरचना है:

```python
memory = [user_defined_task]
while llm_should_continue(memory): # यह लूप मल्टी-स्टेप भाग है
    action = llm_get_next_action(memory) # यह टूल-कॉलिंग भाग है
    observations = execute_action(action)
    memory += [action, observations]
```

यह एजेंटिक सिस्टम एक लूप में चलता है, प्रत्येक चरण में एक नई क्रिया को शुरू करता है (क्रिया में कुछ पूर्व-निर्धारित *tools* को कॉल करना शामिल हो सकता है जो केवल फंक्शंस हैं), जब तक कि उसके अवलोकन से यह स्पष्ट न हो जाए कि दिए गए कार्य को हल करने के लिए एक संतोषजनक स्थिति प्राप्त कर ली गई है।

## ✅ Agents का उपयोग कब करें / ⛔ कब उनसे बचें

Agents तब उपयोगी होते हैं जब आपको किसी ऐप के वर्कफ़्लो को निर्धारित करने के लिए LLM की आवश्यकता होती है। लेकिन वे अक्सर जरूरत से ज्यादा होते हैं। सवाल यह है कि, क्या मुझे वास्तव में दिए गए कार्य को कुशलतापूर्वक हल करने के लिए वर्कफ़्लो में लचीलेपन की आवश्यकता है?
यदि पूर्व-निर्धारित वर्कफ़्लो बहुत बार विफल होता है, तो इसका मतलब है कि आपको अधिक लचीलेपन की आवश्यकता है।

आइए एक उदाहरण लेते हैं: मान लीजिए आप एक ऐप बना रहे हैं जो एक सर्फिंग ट्रिप वेबसाइट पर ग्राहक अनुरोधों को संभालता है।

आप पहले से जान सकते हैं कि अनुरोध 2 में से किसी एक श्रेणी में आएंगे (उपयोगकर्ता की पसंद के आधार पर), और आपके पास इन 2 मामलों में से प्रत्येक के लिए एक पूर्व-निर्धारित वर्कफ़्लो है।

1. ट्रिप के बारे में कुछ जानकारी चाहिए? ⇒ उन्हें अपने नॉलेज बेस में खोज करने के लिए एक सर्च बार तक पहुंच दें
2. सेल्स टीम से बात करना चाहते हैं? ⇒ उन्हें एक संपर्क फॉर्म में टाइप करने दें।

यदि वह निर्धारणात्मक वर्कफ़्लो सभी प्रश्नों के लिए फिट बैठता है, तो बेशक बस सब कुछ कोड करें! यह आपको एक 100% विश्वसनीय सिस्टम देगा और एलएलएम द्वारा अनपेक्षित कार्यप्रवाह में हस्तक्षेप करने से त्रुटियों का कोई जोखिम नहीं होगा। साधारणता और मजबूती के लिए, सलाह दी जाती है कि एजेंटिक व्यवहार का उपयोग न किया जाए।

लेकिन क्या होगा अगर वर्कफ़्लो को पहले से इतनी अच्छी तरह से निर्धारित नहीं किया जा सकता?

उदाहरण के लिए, एक उपयोगकर्ता पूछना चाहता है: `"मैं सोमवार को आ सकता हूं, लेकिन मैं अपना पासपोर्ट भूल गया जिससे मुझे बुधवार तक देर हो सकती है, क्या आप मुझे और मेरी चीजों को मंगलवार सुबह सर्फ करने ले जा सकते हैं, क्या मुझे कैंसलेशन इंश्योरेंस मिल सकता है?"` यह प्रश्न कई कारकों पर निर्भर करता है, और शायद ऊपर दिए गए पूर्व-निर्धारित मानदंडों में से कोई भी इस अनुरोध के लिए पर्याप्त नहीं होगा।

यदि पूर्व-निर्धारित वर्कफ़्लो बहुत बार विफल होता है, तो इसका मतलब है कि आपको अधिक लचीलेपन की आवश्यकता है।

यहीं पर एक एजेंटिक सेटअप मदद करता है।

ऊपर दिए गए उदाहरण में, आप बस एक मल्टी-स्टेप agent बना सकते हैं जिसके पास मौसम पूर्वानुमान के लिए एक मौसम API, यात्रा की दूरी जानने के लिए के लिए Google Maps API, एक कर्मचारी उपलब्धता डैशबोर्ड और आपके नॉलेज बेस पर एक RAG सिस्टम तक पहुंच है।

हाल ही तक, कंप्यूटर प्रोग्राम पूर्व-निर्धारित वर्कफ़्लो तक सीमित थे, if/else स्विच का
ढेर लगाकार जटिलता को संभालने का प्रयास कर रहे थे। वे बेहद संकीर्ण कार्यों पर केंद्रित थे, जैसे "इन संख्याओं का योग निकालें" या "इस ग्राफ़ में सबसे छोटा रास्ता खोजें"। लेकिन वास्तव में, अधिकांश वास्तविक जीवन के कार्य, जैसे ऊपर दिया गया हमारा यात्रा उदाहरण, पूर्व-निर्धारित वर्कफ़्लो में फिट नहीं होते हैं। एजेंटिक सिस्टम प्रोग्राम के लिए वास्तविक दुनिया के कार्यों की विशाल दुनिया खोलते हैं!

## क्यों `smolagents`?

कुछ लो-लेवल एजेंटिक उपयोग के मामलों के लिए, जैसे चेन या राउटर, आप सभी कोड खुद लिख सकते हैं। आप इस तरह से बहुत बेहतर होंगे, क्योंकि यह आपको अपने सिस्टम को बेहतर ढंग से नियंत्रित और समझने की अनुमति देगा।

लेकिन जैसे ही आप अधिक जटिल व्यवहारों की ओर बढ़ते हैं जैसे कि LLM को एक फ़ंक्शन कॉल करने देना (यह "tool calling" है) या LLM को एक while लूप चलाने देना ("multi-step agent"), कुछ एब्सट्रैक्शन्स की आवश्यकता होती है:
- टूल कॉलिंग के लिए, आपको एजेंट के आउटपुट को पार्स करने की आवश्यकता होती है, इसलिए इस आउटपुट को एक पूर्व-निर्धारित प्रारूप की आवश्यकता होती है जैसे "विचार: मुझे 'get_weather' टूल कॉल करना चाहिए। क्रिया: get_weather(Paris)।", जिसे आप एक पूर्व-निर्धारित फ़ंक्शन के साथ पार्स करते हैं, और LLM को दिए गए सिस्टम प्रॉम्प्ट को इस प्रारूप के बारे में सूचित करना चाहिए।
- एक मल्टी-स्टेप एजेंट के लिए जहां LLM आउटपुट लूप को निर्धारित करता है, आपको पिछले लूप इटरेशन में क्या हुआ इसके आधार पर LLM को एक अलग प्रॉम्प्ट देने की आवश्यकता होती है: इसलिए आपको किसी प्रकार की मेमोरी की आवश्यकता होती है।

इन दो उदाहरणों के साथ, हमने पहले ही कुछ चीजों की आवश्यकता का पता लगा लिया:

- बेशक, एक LLM जो सिस्टम को पावर देने वाले इंजन के रूप में कार्य करता है
- एजेंट द्वारा एक्सेस किए जा सकने वाले टूल्स की एक सूची
- एक पार्सर जो LLM आउटपुट से टूल कॉल को निकालता है
- एक सिस्टम प्रोम्प्ट जो पार्सर के साथ सिंक्रनाइज़ होता है
- एक मेमोरी

लेकिन रुकिए, चूंकि हम निर्णयों में LLM को जगह देते हैं, निश्चित रूप से वे गलतियां करेंगे: इसलिए हमें एरर लॉगिंग और पुनः प्रयास तंत्र की आवश्यकता है।

ये सभी तत्व एक अच्छे कामकाजी सिस्टम बनाने के लिए एक-दूसरे से घनिष्ठ रूप से जुड़े हुए हैं। यही कारण है कि हमने तय किया कि इन सभी चीजों को एक साथ काम करने के लिए बुनियादी निर्माण ब्लॉक्स की आवश्यकता है।

## कोड Agents

एक मल्टी-स्टेप एजेंट में, प्रत्येक चरण पर, LLM बाहरी टूल्स को कुछ कॉल के रूप में एक क्रिया लिख सकता है। इन क्रियाओं को लिखने के लिए एक सामान्य स्वरूप (Anthropic, OpenAI और कई अन्य द्वारा उपयोग किया जाता है) आमतौर पर "टूल्स के नाम और उपयोग करने के लिए तर्कों के JSON के रूप में क्रियाएं लिखने" के विभिन्न रूप होते हैं, जिन्हें आप फिर पार्स करते हैं यह जानने के लिए कि कौन सा टूल किन तर्कों के साथ निष्पादित करना है"।

[कई](https://huggingface.co/papers/2402.01030) [शोध](https://huggingface.co/papers/2411.01747) [पत्रों](https://huggingface.co/papers/2401.00812) ने दिखाया है कि कोड में टूल कॉलिंग LLM का होना बहुत बेहतर है।

इसका कारण बस यह है कि *हमने अपनी कोड भाषाओं को विशेष रूप से कंप्यूटर द्वारा किए गए कार्यों को व्यक्त करने का सर्वोत्तम संभव तरीका बनाने के लिए तैयार किया*। यदि JSON स्निपेट्स बेहतर अभिव्यक्ति होते, तो JSON शीर्ष प्रोग्रामिंग भाषा होती और प्रोग्रामिंग नरक में होती।

नीचे दी गई छवि, [Executable Code Actions Elicit Better LLM Agents](https://huggingface.co/papers/2402.01030) से ली गई है, जो कोड में क्रियाएं लिखने के कुछ फायदे दर्शाती है:

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/code_vs_json_actions.png">

JSON जैसे स्निपेट्स की बजाय कोड में क्रियाएं लिखने से बेहतर प्राप्त होता है:

- **कम्पोजेबिलिटी:** क्या आप JSON क्रियाओं को एक-दूसरे के भीतर नेस्ट कर सकते हैं, या बाद में पुन: उपयोग करने के लिए JSON क्रियाओं का एक सेट परिभाषित कर सकते हैं, उसी तरह जैसे आप बस एक पायथन फंक्शन परिभाषित कर सकते हैं?
- **ऑब्जेक्ट प्रबंधन:** आप `generate_image` जैसी क्रिया के आउटपुट को JSON में कैसे स्टोर करते हैं?
- **सामान्यता:** कोड को सरल रूप से कुछ भी व्यक्त करने के लिए बनाया गया है जो आप कंप्यूटर से करवा सकते हैं।
- **LLM प्रशिक्षण डेटा में प्रतिनिधित्व:** बहुत सारी गुणवत्तापूर्ण कोड क्रियाएं पहले से ही LLM के ट्रेनिंग डेटा में शामिल हैं जिसका मतलब है कि वे इसके लिए पहले से ही प्रशिक्षित हैं!

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/conceptual_guides/intro_agents.md" />

### Agents
https://huggingface.co/docs/smolagents/v1.22.0/hi/reference/agents.md

# Agents

<Tip warning={true}>

Smolagents एक experimental API है जो किसी भी समय बदल सकता है। एजेंट्स द्वारा लौटाए गए परिणाम भिन्न हो सकते हैं क्योंकि APIs या underlying मॉडल बदलने की संभावना रखते हैं।

</Tip>

Agents और tools के बारे में अधिक जानने के लिए [introductory guide](../index) पढ़ना सुनिश्चित करें। 
यह पेज underlying क्लासेज के लिए API docs को शामिल करता है।

## Agents

हमारे एजेंट्स [MultiStepAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.MultiStepAgent) से इनहेरिट करते हैं, जिसका अर्थ है कि वे कई चरणों में कार्य कर सकते हैं, प्रत्येक चरण में एक विचार, फिर एक टूल कॉल और एक्जीक्यूशन शामिल होता है। [इस कॉन्सेप्चुअल गाइड](../conceptual_guides/react) में अधिक पढ़ें।

हम मुख्य `Agent` क्लास पर आधारित दो प्रकार के एजेंट्स प्रदान करते हैं।
  - [CodeAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.CodeAgent) डिफ़ॉल्ट एजेंट है, यह अपने टूल कॉल्स को Python कोड में लिखता है।
  - [ToolCallingAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.ToolCallingAgent) अपने टूल कॉल्स को JSON में लिखता है।

दोनों को इनिशियलाइजेशन पर `model` और टूल्स की सूची `tools` आर्गुमेंट्स की आवश्यकता होती है।

### Agents की क्लासेज[[smolagents.MultiStepAgent]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.MultiStepAgent</name><anchor>smolagents.MultiStepAgent</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L266</source><parameters>[{"name": "tools", "val": ": list"}, {"name": "model", "val": ": Model"}, {"name": "prompt_templates", "val": ": smolagents.agents.PromptTemplates | None = None"}, {"name": "instructions", "val": ": str | None = None"}, {"name": "max_steps", "val": ": int = 20"}, {"name": "add_base_tools", "val": ": bool = False"}, {"name": "verbosity_level", "val": ": LogLevel = <LogLevel.INFO: 1>"}, {"name": "managed_agents", "val": ": list | None = None"}, {"name": "step_callbacks", "val": ": list[collections.abc.Callable] | dict[typing.Type[smolagents.memory.MemoryStep], collections.abc.Callable | list[collections.abc.Callable]] | None = None"}, {"name": "planning_interval", "val": ": int | None = None"}, {"name": "name", "val": ": str | None = None"}, {"name": "description", "val": ": str | None = None"}, {"name": "provide_run_summary", "val": ": bool = False"}, {"name": "final_answer_checks", "val": ": list[collections.abc.Callable] | None = None"}, {"name": "return_full_result", "val": ": bool = False"}, {"name": "logger", "val": ": smolagents.monitoring.AgentLogger | None = None"}]</parameters><paramsdesc>- **tools** (`list[Tool]`) -- [Tool](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool)s that the agent can use.
- **model** (`Callable[[list[dict[str, str]]], ChatMessage]`) -- Model that will generate the agent's actions.
- **prompt_templates** ([PromptTemplates](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.PromptTemplates), *optional*) -- Prompt templates.
- **instructions** (`str`, *optional*) -- Custom instructions for the agent, will be inserted in the system prompt.
- **max_steps** (`int`, default `20`) -- Maximum number of steps the agent can take to solve the task.
- **add_base_tools** (`bool`, default `False`) -- Whether to add the base tools to the agent's tools.
- **verbosity_level** (`LogLevel`, default `LogLevel.INFO`) -- Level of verbosity of the agent's logs.
- **managed_agents** (`list`, *optional*) -- Managed agents that the agent can call.
- **step_callbacks** (`list[Callable]` | `dict[Type[MemoryStep], Callable | list[Callable]]`, *optional*) -- Callbacks that will be called at each step.
- **planning_interval** (`int`, *optional*) -- Interval at which the agent will run a planning step.
- **name** (`str`, *optional*) -- Necessary for a managed agent only - the name by which this agent can be called.
- **description** (`str`, *optional*) -- Necessary for a managed agent only - the description of this agent.
- **provide_run_summary** (`bool`, *optional*) -- Whether to provide a run summary when called as a managed agent.
- **final_answer_checks** (`list[Callable]`, *optional*) -- List of validation functions to run before accepting a final answer.
  Each function should:
  - Take the final answer and the agent's memory as arguments.
  - Return a boolean indicating whether the final answer is valid.
- **return_full_result** (`bool`, default `False`) -- Whether to return the full `RunResult` object or just the final answer output from the agent run.</paramsdesc><paramgroups>0</paramgroups></docstring>

Agent class that solves the given task step by step, using the ReAct framework:
While the objective is not reached, the agent will perform a cycle of action (given by the LLM) and observation (obtained from the environment).





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>extract_action</name><anchor>smolagents.MultiStepAgent.extract_action</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L783</source><parameters>[{"name": "model_output", "val": ": str"}, {"name": "split_token", "val": ": str"}]</parameters><paramsdesc>- **model_output** (`str`) -- Output of the LLM
- **split_token** (`str`) -- Separator for the action. Should match the example in the system prompt.</paramsdesc><paramgroups>0</paramgroups></docstring>

Parse action from the LLM output




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_dict</name><anchor>smolagents.MultiStepAgent.from_dict</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L1004</source><parameters>[{"name": "agent_dict", "val": ": dict"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **agent_dict** (`dict[str, Any]`) -- Dictionary representation of the agent.
- ****kwargs** -- Additional keyword arguments that will override agent_dict values.</paramsdesc><paramgroups>0</paramgroups><rettype>`MultiStepAgent`</rettype><retdesc>Instance of the agent class.</retdesc></docstring>
Create agent from a dictionary representation.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_folder</name><anchor>smolagents.MultiStepAgent.from_folder</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L1102</source><parameters>[{"name": "folder", "val": ": str | pathlib.Path"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **folder** (`str` or `Path`) -- The folder where the agent is saved.
- ****kwargs** -- Additional keyword arguments that will be passed to the agent's init.</paramsdesc><paramgroups>0</paramgroups></docstring>
Loads an agent from a local folder.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_hub</name><anchor>smolagents.MultiStepAgent.from_hub</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L1048</source><parameters>[{"name": "repo_id", "val": ": str"}, {"name": "token", "val": ": str | None = None"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **repo_id** (`str`) --
  The name of the repo on the Hub where your tool is defined.
- **token** (`str`, *optional*) --
  The token to identify you on hf.co. If unset, will use the token generated when running
  `huggingface-cli login` (stored in `~/.huggingface`).
- **trust_remote_code(`bool`,** *optional*, defaults to False) --
  This flags marks that you understand the risk of running remote code and that you trust this tool.
  If not setting this to True, loading the tool from Hub will fail.
- **kwargs** (additional keyword arguments, *optional*) --
  Additional keyword arguments that will be split in two: all arguments relevant to the Hub (such as
  `cache_dir`, `revision`, `subfolder`) will be used when downloading the files for your agent, and the
  others will be passed along to its init.</paramsdesc><paramgroups>0</paramgroups></docstring>

Loads an agent defined on the Hub.

<Tip warning={true}>

Loading a tool from the Hub means that you'll download the tool and execute it locally.
ALWAYS inspect the tool you're downloading before loading it within your runtime, as you would do when
installing a package using pip/npm/apt.

</Tip>




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>initialize_system_prompt</name><anchor>smolagents.MultiStepAgent.initialize_system_prompt</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L743</source><parameters>[]</parameters></docstring>
To be implemented in child classes

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>interrupt</name><anchor>smolagents.MultiStepAgent.interrupt</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L748</source><parameters>[]</parameters></docstring>
Interrupts the agent execution.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>provide_final_answer</name><anchor>smolagents.MultiStepAgent.provide_final_answer</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L804</source><parameters>[{"name": "task", "val": ": str"}]</parameters><paramsdesc>- **task** (`str`) -- Task to perform.
- **images** (`list[PIL.Image.Image]`, *optional*) -- Image(s) objects.</paramsdesc><paramgroups>0</paramgroups><rettype>`str`</rettype><retdesc>Final answer to the task.</retdesc></docstring>

Provide the final answer to the task, based on the logs of the agent's interactions.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>push_to_hub</name><anchor>smolagents.MultiStepAgent.push_to_hub</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L1134</source><parameters>[{"name": "repo_id", "val": ": str"}, {"name": "commit_message", "val": ": str = 'Upload agent'"}, {"name": "private", "val": ": bool | None = None"}, {"name": "token", "val": ": bool | str | None = None"}, {"name": "create_pr", "val": ": bool = False"}]</parameters><paramsdesc>- **repo_id** (`str`) --
  The name of the repository you want to push to. It should contain your organization name when
  pushing to a given organization.
- **commit_message** (`str`, *optional*, defaults to `"Upload agent"`) --
  Message to commit while pushing.
- **private** (`bool`, *optional*, defaults to `None`) --
  Whether to make the repo private. If `None`, the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
- **token** (`bool` or `str`, *optional*) --
  The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated
  when running `huggingface-cli login` (stored in `~/.huggingface`).
- **create_pr** (`bool`, *optional*, defaults to `False`) --
  Whether to create a PR with the uploaded files or directly commit.</paramsdesc><paramgroups>0</paramgroups></docstring>

Upload the agent to the Hub.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>replay</name><anchor>smolagents.MultiStepAgent.replay</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L853</source><parameters>[{"name": "detailed", "val": ": bool = False"}]</parameters><paramsdesc>- **detailed** (bool, optional) -- If True, also displays the memory at each step. Defaults to False.
  Careful: will increase log length exponentially. Use only for debugging.</paramsdesc><paramgroups>0</paramgroups></docstring>
Prints a pretty replay of the agent's steps.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>run</name><anchor>smolagents.MultiStepAgent.run</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L433</source><parameters>[{"name": "task", "val": ": str"}, {"name": "stream", "val": ": bool = False"}, {"name": "reset", "val": ": bool = True"}, {"name": "images", "val": ": list['PIL.Image.Image'] | None = None"}, {"name": "additional_args", "val": ": dict | None = None"}, {"name": "max_steps", "val": ": int | None = None"}, {"name": "return_full_result", "val": ": bool | None = None"}]</parameters><paramsdesc>- **task** (`str`) -- Task to perform.
- **stream** (`bool`) -- Whether to run in streaming mode.
  If `True`, returns a generator that yields each step as it is executed. You must iterate over this generator to process the individual steps (e.g., using a for loop or `next()`).
  If `False`, executes all steps internally and returns only the final answer after completion.
- **reset** (`bool`) -- Whether to reset the conversation or keep it going from previous run.
- **images** (`list[PIL.Image.Image]`, *optional*) -- Image(s) objects.
- **additional_args** (`dict`, *optional*) -- Any other variables that you want to pass to the agent run, for instance images or dataframes. Give them clear names!
- **max_steps** (`int`, *optional*) -- Maximum number of steps the agent can take to solve the task. if not provided, will use the agent's default value.
- **return_full_result** (`bool`, *optional*) -- Whether to return the full `RunResult` object or just the final answer output.
  If `None` (default), the agent's `self.return_full_result` setting is used.</paramsdesc><paramgroups>0</paramgroups></docstring>

Run the agent for the given task.



<ExampleCodeBlock anchor="smolagents.MultiStepAgent.run.example">

Example:
```py
from smolagents import CodeAgent
agent = CodeAgent(tools=[])
agent.run("What is the result of 2 power 3.7384?")
```

</ExampleCodeBlock>


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>save</name><anchor>smolagents.MultiStepAgent.save</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L886</source><parameters>[{"name": "output_dir", "val": ": str | pathlib.Path"}, {"name": "relative_path", "val": ": str | None = None"}]</parameters><paramsdesc>- **output_dir** (`str` or `Path`) -- The folder in which you want to save your agent.</paramsdesc><paramgroups>0</paramgroups></docstring>

Saves the relevant code files for your agent. This will copy the code of your agent in `output_dir` as well as autogenerate:

- a `tools` folder containing the logic for each of the tools under `tools/{tool_name}.py`.
- a `managed_agents` folder containing the logic for each of the managed agents.
- an `agent.json` file containing a dictionary representing your agent.
- a `prompt.yaml` file containing the prompt templates used by your agent.
- an `app.py` file providing a UI for your agent when it is exported to a Space with `agent.push_to_hub()`
- a `requirements.txt` containing the names of the modules used by your tool (as detected when inspecting its
  code)




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>step</name><anchor>smolagents.MultiStepAgent.step</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L776</source><parameters>[{"name": "memory_step", "val": ": ActionStep"}]</parameters></docstring>

Perform one step in the ReAct framework: the agent thinks, acts, and observes the result.
Returns either None if the step is not final, or the final answer.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_dict</name><anchor>smolagents.MultiStepAgent.to_dict</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L964</source><parameters>[]</parameters><rettype>`dict`</rettype><retdesc>Dictionary representation of the agent.</retdesc></docstring>
Convert the agent to a dictionary representation.






</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>visualize</name><anchor>smolagents.MultiStepAgent.visualize</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L849</source><parameters>[]</parameters></docstring>
Creates a rich tree visualization of the agent's structure.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>write_memory_to_messages</name><anchor>smolagents.MultiStepAgent.write_memory_to_messages</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L752</source><parameters>[{"name": "summary_mode", "val": ": bool = False"}]</parameters></docstring>

Reads past llm_outputs, actions, and observations or errors from the memory into a series of messages
that can be used as input to the LLM. Adds a number of keywords (such as PLAN, error, etc) to help
the LLM.


</div></div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.CodeAgent</name><anchor>smolagents.CodeAgent</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L1483</source><parameters>[{"name": "tools", "val": ": list"}, {"name": "model", "val": ": Model"}, {"name": "prompt_templates", "val": ": smolagents.agents.PromptTemplates | None = None"}, {"name": "additional_authorized_imports", "val": ": list[str] | None = None"}, {"name": "planning_interval", "val": ": int | None = None"}, {"name": "executor_type", "val": ": typing.Literal['local', 'e2b', 'modal', 'docker', 'wasm'] = 'local'"}, {"name": "executor_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "max_print_outputs_length", "val": ": int | None = None"}, {"name": "stream_outputs", "val": ": bool = False"}, {"name": "use_structured_outputs_internally", "val": ": bool = False"}, {"name": "code_block_tags", "val": ": str | tuple[str, str] | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **tools** (`list[Tool]`) -- [Tool](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool)s that the agent can use.
- **model** (`Model`) -- Model that will generate the agent's actions.
- **prompt_templates** ([PromptTemplates](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.PromptTemplates), *optional*) -- Prompt templates.
- **additional_authorized_imports** (`list[str]`, *optional*) -- Additional authorized imports for the agent.
- **planning_interval** (`int`, *optional*) -- Interval at which the agent will run a planning step.
- **executor_type** (`Literal["local", "e2b", "modal", "docker", "wasm"]`, default `"local"`) -- Type of code executor.
- **executor_kwargs** (`dict`, *optional*) -- Additional arguments to pass to initialize the executor.
- **max_print_outputs_length** (`int`, *optional*) -- Maximum length of the print outputs.
- **stream_outputs** (`bool`, *optional*, default `False`) -- Whether to stream outputs during execution.
- **use_structured_outputs_internally** (`bool`, default `False`) -- Whether to use structured generation at each action step: improves performance for many models.

  <Added version="1.17.0"/>
- **code_block_tags** (`tuple[str, str]` | `Literal["markdown"]`, *optional*) -- Opening and closing tags for code blocks (regex strings). Pass a custom tuple, or pass 'markdown' to use ("```(?:python|py)", "\n```"), leave empty to use ("<code>", "</code>").
- ****kwargs** -- Additional keyword arguments.</paramsdesc><paramgroups>0</paramgroups></docstring>

In this agent, the tool calls will be formulated by the LLM in code format, then parsed and executed.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>cleanup</name><anchor>smolagents.CodeAgent.cleanup</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L1571</source><parameters>[]</parameters></docstring>
Clean up resources used by the agent, such as the remote Python executor.

</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_dict</name><anchor>smolagents.CodeAgent.from_dict</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L1754</source><parameters>[{"name": "agent_dict", "val": ": dict"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **agent_dict** (`dict[str, Any]`) -- Dictionary representation of the agent.
- ****kwargs** -- Additional keyword arguments that will override agent_dict values.</paramsdesc><paramgroups>0</paramgroups><rettype>`CodeAgent`</rettype><retdesc>Instance of the CodeAgent class.</retdesc></docstring>
Create CodeAgent from a dictionary representation.








</div></div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.ToolCallingAgent</name><anchor>smolagents.ToolCallingAgent</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L1189</source><parameters>[{"name": "tools", "val": ": list"}, {"name": "model", "val": ": Model"}, {"name": "prompt_templates", "val": ": smolagents.agents.PromptTemplates | None = None"}, {"name": "planning_interval", "val": ": int | None = None"}, {"name": "stream_outputs", "val": ": bool = False"}, {"name": "max_tool_threads", "val": ": int | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **tools** (`list[Tool]`) -- [Tool](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool)s that the agent can use.
- **model** (`Model`) -- Model that will generate the agent's actions.
- **prompt_templates** ([PromptTemplates](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.PromptTemplates), *optional*) -- Prompt templates.
- **planning_interval** (`int`, *optional*) -- Interval at which the agent will run a planning step.
- **stream_outputs** (`bool`, *optional*, default `False`) -- Whether to stream outputs during execution.
- **max_tool_threads** (`int`, *optional*) -- Maximum number of threads for parallel tool calls.
  Higher values increase concurrency but resource usage as well.
  Defaults to `ThreadPoolExecutor`'s default.
- ****kwargs** -- Additional keyword arguments.</paramsdesc><paramgroups>0</paramgroups></docstring>

This agent uses JSON-like tool calls, using method `model.get_tool_call` to leverage the LLM engine's tool calling capabilities.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>execute_tool_call</name><anchor>smolagents.ToolCallingAgent.execute_tool_call</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L1431</source><parameters>[{"name": "tool_name", "val": ": str"}, {"name": "arguments", "val": ": dict[str, str] | str"}]</parameters><paramsdesc>- **tool_name** (`str`) -- Name of the tool or managed agent to execute.
- **arguments** (dict[str, str] | str) -- Arguments passed to the tool call.</paramsdesc><paramgroups>0</paramgroups></docstring>

Execute a tool or managed agent with the provided arguments.

The arguments are replaced with the actual values from the state if they refer to state variables.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>process_tool_calls</name><anchor>smolagents.ToolCallingAgent.process_tool_calls</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L1340</source><parameters>[{"name": "chat_message", "val": ": ChatMessage"}, {"name": "memory_step", "val": ": ActionStep"}]</parameters><paramsdesc>- **chat_message** (`ChatMessage`) -- Chat message containing tool calls from the model.
- **memory_step** (`ActionStep)` -- Memory ActionStep to update with results.</paramsdesc><paramgroups>0</paramgroups><yieldtype>`ToolCall | ToolOutput`</yieldtype><yielddesc>The tool call or tool output.</yielddesc></docstring>
Process tool calls from the model output and update agent memory.








</div></div>

### stream_to_gradio[[smolagents.stream_to_gradio]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>smolagents.stream_to_gradio</name><anchor>smolagents.stream_to_gradio</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/gradio_ui.py#L248</source><parameters>[{"name": "agent", "val": ""}, {"name": "task", "val": ": str"}, {"name": "task_images", "val": ": list | None = None"}, {"name": "reset_agent_memory", "val": ": bool = False"}, {"name": "additional_args", "val": ": dict | None = None"}]</parameters></docstring>
Runs an agent with the given task and streams the messages from the agent as gradio ChatMessages.

</div>

### GradioUI[[smolagents.GradioUI]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.GradioUI</name><anchor>smolagents.GradioUI</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/gradio_ui.py#L279</source><parameters>[{"name": "agent", "val": ": MultiStepAgent"}, {"name": "file_upload_folder", "val": ": str | None = None"}, {"name": "reset_agent_memory", "val": ": bool = False"}]</parameters><paramsdesc>- **agent** ([MultiStepAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.MultiStepAgent)) -- The agent to interact with.
- **file_upload_folder** (`str`, *optional*) -- The folder where uploaded files will be saved.
  If not provided, file uploads are disabled.
- **reset_agent_memory** (`bool`, *optional*, defaults to `False`) -- Whether to reset the agent's memory at the start of each interaction.
  If `True`, the agent will not remember previous interactions.</paramsdesc><paramgroups>0</paramgroups><raises>- ``ModuleNotFoundError`` -- If the `gradio` extra is not installed.</raises><raisederrors>``ModuleNotFoundError``</raisederrors></docstring>

Gradio interface for interacting with a [MultiStepAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.MultiStepAgent).

This class provides a web interface to interact with the agent in real-time, allowing users to submit prompts, upload files, and receive responses in a chat-like format.
It  can reset the agent's memory at the start of each interaction if desired.
It supports file uploads, which are saved to a specified folder.
It uses the `gradio.Chatbot` component to display the conversation history.
This class requires the `gradio` extra to be installed: `pip install 'smolagents[gradio]'`.







<ExampleCodeBlock anchor="smolagents.GradioUI.example">

Example:
```python
from smolagents import CodeAgent, GradioUI, InferenceClientModel

model = InferenceClientModel(model_id="meta-llama/Meta-Llama-3.1-8B-Instruct")
agent = CodeAgent(tools=[], model=model)
gradio_ui = GradioUI(agent, file_upload_folder="uploads", reset_agent_memory=True)
gradio_ui.launch()
```

</ExampleCodeBlock>



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>launch</name><anchor>smolagents.GradioUI.launch</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/gradio_ui.py#L406</source><parameters>[{"name": "share", "val": ": bool = True"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **share** (`bool`, defaults to `True`) -- Whether to share the app publicly.
- ****kwargs** -- Additional keyword arguments to pass to the Gradio launch method.</paramsdesc><paramgroups>0</paramgroups></docstring>

Launch the Gradio app with the agent interface.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>upload_file</name><anchor>smolagents.GradioUI.upload_file</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/gradio_ui.py#L356</source><parameters>[{"name": "file", "val": ""}, {"name": "file_uploads_log", "val": ""}, {"name": "allowed_file_types", "val": " = None"}]</parameters><paramsdesc>- **file** (`gradio.File`) -- The uploaded file.
- **file_uploads_log** (`list`) -- A list to log uploaded files.
- **allowed_file_types** (`list`, *optional*) -- List of allowed file extensions. Defaults to [".pdf", ".docx", ".txt"].</paramsdesc><paramgroups>0</paramgroups></docstring>

Upload a file and add it to the list of uploaded files in the session state.

The file is saved to the `self.file_upload_folder` folder.
If the file type is not allowed, it returns a message indicating the disallowed file type.




</div></div>

## मॉडल्स

आप स्वतंत्र रूप से अपने स्वयं के मॉडल बना सकते हैं और उनका उपयोग कर सकते हैं।

आप अपने एजेंट के लिए कोई भी `model` कॉल करने योग्य उपयोग कर सकते हैं, जब तक कि:
1. यह अपने इनपुट `messages` के लिए [messages format](./chat_templating) (`List[Dict[str, str]]`) का पालन करता है, और यह एक `str` लौटाता है।
2. यह आर्गुमेंट `stop_sequences` में पास किए गए सीक्वेंस से *पहले* आउटपुट जनरेट करना बंद कर देता है।

अपने LLM को परिभाषित करने के लिए, आप एक `custom_model` मेथड बना सकते हैं जो [messages](./chat_templating) की एक सूची स्वीकार करता है और टेक्स्ट युक्त .content विशेषता वाला एक ऑब्जेक्ट लौटाता है। इस कॉलेबल को एक `stop_sequences` आर्गुमेंट भी स्वीकार करने की आवश्यकता होती है जो बताता है कि कब जनरेट करना और बंद करना है।

```python
from huggingface_hub import login, InferenceClient

login("<YOUR_HUGGINGFACEHUB_API_TOKEN>")

model_id = "meta-llama/Llama-3.3-70B-Instruct"

client = InferenceClient(model=model_id)

def custom_model(messages, stop_sequences=["Task"]):
    response = client.chat_completion(messages, stop=stop_sequences, max_tokens=1000)
    answer = response.choices[0].message
    return answer
```

इसके अतिरिक्त, `custom_model` एक `grammar` आर्गुमेंट भी ले सकता है। जिस स्थिति में आप एजेंट इनिशियलाइजेशन पर एक `grammar` निर्दिष्ट करते हैं, यह आर्गुमेंट मॉडल के कॉल्स को आपके द्वारा इनिशियलाइजेशन पर परिभाषित `grammar` के साथ पास किया जाएगा, ताकि [constrained generation](https://huggingface.co/docs/text-generation-inference/conceptual/guidance) की अनुमति मिल सके जिससे उचित-फॉर्मेटेड एजेंट आउटपुट को फोर्स किया जा सके।

### TransformersModel[[smolagents.TransformersModel]]

सुविधा के लिए, हमने एक `TransformersModel` जोड़ा है जो इनिशियलाइजेशन पर दिए गए model_id के लिए एक लोकल `transformers` पाइपलाइन बनाकर ऊपर के बिंदुओं को लागू करता है।

```python
from smolagents import TransformersModel

model = TransformersModel(model_id="HuggingFaceTB/SmolLM-135M-Instruct")

print(model([{"role": "user", "content": "Ok!"}], stop_sequences=["great"]))
```
```text
>>> What a
```

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.TransformersModel</name><anchor>smolagents.TransformersModel</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/models.py#L782</source><parameters>[{"name": "model_id", "val": ": str | None = None"}, {"name": "device_map", "val": ": str | None = None"}, {"name": "torch_dtype", "val": ": str | None = None"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "model_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "max_new_tokens", "val": ": int = 4096"}, {"name": "max_tokens", "val": ": int | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`) --
  The Hugging Face model ID to be used for inference. This can be a path or model identifier from the Hugging Face model hub.
  For example, `"Qwen/Qwen2.5-Coder-32B-Instruct"`.
- **device_map** (`str`, *optional*) --
  The device_map to initialize your model with.
- **torch_dtype** (`str`, *optional*) --
  The torch_dtype to initialize your model with.
- **trust_remote_code** (bool, default `False`) --
  Some models on the Hub require running remote code: for this model, you would have to set this flag to True.
- **model_kwargs** (`dict[str, Any]`, *optional*) --
  Additional keyword arguments to pass to `AutoModel.from_pretrained` (like revision, model_args, config, etc.).
- **max_new_tokens** (`int`, default `4096`) --
  Maximum number of new tokens to generate, ignoring the number of tokens in the prompt.
- **max_tokens** (`int`, *optional*) --
  Alias for `max_new_tokens`. If provided, this value takes precedence.
- ****kwargs** --
  Additional keyword arguments to forward to the underlying Transformers model generate call, such as `device`.</paramsdesc><paramgroups>0</paramgroups><raises>- ``ValueError`` -- 
  If the model name is not provided.</raises><raisederrors>``ValueError``</raisederrors></docstring>
A class that uses Hugging Face's Transformers library for language model interaction.

This model allows you to load and use Hugging Face's models locally using the Transformers library. It supports features like stop sequences and grammar customization.

> [!TIP]
> You must have `transformers` and `torch` installed on your machine. Please run `pip install 'smolagents[transformers]'` if it's not the case.







<ExampleCodeBlock anchor="smolagents.TransformersModel.example">

Example:
```python
>>> engine = TransformersModel(
...     model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
...     device="cuda",
...     max_new_tokens=5000,
... )
>>> messages = [{"role": "user", "content": "Explain quantum mechanics in simple terms."}]
>>> response = engine(messages, stop_sequences=["END"])
>>> print(response)
"Quantum mechanics is the branch of physics that studies..."
```

</ExampleCodeBlock>


</div>

### InferenceClientModel[[smolagents.InferenceClientModel]]

`InferenceClientModel` LLM के एक्जीक्यूशन के लिए [HF Inference API](https://huggingface.co/docs/api-inference/index) क्लाइंट को रैप करता है।

```python
from smolagents import InferenceClientModel

messages = [
  {"role": "user", "content": "Hello, how are you?"},
  {"role": "assistant", "content": "I'm doing great. How can I help you today?"},
  {"role": "user", "content": "No need to help, take it easy."},
]

model = InferenceClientModel()
print(model(messages))
```
```text
>>> Of course! If you change your mind, feel free to reach out. Take care!
```
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.InferenceClientModel</name><anchor>smolagents.InferenceClientModel</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/models.py#L1341</source><parameters>[{"name": "model_id", "val": ": str = 'Qwen/Qwen2.5-Coder-32B-Instruct'"}, {"name": "provider", "val": ": str | None = None"}, {"name": "token", "val": ": str | None = None"}, {"name": "timeout", "val": ": int = 120"}, {"name": "client_kwargs", "val": ": dict[str, typing.Any] | None = None"}, {"name": "custom_role_conversions", "val": ": dict[str, str] | None = None"}, {"name": "api_key", "val": ": str | None = None"}, {"name": "bill_to", "val": ": str | None = None"}, {"name": "base_url", "val": ": str | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`, *optional*, default `"Qwen/Qwen2.5-Coder-32B-Instruct"`) --
  The Hugging Face model ID to be used for inference.
  This can be a model identifier from the Hugging Face model hub or a URL to a deployed Inference Endpoint.
  Currently, it defaults to `"Qwen/Qwen2.5-Coder-32B-Instruct"`, but this may change in the future.
- **provider** (`str`, *optional*) --
  Name of the provider to use for inference. A list of supported providers can be found in the [Inference Providers documentation](https://huggingface.co/docs/inference-providers/index#partners).
  Defaults to "auto" i.e. the first of the providers available for the model, sorted by the user's order [here](https://hf.co/settings/inference-providers).
  If `base_url` is passed, then `provider` is not used.
- **token** (`str`, *optional*) --
  Token used by the Hugging Face API for authentication. This token need to be authorized 'Make calls to the serverless Inference Providers'.
  If the model is gated (like Llama-3 models), the token also needs 'Read access to contents of all public gated repos you can access'.
  If not provided, the class will try to use environment variable 'HF_TOKEN', else use the token stored in the Hugging Face CLI configuration.
- **timeout** (`int`, *optional*, defaults to 120) --
  Timeout for the API request, in seconds.
- **client_kwargs** (`dict[str, Any]`, *optional*) --
  Additional keyword arguments to pass to the Hugging Face InferenceClient.
- **custom_role_conversions** (`dict[str, str]`, *optional*) --
  Custom role conversion mapping to convert message roles in others.
  Useful for specific models that do not support specific message roles like "system".
- **api_key** (`str`, *optional*) --
  Token to use for authentication. This is a duplicated argument from `token` to make [InferenceClientModel](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.InferenceClientModel)
  follow the same pattern as `openai.OpenAI` client. Cannot be used if `token` is set. Defaults to None.
- **bill_to** (`str`, *optional*) --
  The billing account to use for the requests. By default the requests are billed on the user's account. Requests can only be billed to
  an organization the user is a member of, and which has subscribed to Enterprise Hub.
- **base_url** (`str`, `optional`) --
  Base URL to run inference. This is a duplicated argument from `model` to make [InferenceClientModel](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.InferenceClientModel)
  follow the same pattern as `openai.OpenAI` client. Cannot be used if `model` is set. Defaults to None.
- ****kwargs** --
  Additional keyword arguments to forward to the underlying Hugging Face InferenceClient completion call.</paramsdesc><paramgroups>0</paramgroups><raises>- ``ValueError`` -- 
  If the model name is not provided.</raises><raisederrors>``ValueError``</raisederrors></docstring>
A class to interact with Hugging Face's Inference Providers for language model interaction.

This model allows you to communicate with Hugging Face's models using Inference Providers. It can be used in both serverless mode, with a dedicated endpoint, or even with a local URL, supporting features like stop sequences and grammar customization.

Providers include Cerebras, Cohere, Fal, Fireworks, HF-Inference, Hyperbolic, Nebius, Novita, Replicate, SambaNova, Together, and more.







<ExampleCodeBlock anchor="smolagents.InferenceClientModel.example">

Example:
```python
>>> engine = InferenceClientModel(
...     model_id="Qwen/Qwen2.5-Coder-32B-Instruct",
...     provider="nebius",
...     token="your_hf_token_here",
...     max_tokens=5000,
... )
>>> messages = [{"role": "user", "content": "Explain quantum mechanics in simple terms."}]
>>> response = engine(messages, stop_sequences=["END"])
>>> print(response)
"Quantum mechanics is the branch of physics that studies..."
```

</ExampleCodeBlock>



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>create_client</name><anchor>smolagents.InferenceClientModel.create_client</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/models.py#L1432</source><parameters>[]</parameters></docstring>
Create the Hugging Face client.

</div></div>

### LiteLLMModel[[smolagents.LiteLLMModel]]

`LiteLLMModel` विभिन्न प्रदाताओं से 100+ LLMs को सपोर्ट करने के लिए [LiteLLM](https://www.litellm.ai/) का लाभ उठाता है।
आप मॉडल इनिशियलाइजेशन पर kwargs पास कर सकते हैं जो तब मॉडल का उपयोग करते समय प्रयोग किए जाएंगे, उदाहरण के लिए नीचे हम `temperature` पास करते हैं।

```python
from smolagents import LiteLLMModel

messages = [
  {"role": "user", "content": "Hello, how are you?"},
  {"role": "assistant", "content": "I'm doing great. How can I help you today?"},
  {"role": "user", "content": "No need to help, take it easy."},
]

model = LiteLLMModel(model_id="anthropic/claude-3-5-sonnet-latest", temperature=0.2, max_tokens=10)
print(model(messages))
```

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.LiteLLMModel</name><anchor>smolagents.LiteLLMModel</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/models.py#L1098</source><parameters>[{"name": "model_id", "val": ": str | None = None"}, {"name": "api_base", "val": ": str | None = None"}, {"name": "api_key", "val": ": str | None = None"}, {"name": "custom_role_conversions", "val": ": dict[str, str] | None = None"}, {"name": "flatten_messages_as_text", "val": ": bool | None = None"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **model_id** (`str`) --
  The model identifier to use on the server (e.g. "gpt-3.5-turbo").
- **api_base** (`str`, *optional*) --
  The base URL of the provider API to call the model.
- **api_key** (`str`, *optional*) --
  The API key to use for authentication.
- **custom_role_conversions** (`dict[str, str]`, *optional*) --
  Custom role conversion mapping to convert message roles in others.
  Useful for specific models that do not support specific message roles like "system".
- **flatten_messages_as_text** (`bool`, *optional*) -- Whether to flatten messages as text.
  Defaults to `True` for models that start with "ollama", "groq", "cerebras".
- ****kwargs** --
  Additional keyword arguments to forward to the underlying LiteLLM completion call.</paramsdesc><paramgroups>0</paramgroups></docstring>
Model to use [LiteLLM Python SDK](https://docs.litellm.ai/docs/#litellm-python-sdk) to access hundreds of LLMs.





<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>create_client</name><anchor>smolagents.LiteLLMModel.create_client</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/models.py#L1148</source><parameters>[]</parameters></docstring>
Create the LiteLLM client.

</div></div>

### OpenAiServerModel


यह क्लास आपको किसी भी OpenAIServer कम्पैटिबल मॉडल को कॉल करने देती है।
यहाँ बताया गया है कि आप इसे कैसे सेट कर सकते हैं (आप दूसरे सर्वर को पॉइंट करने के लिए `api_base` url को कस्टमाइज़ कर सकते हैं):
```py
import os
from smolagents import OpenAIServerModel

model = OpenAIServerModel(
    model_id="gpt-4o",
    api_base="https://api.openai.com/v1",
    api_key=os.environ["OPENAI_API_KEY"],
)
```

## Prompts[[smolagents.PromptTemplates]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.PromptTemplates</name><anchor>smolagents.PromptTemplates</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L164</source><parameters>""</parameters><paramsdesc>- **system_prompt** (`str`) -- System prompt.
- **planning** ([PlanningPromptTemplate](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.PlanningPromptTemplate)) -- Planning prompt templates.
- **managed_agent** ([ManagedAgentPromptTemplate](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.ManagedAgentPromptTemplate)) -- Managed agent prompt templates.
- **final_answer** ([FinalAnswerPromptTemplate](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.FinalAnswerPromptTemplate)) -- Final answer prompt templates.</paramsdesc><paramgroups>0</paramgroups></docstring>

Prompt templates for the agent.




</div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.PlanningPromptTemplate</name><anchor>smolagents.PlanningPromptTemplate</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L123</source><parameters>""</parameters><paramsdesc>- **plan** (`str`) -- Initial plan prompt.
- **update_plan_pre_messages** (`str`) -- Update plan pre-messages prompt.
- **update_plan_post_messages** (`str`) -- Update plan post-messages prompt.</paramsdesc><paramgroups>0</paramgroups></docstring>

Prompt templates for the planning step.




</div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.ManagedAgentPromptTemplate</name><anchor>smolagents.ManagedAgentPromptTemplate</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L138</source><parameters>""</parameters><paramsdesc>- **task** (`str`) -- Task prompt.
- **report** (`str`) -- Report prompt.</paramsdesc><paramgroups>0</paramgroups></docstring>

Prompt templates for the managed agent.




</div>

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.FinalAnswerPromptTemplate</name><anchor>smolagents.FinalAnswerPromptTemplate</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agents.py#L151</source><parameters>""</parameters><paramsdesc>- **pre_messages** (`str`) -- Pre-messages prompt.
- **post_messages** (`str`) -- Post-messages prompt.</paramsdesc><paramgroups>0</paramgroups></docstring>

Prompt templates for the final answer.




</div>

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/reference/agents.md" />

### Tools
https://huggingface.co/docs/smolagents/v1.22.0/hi/reference/tools.md

# Tools

<Tip warning={true}>

Smolagents एक experimental API है जो किसी भी समय बदल सकता है। एजेंट्स द्वारा लौटाए गए परिणाम भिन्न हो सकते हैं क्योंकि APIs या underlying मॉडल बदलने की संभावना रखते हैं।

</Tip>

एजेंट्स और टूल्स के बारे में अधिक जानने के लिए [introductory guide](../index) पढ़ना सुनिश्चित करें। 
यह पेज underlying क्लासेज के लिए API docs को शामिल करता है।

## Tools

### load_tool[[smolagents.load_tool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>smolagents.load_tool</name><anchor>smolagents.load_tool</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L840</source><parameters>[{"name": "repo_id", "val": ""}, {"name": "model_repo_id", "val": ": str | None = None"}, {"name": "token", "val": ": str | None = None"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **repo_id** (`str`) --
  Space repo ID of a tool on the Hub.
- **model_repo_id** (`str`, *optional*) --
  Use this argument to use a different model than the default one for the tool you selected.
- **token** (`str`, *optional*) --
  The token to identify you on hf.co. If unset, will use the token generated when running `huggingface-cli
  login` (stored in `~/.huggingface`).
- **trust_remote_code** (`bool`, *optional*, defaults to False) --
  This needs to be accepted in order to load a tool from Hub.
- **kwargs** (additional keyword arguments, *optional*) --
  Additional keyword arguments that will be split in two: all arguments relevant to the Hub (such as
  `cache_dir`, `revision`, `subfolder`) will be used when downloading the files for your tool, and the others
  will be passed along to its init.</paramsdesc><paramgroups>0</paramgroups></docstring>

Main function to quickly load a tool from the Hub.

<Tip warning={true}>

Loading a tool means that you'll download the tool and execute it locally.
ALWAYS inspect the tool you're downloading before loading it within your runtime, as you would do when
installing a package using pip/npm/apt.

</Tip>




</div>

### tool[[smolagents.tool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>smolagents.tool</name><anchor>smolagents.tool</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L1061</source><parameters>[{"name": "tool_function", "val": ": Callable"}]</parameters><paramsdesc>- **tool_function** (`Callable`) -- Function to convert into a Tool subclass.
  Should have type hints for each input and a type hint for the output.
  Should also have a docstring including the description of the function
  and an 'Args:' part where each argument is described.</paramsdesc><paramgroups>0</paramgroups></docstring>

Convert a function into an instance of a dynamically created Tool subclass.




</div>

### Tool[[smolagents.Tool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.Tool</name><anchor>smolagents.Tool</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L106</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>

A base class for the functions used by the agent. Subclass this and implement the `forward` method as well as the
following class attributes:

- **description** (`str`) -- A short description of what your tool does, the inputs it expects and the output(s) it
  will return. For instance 'This is a tool that downloads a file from a `url`. It takes the `url` as input, and
  returns the text contained in the file'.
- **name** (`str`) -- A performative name that will be used for your tool in the prompt to the agent. For instance
  `"text-classifier"` or `"image_generator"`.
- **inputs** (`Dict[str, Dict[str, Union[str, type, bool]]]`) -- The dict of modalities expected for the inputs.
  It has one `type`key and a `description`key.
  This is used by `launch_gradio_demo` or to make a nice space from your tool, and also can be used in the generated
  description for your tool.
- **output_type** (`type`) -- The type of the tool output. This is used by `launch_gradio_demo`
  or to make a nice space from your tool, and also can be used in the generated description for your tool.
- **output_schema** (`Dict[str, Any]`, *optional*) -- The JSON schema defining the expected structure of the tool output.
  This can be included in system prompts to help agents understand the expected output format. Note: This is currently
  used for informational purposes only and does not perform actual output validation.

You can also override the method [setup()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool.setup) if your tool has an expensive operation to perform before being
usable (such as loading a model). [setup()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool.setup) will be called the first time you use your tool, but not at
instantiation.



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_dict</name><anchor>smolagents.Tool.from_dict</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L367</source><parameters>[{"name": "tool_dict", "val": ": dict[str, Any]"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **tool_dict** (`dict[str, Any]`) -- Dictionary representation of the tool.
- ****kwargs** -- Additional keyword arguments to pass to the tool's constructor.</paramsdesc><paramgroups>0</paramgroups><rettype>`Tool`</rettype><retdesc>Tool object.</retdesc></docstring>

Create tool from a dictionary representation.








</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_gradio</name><anchor>smolagents.Tool.from_gradio</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L741</source><parameters>[{"name": "gradio_tool", "val": ""}]</parameters></docstring>

Creates a [Tool](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool) from a gradio tool.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_hub</name><anchor>smolagents.Tool.from_hub</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L516</source><parameters>[{"name": "repo_id", "val": ": str"}, {"name": "token", "val": ": str | None = None"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **repo_id** (`str`) --
  The name of the Space repo on the Hub where your tool is defined.
- **token** (`str`, *optional*) --
  The token to identify you on hf.co. If unset, will use the token generated when running
  `huggingface-cli login` (stored in `~/.huggingface`).
- **trust_remote_code(`str`,** *optional*, defaults to False) --
  This flags marks that you understand the risk of running remote code and that you trust this tool.
  If not setting this to True, loading the tool from Hub will fail.
- **kwargs** (additional keyword arguments, *optional*) --
  Additional keyword arguments that will be split in two: all arguments relevant to the Hub (such as
  `cache_dir`, `revision`, `subfolder`) will be used when downloading the files for your tool, and the
  others will be passed along to its init.</paramsdesc><paramgroups>0</paramgroups></docstring>

Loads a tool defined on the Hub.

<Tip warning={true}>

Loading a tool from the Hub means that you'll download the tool and execute it locally.
ALWAYS inspect the tool you're downloading before loading it within your runtime, as you would do when
installing a package using pip/npm/apt.

</Tip>




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_langchain</name><anchor>smolagents.Tool.from_langchain</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L762</source><parameters>[{"name": "langchain_tool", "val": ""}]</parameters></docstring>

Creates a [Tool](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool) from a langchain tool.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_space</name><anchor>smolagents.Tool.from_space</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L599</source><parameters>[{"name": "space_id", "val": ": str"}, {"name": "name", "val": ": str"}, {"name": "description", "val": ": str"}, {"name": "api_name", "val": ": str | None = None"}, {"name": "token", "val": ": str | None = None"}]</parameters><paramsdesc>- **space_id** (`str`) --
  The id of the Space on the Hub.
- **name** (`str`) --
  The name of the tool.
- **description** (`str`) --
  The description of the tool.
- **api_name** (`str`, *optional*) --
  The specific api_name to use, if the space has several tabs. If not precised, will default to the first available api.
- **token** (`str`, *optional*) --
  Add your token to access private spaces or increase your GPU quotas.</paramsdesc><paramgroups>0</paramgroups><rettype>[Tool](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool)</rettype><retdesc>The Space, as a tool.</retdesc></docstring>

Creates a [Tool](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool) from a Space given its id on the Hub.







<ExampleCodeBlock anchor="smolagents.Tool.from_space.example">

Examples:
```py
>>> image_generator = Tool.from_space(
...     space_id="black-forest-labs/FLUX.1-schnell",
...     name="image-generator",
...     description="Generate an image from a prompt"
... )
>>> image = image_generator("Generate an image of a cool surfer in Tahiti")
```

</ExampleCodeBlock>
<ExampleCodeBlock anchor="smolagents.Tool.from_space.example-2">

```py
>>> face_swapper = Tool.from_space(
...     "tuan2308/face-swap",
...     "face_swapper",
...     "Tool that puts the face shown on the first image on the second image. You can give it paths to images.",
... )
>>> image = face_swapper('./aymeric.jpeg', './ruth.jpg')
```

</ExampleCodeBlock>


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>push_to_hub</name><anchor>smolagents.Tool.push_to_hub</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L421</source><parameters>[{"name": "repo_id", "val": ": str"}, {"name": "commit_message", "val": ": str = 'Upload tool'"}, {"name": "private", "val": ": bool | None = None"}, {"name": "token", "val": ": bool | str | None = None"}, {"name": "create_pr", "val": ": bool = False"}]</parameters><paramsdesc>- **repo_id** (`str`) --
  The name of the repository you want to push your tool to. It should contain your organization name when
  pushing to a given organization.
- **commit_message** (`str`, *optional*, defaults to `"Upload tool"`) --
  Message to commit while pushing.
- **private** (`bool`, *optional*) --
  Whether to make the repo private. If `None` (default), the repo will be public unless the organization's default is private. This value is ignored if the repo already exists.
- **token** (`bool` or `str`, *optional*) --
  The token to use as HTTP bearer authorization for remote files. If unset, will use the token generated
  when running `huggingface-cli login` (stored in `~/.huggingface`).
- **create_pr** (`bool`, *optional*, defaults to `False`) --
  Whether to create a PR with the uploaded files or directly commit.</paramsdesc><paramgroups>0</paramgroups></docstring>

Upload the tool to the Hub.




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>save</name><anchor>smolagents.Tool.save</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L390</source><parameters>[{"name": "output_dir", "val": ": str | Path"}, {"name": "tool_file_name", "val": ": str = 'tool'"}, {"name": "make_gradio_app", "val": ": bool = True"}]</parameters><paramsdesc>- **output_dir** (`str` or `Path`) -- The folder in which you want to save your tool.
- **tool_file_name** (`str`, *optional*) -- The file name in which you want to save your tool.
- **make_gradio_app** (`bool`, *optional*, defaults to True) -- Whether to also export a `requirements.txt` file and Gradio UI.</paramsdesc><paramgroups>0</paramgroups></docstring>

Saves the relevant code files for your tool so it can be pushed to the Hub. This will copy the code of your
tool in `output_dir` as well as autogenerate:

- a `{tool_file_name}.py` file containing the logic for your tool.
If you pass `make_gradio_app=True`, this will also write:
- an `app.py` file providing a UI for your tool when it is exported to a Space with `tool.push_to_hub()`
- a `requirements.txt` containing the names of the modules used by your tool (as detected when inspecting its
  code)




</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>setup</name><anchor>smolagents.Tool.setup</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L251</source><parameters>[]</parameters></docstring>

Overwrite this method here for any operation that is expensive and needs to be executed before you start using
your tool. Such as loading a big model.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_dict</name><anchor>smolagents.Tool.to_dict</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L292</source><parameters>[]</parameters></docstring>
Returns a dictionary representing the tool

</div></div>

### launch_gradio_demo[[smolagents.launch_gradio_demo]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>smolagents.launch_gradio_demo</name><anchor>smolagents.launch_gradio_demo</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L794</source><parameters>[{"name": "tool", "val": ": Tool"}]</parameters><paramsdesc>- **tool** (`Tool`) -- The tool for which to launch the demo.</paramsdesc><paramgroups>0</paramgroups></docstring>

Launches a gradio demo for a tool. The corresponding tool class needs to properly implement the class attributes
`inputs` and `output_type`.




</div>

## Default Tools

### PythonInterpreterTool[[smolagents.PythonInterpreterTool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.PythonInterpreterTool</name><anchor>smolagents.PythonInterpreterTool</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/default_tools.py#L38</source><parameters>[{"name": "*args", "val": ""}, {"name": "authorized_imports", "val": " = None"}, {"name": "**kwargs", "val": ""}]</parameters></docstring>


</div>

### DuckDuckGoSearchTool[[smolagents.DuckDuckGoSearchTool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.DuckDuckGoSearchTool</name><anchor>smolagents.DuckDuckGoSearchTool</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/default_tools.py#L101</source><parameters>[{"name": "max_results", "val": ": int = 10"}, {"name": "rate_limit", "val": ": float | None = 1.0"}, {"name": "**kwargs", "val": ""}]</parameters><paramsdesc>- **max_results** (`int`, default `10`) -- Maximum number of search results to return.
- **rate_limit** (`float`, default `1.0`) -- Maximum queries per second. Set to `None` to disable rate limiting.
- ****kwargs** -- Additional keyword arguments for the `DDGS` client.</paramsdesc><paramgroups>0</paramgroups></docstring>
Web search tool that performs searches using the DuckDuckGo search engine.



<ExampleCodeBlock anchor="smolagents.DuckDuckGoSearchTool.example">

Examples:
```python
>>> from smolagents import DuckDuckGoSearchTool
>>> web_search_tool = DuckDuckGoSearchTool(max_results=5, rate_limit=2.0)
>>> results = web_search_tool("Hugging Face")
>>> print(results)
```

</ExampleCodeBlock>


</div>

### VisitWebpageTool[[smolagents.VisitWebpageTool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.VisitWebpageTool</name><anchor>smolagents.VisitWebpageTool</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/default_tools.py#L451</source><parameters>[{"name": "max_output_length", "val": ": int = 40000"}]</parameters></docstring>


</div>

### UserInputTool[[smolagents.UserInputTool]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.UserInputTool</name><anchor>smolagents.UserInputTool</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/default_tools.py#L90</source><parameters>[{"name": "*args", "val": ""}, {"name": "**kwargs", "val": ""}]</parameters></docstring>


</div>

## ToolCollection[[smolagents.ToolCollection]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.ToolCollection</name><anchor>smolagents.ToolCollection</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L895</source><parameters>[{"name": "tools", "val": ": list[Tool]"}]</parameters></docstring>

Tool collections enable loading a collection of tools in the agent's toolbox.

Collections can be loaded from a collection in the Hub or from an MCP server, see:
- [ToolCollection.from_hub()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.ToolCollection.from_hub)
- [ToolCollection.from_mcp()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.ToolCollection.from_mcp)

For example and usage, see: [ToolCollection.from_hub()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.ToolCollection.from_hub) and [ToolCollection.from_mcp()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.ToolCollection.from_mcp)



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_hub</name><anchor>smolagents.ToolCollection.from_hub</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L909</source><parameters>[{"name": "collection_slug", "val": ": str"}, {"name": "token", "val": ": str | None = None"}, {"name": "trust_remote_code", "val": ": bool = False"}]</parameters><paramsdesc>- **collection_slug** (str) -- The collection slug referencing the collection.
- **token** (str, *optional*) -- The authentication token if the collection is private.
- **trust_remote_code** (bool, *optional*, defaults to False) -- Whether to trust the remote code.</paramsdesc><paramgroups>0</paramgroups><rettype>ToolCollection</rettype><retdesc>A tool collection instance loaded with the tools.</retdesc></docstring>
Loads a tool collection from the Hub.

it adds a collection of tools from all Spaces in the collection to the agent's toolbox

> [!NOTE]
> Only Spaces will be fetched, so you can feel free to add models and datasets to your collection if you'd
> like for this collection to showcase them.







<ExampleCodeBlock anchor="smolagents.ToolCollection.from_hub.example">

Example:
```py
>>> from smolagents import ToolCollection, CodeAgent

>>> image_tool_collection = ToolCollection.from_hub("huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f")
>>> agent = CodeAgent(tools=[*image_tool_collection.tools], add_base_tools=True)

>>> agent.run("Please draw me a picture of rivers and lakes.")
```

</ExampleCodeBlock>


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>from_mcp</name><anchor>smolagents.ToolCollection.from_mcp</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/tools.py#L949</source><parameters>[{"name": "server_parameters", "val": ": 'mcp.StdioServerParameters' | dict"}, {"name": "trust_remote_code", "val": ": bool = False"}, {"name": "structured_output", "val": ": bool | None = None"}]</parameters><paramsdesc>- **server_parameters** (`mcp.StdioServerParameters` or `dict`) --
  Configuration parameters to connect to the MCP server. This can be:

  - An instance of `mcp.StdioServerParameters` for connecting a Stdio MCP server via standard input/output using a subprocess.

  - A `dict` with at least:
    - "url": URL of the server.
    - "transport": Transport protocol to use, one of:
      - "streamable-http": Streamable HTTP transport (default).
      - "sse": Legacy HTTP+SSE transport (deprecated).
- **trust_remote_code** (`bool`, *optional*, defaults to `False`) --
  Whether to trust the execution of code from tools defined on the MCP server.
  This option should only be set to `True` if you trust the MCP server,
  and undertand the risks associated with running remote code on your local machine.
  If set to `False`, loading tools from MCP will fail.
- **structured_output** (`bool`, *optional*, defaults to `False`) --
  Whether to enable structured output features for MCP tools. If True, enables:
  - Support for outputSchema in MCP tools
  - Structured content handling (structuredContent from MCP responses)
  - JSON parsing fallback for structured data
  If False, uses the original simple text-only behavior for backwards compatibility.</paramsdesc><paramgroups>0</paramgroups><rettype>ToolCollection</rettype><retdesc>A tool collection instance.</retdesc></docstring>
Automatically load a tool collection from an MCP server.

This method supports Stdio, Streamable HTTP, and legacy HTTP+SSE MCP servers. Look at the `server_parameters`
argument for more details on how to connect to each MCP server.

Note: a separate thread will be spawned to run an asyncio event loop handling
the MCP server.







<ExampleCodeBlock anchor="smolagents.ToolCollection.from_mcp.example">

Example with a Stdio MCP server:
```py
>>> import os
>>> from smolagents import ToolCollection, CodeAgent, InferenceClientModel
>>> from mcp import StdioServerParameters

>>> model = InferenceClientModel()

>>> server_parameters = StdioServerParameters(
>>>     command="uvx",
>>>     args=["--quiet", "pubmedmcp@0.1.3"],
>>>     env={"UV_PYTHON": "3.12", **os.environ},
>>> )

>>> with ToolCollection.from_mcp(server_parameters, trust_remote_code=True) as tool_collection:
>>>     agent = CodeAgent(tools=[*tool_collection.tools], add_base_tools=True, model=model)
>>>     agent.run("Please find a remedy for hangover.")
```

</ExampleCodeBlock>

<ExampleCodeBlock anchor="smolagents.ToolCollection.from_mcp.example-2">

Example with structured output enabled:
```py
>>> with ToolCollection.from_mcp(server_parameters, trust_remote_code=True, structured_output=True) as tool_collection:
>>>     agent = CodeAgent(tools=[*tool_collection.tools], add_base_tools=True, model=model)
>>>     agent.run("Please find a remedy for hangover.")
```

</ExampleCodeBlock>

<ExampleCodeBlock anchor="smolagents.ToolCollection.from_mcp.example-3">

Example with a Streamable HTTP MCP server:
```py
>>> with ToolCollection.from_mcp({"url": "http://127.0.0.1:8000/mcp", "transport": "streamable-http"}, trust_remote_code=True) as tool_collection:
>>>     agent = CodeAgent(tools=[*tool_collection.tools], add_base_tools=True, model=model)
>>>     agent.run("Please find a remedy for hangover.")
```

</ExampleCodeBlock>


</div></div>

## Agent टाइप्स

एजेंट्स टूल्स के बीच किसी भी प्रकार की ऑब्जेक्ट को संभाल सकते हैं; टूल्स, पूरी तरह से मल्टीमोडल होने के कारण, टेक्स्ट, इमेज, ऑडियो, वीडियो सहित अन्य प्रकारों को स्वीकार और रिटर्न कर सकते हैं। 
टूल्स के बीच अनुकूलता बढ़ाने के साथ-साथ इन रिटर्न्स को ipython (jupyter, colab, ipython notebooks, ...) में सही ढंग से रेंडर करने के लिए, हम इन टाइप्स के आसपास रैपर क्लासेज को लागू करते हैं।

रैप किए गए ऑब्जेक्ट्स को प्रारंभ में जैसा व्यवहार करना चाहिए वैसा ही करना जारी रखना चाहिए; एक टेक्स्ट ऑब्जेक्ट को अभी भी स्ट्रिंग की तरह व्यवहार करना चाहिए|
एक इमेज ऑब्जेक्ट को अभी भी `PIL.Image` की तरह व्यवहार करना चाहिए।

इन टाइप्स के तीन विशिष्ट उद्देश्य हैं:

- टाइप पर `to_raw` को कॉल करने से अंतर्निहित ऑब्जेक्ट रिटर्न होना चाहिए
- टाइप पर `to_string` को कॉल करने से ऑब्जेक्ट को स्ट्रिंग के रूप में रिटर्न होना चाहिए: वह `AgentText` के मामले में स्ट्रिंग हो सकती है लेकिन अन्य उदाहरणों में ऑब्जेक्ट के सीरियलाइज्ड वर्जन का पाथ होगा
- इसे एक ipython kernel में प्रदर्शित करने पर ऑब्जेक्ट को सही ढंग से प्रदर्शित करना चाहिए

### AgentText[[smolagents.AgentText]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.AgentText</name><anchor>smolagents.AgentText</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agent_types.py#L62</source><parameters>[{"name": "value", "val": ""}]</parameters></docstring>

Text type returned by the agent. Behaves as a string.


</div>

### AgentImage[[smolagents.AgentImage]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.AgentImage</name><anchor>smolagents.AgentImage</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agent_types.py#L74</source><parameters>[{"name": "value", "val": ""}]</parameters></docstring>

Image type returned by the agent. Behaves as a PIL.Image.Image.



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>save</name><anchor>smolagents.AgentImage.save</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agent_types.py#L164</source><parameters>[{"name": "output_bytes", "val": ""}, {"name": "format", "val": ": str = None"}, {"name": "**params", "val": ""}]</parameters><paramsdesc>- **output_bytes** (bytes) -- The output bytes to save the image to.
- **format** (str) -- The format to use for the output image. The format is the same as in PIL.Image.save.
- ****params** -- Additional parameters to pass to PIL.Image.save.</paramsdesc><paramgroups>0</paramgroups></docstring>

Saves the image to a file.



</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_raw</name><anchor>smolagents.AgentImage.to_raw</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agent_types.py#L119</source><parameters>[]</parameters></docstring>

Returns the "raw" version of that object. In the case of an AgentImage, it is a PIL.Image.Image.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_string</name><anchor>smolagents.AgentImage.to_string</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agent_types.py#L136</source><parameters>[]</parameters></docstring>

Returns the stringified version of that object. In the case of an AgentImage, it is a path to the serialized
version of the image.


</div></div>

### AgentAudio[[smolagents.AgentAudio]]

<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>class smolagents.AgentAudio</name><anchor>smolagents.AgentAudio</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agent_types.py#L176</source><parameters>[{"name": "value", "val": ""}, {"name": "samplerate", "val": " = 16000"}]</parameters></docstring>

Audio type returned by the agent.



<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_raw</name><anchor>smolagents.AgentAudio.to_raw</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agent_types.py#L216</source><parameters>[]</parameters></docstring>

Returns the "raw" version of that object. It is a `torch.Tensor` object.


</div>
<div class="docstring border-l-2 border-t-2 pl-4 pt-3.5 border-gray-100 rounded-tl-xl mb-6 mt-8">


<docstring><name>to_string</name><anchor>smolagents.AgentAudio.to_string</anchor><source>https://github.com/huggingface/smolagents/blob/v1.22.0/src/smolagents/agent_types.py#L237</source><parameters>[]</parameters></docstring>

Returns the stringified version of that object. In the case of an AgentAudio, it is a path to the serialized
version of the audio.


</div></div>

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/reference/tools.md" />

### मल्टी-एजेंट सिस्टम का आयोजन करें 🤖🤝🤖
https://huggingface.co/docs/smolagents/v1.22.0/hi/examples/multiagents.md

# मल्टी-एजेंट सिस्टम का आयोजन करें 🤖🤝🤖

<DocNotebookDropdown
  classNames="absolute z-10 right-0 top-0"
  options={[
    {label: "Mixed", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/multiagents.ipynb"},
    {label: "PyTorch", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/multiagents.ipynb"},
    {label: "TensorFlow", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/multiagents.ipynb"},
    {label: "Mixed", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/multiagents.ipynb"},
    {label: "PyTorch", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/multiagents.ipynb"},
    {label: "TensorFlow", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/multiagents.ipynb"},
]} />

इस नोटबुक में हम एक **मल्टी-एजेंट वेब ब्राउज़र बनाएंगे: एक एजेंटिक सिस्टम जिसमें कई एजेंट वेब का उपयोग करके समस्याओं को हल करने के लिए सहयोग करते हैं!**

यह एक सरल संरचना होगी, जो प्रबंधित वेब खोज एजेंट को रैप करने के लिए `ManagedAgent` ऑब्जेक्ट का उपयोग करता है:

```
              +----------------+
              | Manager agent  |
              +----------------+
                       |
        _______________|______________
       |                              |
  Code interpreter   +--------------------------------+
       tool          |         Managed agent          |
                     |      +------------------+      |
                     |      | Web Search agent |      |
                     |      +------------------+      |
                     |         |            |         |
                     |  Web Search tool     |         |
                     |             Visit webpage tool |
                     +--------------------------------+
```
आइए इस सिस्टम को सेट करें।

आवश्यक डिपेंडेंसी इंस्टॉल करने के लिए नीचे दी गई लाइन चलाएं:

```
!pip install 'smolagents[toolkit]' --upgrade -q
```

HF Inference API को कॉल करने के लिए लॉगिन करें:

```
from huggingface_hub import login

login()
```

⚡️ हमारा एजेंट [Qwen/Qwen2.5-Coder-32B-Instruct](https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct) द्वारा संचालित होगा जो `InferenceClientModel` क्लास का उपयोग करता है जो HF के Inference API का उपयोग करता है: Inference API किसी भी OS मॉडल को जल्दी और आसानी से चलाने की अनुमति देता है।

_नोट:_ The Inference API विभिन्न मानदंडों के आधार पर मॉडल होस्ट करता है, और डिप्लॉय किए गए मॉडल बिना पूर्व सूचना के अपडेट या बदले जा सकते हैं। इसके बारे में अधिक जानें [यहां](https://huggingface.co/docs/api-inference/supported-models)।

```py
model_id = "Qwen/Qwen2.5-Coder-32B-Instruct"
```

## 🔍 एक वेब सर्च टूल बनाएं

वेब ब्राउज़िंग के लिए, हम पहले से मौजूद `WebSearchTool` टूल का उपयोग कर सकते हैं जो Google search के समान सुविधा प्रदान करता है।

लेकिन फिर हमें `WebSearchTool` द्वारा खोजे गए पेज को देखने में भी सक्षम होने की आवश्यकता होगी।
ऐसा करने के लिए, हम लाइब्रेरी के बिल्ट-इन `VisitWebpageTool` को इम्पोर्ट कर सकते हैं, लेकिन हम इसे फिर से बनाएंगे यह देखने के लिए कि यह कैसे किया जाता है।

तो आइए `markdownify` का उपयोग करके शुरू से अपना `VisitWebpageTool` टूल बनाएं।

```py
import re
import requests
from markdownify import markdownify
from requests.exceptions import RequestException
from smolagents import tool


@tool
def visit_webpage(url: str) -> str:
    """Visits a webpage at the given URL and returns its content as a markdown string.

    Args:
        url: The URL of the webpage to visit.

    Returns:
        The content of the webpage converted to Markdown, or an error message if the request fails.
    """
    try:
        # Send a GET request to the URL
        response = requests.get(url)
        response.raise_for_status()  # Raise an exception for bad status codes

        # Convert the HTML content to Markdown
        markdown_content = markdownify(response.text).strip()

        # Remove multiple line breaks
        markdown_content = re.sub(r"\n{3,}", "\n\n", markdown_content)

        return markdown_content

    except RequestException as e:
        return f"Error fetching the webpage: {str(e)}"
    except Exception as e:
        return f"An unexpected error occurred: {str(e)}"
```

ठीक है, अब चलिए हमारे टूल को टेस्ट करें!

```py
print(visit_webpage("https://en.wikipedia.org/wiki/Hugging_Face")[:500])
```

## हमारी मल्टी-एजेंट सिस्टम का निर्माण करें 🤖🤝🤖

अब जब हमारे पास सभी टूल्स `search` और `visit_webpage` हैं, हम उनका उपयोग वेब एजेंट बनाने के लिए कर सकते हैं।

इस एजेंट के लिए कौन सा कॉन्फ़िगरेशन चुनें?
- वेब ब्राउज़िंग एक सिंगल-टाइमलाइन टास्क है जिसे समानांतर टूल कॉल की आवश्यकता नहीं है, इसलिए JSON टूल कॉलिंग इसके लिए अच्छी तरह काम करती है। इसलिए हम `ToolCallingAgent` चुनते हैं।
- साथ ही, चूंकि कभी-कभी वेब सर्च में सही उत्तर खोजने से पहले कई पेजों की सर्च करने की आवश्यकता होती है, हम `max_steps` को बढ़ाकर 10 करना पसंद करते हैं।

```py
from smolagents import (
    CodeAgent,
    ToolCallingAgent,
    InferenceClientModel,
    ManagedAgent,
    WebSearchTool,
    LiteLLMModel,
)

model = InferenceClientModel(model_id=model_id)

web_agent = ToolCallingAgent(
    tools=[WebSearchTool(), visit_webpage],
    model=model,
    max_steps=10,
)
```

फिर हम इस एजेंट को एक `ManagedAgent` में रैप करते हैं जो इसे इसके मैनेजर एजेंट द्वारा कॉल करने योग्य बनाएगा।

```py
managed_web_agent = ManagedAgent(
    agent=web_agent,
    name="search",
    description="Runs web searches for you. Give it your query as an argument.",
)
```

अंत में हम एक मैनेजर एजेंट बनाते हैं, और इनिशियलाइजेशन पर हम अपने मैनेज्ड एजेंट को इसके `managed_agents` आर्गुमेंट में पास करते हैं।

चूंकि यह एजेंट योजना बनाने और सोचने का काम करता है, उन्नत तर्क लाभदायक होगा, इसलिए `CodeAgent` सबसे अच्छा विकल्प होगा।

साथ ही, हम एक ऐसा प्रश्न पूछना चाहते हैं जिसमें वर्तमान वर्ष और अतिरिक्त डेटा गणना शामिल है: इसलिए आइए `additional_authorized_imports=["time", "numpy", "pandas"]` जोड़ें, यदि एजेंट को इन पैकेजों की आवश्यकता हो।

```py
manager_agent = CodeAgent(
    tools=[],
    model=model,
    managed_agents=[managed_web_agent],
    additional_authorized_imports=["time", "numpy", "pandas"],
)
```

बस इतना ही! अब चलिए हमारे सिस्टम को चलाते हैं! हम एक ऐसा प्रश्न चुनते हैं जिसमें गणना और शोध दोनों की आवश्यकता है।

```py
answer = manager_agent.run("If LLM training continues to scale up at the current rhythm until 2030, what would be the electric power in GW required to power the biggest training runs by 2030? What would that correspond to, compared to some countries? Please provide a source for any numbers used.")
```

We get this report as the answer:
```
Based on current growth projections and energy consumption estimates, if LLM trainings continue to scale up at the 
current rhythm until 2030:

1. The electric power required to power the biggest training runs by 2030 would be approximately 303.74 GW, which 
translates to about 2,660,762 GWh/year.

2. Comparing this to countries' electricity consumption:
   - It would be equivalent to about 34% of China's total electricity consumption.
   - It would exceed the total electricity consumption of India (184%), Russia (267%), and Japan (291%).
   - It would be nearly 9 times the electricity consumption of countries like Italy or Mexico.

3. Source of numbers:
   - The initial estimate of 5 GW for future LLM training comes from AWS CEO Matt Garman.
   - The growth projection used a CAGR of 79.80% from market research by Springs.
   - Country electricity consumption data is from the U.S. Energy Information Administration, primarily for the year 
2021.
```

लगता है कि यदि [स्केलिंग हाइपोथिसिस](https://gwern.net/scaling-hypothesis) सत्य बनी रहती है तो हमें कुछ बड़े पावरप्लांट्स की आवश्यकता होगी।

हमारे एजेंट्स ने कार्य को हल करने के लिए कुशलतापूर्वक सहयोग किया! ✅

💡 आप इस ऑर्केस्ट्रेशन को आसानी से अधिक एजेंट्स में विस्तारित कर सकते हैं: एक कोड एक्जीक्यूशन करता है, एक वेब सर्च करता है, एक फाइल लोडिंग को संभालता है।


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/examples/multiagents.md" />

### एजेंटिक RAG
https://huggingface.co/docs/smolagents/v1.22.0/hi/examples/rag.md

# एजेंटिक RAG

<DocNotebookDropdown
  classNames="absolute z-10 right-0 top-0"
  options={[
    {label: "Mixed", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/rag.ipynb"},
    {label: "PyTorch", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/rag.ipynb"},
    {label: "TensorFlow", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/rag.ipynb"},
    {label: "Mixed", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/rag.ipynb"},
    {label: "PyTorch", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/rag.ipynb"},
    {label: "TensorFlow", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/rag.ipynb"},
]} />

रिट्रीवल-ऑगमेंटेड-जनरेशन (RAG) है "एक यूजर के प्रश्न का उत्तर देने के लिए LLM का उपयोग करना, लेकिन उत्तर को एक नॉलेज बेस से प्राप्त जानकारी पर आधारित करना"। इसमें वैनिला या फाइन-ट्यून्ड LLM का उपयोग करने की तुलना में कई फायदे हैं: कुछ नाम लेने के लिए, यह उत्तर को सत्य तथ्यों पर आधारित करने और काल्पनिक बातों को कम करने की अनुमति देता है, यह LLM को डोमेन-विशिष्ट ज्ञान प्रदान करने की अनुमति देता है, और यह नॉलेज बेस से जानकारी तक पहुंच का सूक्ष्म नियंत्रण प्रदान करता है।

लेकिन वैनिला RAG की सीमाएं हैं, सबसे महत्वपूर्ण ये दो:
- यह केवल एक रिट्रीवल स्टेप करता है: यदि परिणाम खराब हैं, तो जनरेशन भी बदले में खराब होगा।
- सिमेंटिक समानता की गणना यूजर के प्रश्न को संदर्भ के रूप में करके की जाती है, जो अनुकूल नहीं हो सकती: उदाहरण के लिए, यूजर का प्रश्न अक्सर एक सवाल होगा, जबकि सही उत्तर देने वाला डॉक्यूमेंट सकारात्मक स्वर में हो सकता है, और इसका समानता स्कोर अन्य स्रोत दस्तावेज़ों की तुलना में कम हो सकता है, जो प्रश्नवाचक स्वर में हो सकते हैं। इससे संबंधित जानकारी को चूकने का जोखिम होता है।

हम एक RAG एजेंट बनाकर इन समस्याओं को कम कर सकते हैं: बहुत सरल तरीके से, एक रिट्रीवर टूल से लैस एजेंट!

यह एजेंट करेगा: ✅ स्वयं क्वेरी तैयार करेगा और ✅ आवश्यकता पड़ने पर पुनः-प्राप्ति के लिए समीक्षा करेगा।

इसलिए यह सहज रूप से कुछ उन्नत RAG तकनीकों को प्राप्त कर लेना चाहिए!
- सिमेंटिक खोज में सीधे यूजर क्वेरी का संदर्भ के रूप में उपयोग करने के बजाय, एजेंट स्वयं एक संदर्भ वाक्य तैयार करता है जो लक्षित डॉक्यूमेंट्स के करीब हो सकता है, जैसा कि [HyDE](https://huggingface.co/papers/2212.10496) में किया गया है।
एजेंट जनरेट किए गए स्निपेट्स का उपयोग कर सकता है और आवश्यकता पड़ने पर पुनः-प्राप्ति कर सकता है, जैसा कि [Self-Query](https://docs.llamaindex.ai/en/stable/examples/evaluation/RetryQuery/) में किया गया है।

चलिए इस सिस्टम को बनाते हैं। 🛠️

आवश्यक डिपेंडेंसी इंस्टॉल करने के लिए नीचे दी गई लाइन चलाएं।
```bash
!pip install smolagents pandas langchain langchain-community sentence-transformers rank_bm25 --upgrade -q
```
HF Inference API को कॉल करने के लिए, आपको अपने एनवायरनमेंट वेरिएबल `HF_TOKEN` के रूप में एक वैध टोकन की आवश्यकता होगी।
हम इसे लोड करने के लिए python-dotenv का उपयोग करते हैं।
```py
from dotenv import load_dotenv
load_dotenv()
```

हम पहले एक नॉलेज बेस लोड करते हैं जिस पर हम RAG को लागू करना चाहते हैं: यह डेटा सेट Hugging Face के कई लाइब्रेरी के डॉक्यूमेंट पृष्ठों का संकलन है, जिन्हें Markdown में स्टोर किया गया है। हम केवल `transformers` लाइब्रेरी के दस्तावेज़ों को रखेंगे।

फिर डेटासेट को प्रोसेस करके और इसे एक वेक्टर डेटाबेस में स्टोर करके नॉलेज बेस तैयार करें जिसे रिट्रीवर द्वारा उपयोग किया जाएगा।

हम [LangChain](https://python.langchain.com/docs/introduction/) का उपयोग करते हैं क्योंकि इसमें उत्कृष्ट वेक्टर डेटाबेस उपयोगिताएं हैं।

```py
import datasets
from langchain.docstore.document import Document
from langchain.text_splitter import RecursiveCharacterTextSplitter
from langchain_community.retrievers import BM25Retriever

knowledge_base = datasets.load_dataset("m-ric/huggingface_doc", split="train")
knowledge_base = knowledge_base.filter(lambda row: row["source"].startswith("huggingface/transformers"))

source_docs = [
    Document(page_content=doc["text"], metadata={"source": doc["source"].split("/")[1]})
    for doc in knowledge_base
]

text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=500,
    chunk_overlap=50,
    add_start_index=True,
    strip_whitespace=True,
    separators=["\n\n", "\n", ".", " ", ""],
)
docs_processed = text_splitter.split_documents(source_docs)
```

अब डॉक्यूमेंट्स तैयार हैं।

तो चलिए अपना एजेंटिक RAG सिस्टम बनाएं!

👉 हमें केवल एक RetrieverTool की आवश्यकता है जिसका उपयोग हमारा एजेंट नॉलेज बेस से जानकारी प्राप्त करने के लिए कर सकता है।

चूंकि हमें टूल के एट्रीब्यूट के रूप में एक vectordb जोड़ने की आवश्यकता है, हम सरल टूल कंस्ट्रक्टर को `@tool` डेकोरेटर के साथ सीधे उपयोग नहीं कर सकते: इसलिए हम [tools tutorial](../tutorials/tools) में हाइलाइट किए गए सेटअप का पालन करेंगे।

```py
from smolagents import Tool

class RetrieverTool(Tool):
    name = "retriever"
    description = "Uses semantic search to retrieve the parts of transformers documentation that could be most relevant to answer your query."
    inputs = {
        "query": {
            "type": "string",
            "description": "The query to perform. This should be semantically close to your target documents. Use the affirmative form rather than a question.",
        }
    }
    output_type = "string"

    def __init__(self, docs, **kwargs):
        super().__init__(**kwargs)
        self.retriever = BM25Retriever.from_documents(
            docs, k=10
        )

    def forward(self, query: str) -> str:
        assert isinstance(query, str), "Your search query must be a string"

        docs = self.retriever.invoke(
            query,
        )
        return "\nRetrieved documents:\n" + "".join(
            [
                f"\n\n===== Document {str(i)} =====\n" + doc.page_content
                for i, doc in enumerate(docs)
            ]
        )

retriever_tool = RetrieverTool(docs_processed)
```
हमने BM25 का उपयोग किया है, जो एक क्लासिक रिट्रीवल विधि है,  क्योंकि इसे सेटअप करना बहुत आसान है।
रिट्रीवल सटीकता में सुधार करने के लिए, आप BM25 को डॉक्यूमेंट्स के लिए वेक्टर प्रतिनिधित्व का उपयोग करके सिमेंटिक खोज से बदल सकते हैं: इस प्रकार आप एक अच्छा एम्बेडिंग मॉडल चुनने के लिए [MTEB Leaderboard](https://huggingface.co/spaces/mteb/leaderboard) पर जा सकते हैं।

अब यह सीधा है कि एक एजेंट बनाया जाए जो इस `retriever_tool` का उपयोग करेगा!


एजेंट को इनिशियलाइजेशन पर इन आर्गुमेंट्स की आवश्यकता होगी:
- `tools`: टूल्स की एक सूची जिन्हें एजेंट कॉल कर सकेगा।
- `model`: LLM जो एजेंट को पावर देता है।
हमारा `model` एक कॉलेबल होना चाहिए जो इनपुट के रूप में संदेशों की एक सूची लेता है और टेक्स्ट लौटाता है। इसे एक stop_sequences आर्गुमेंट भी स्वीकार करने की आवश्यकता है जो बताता है कि जनरेशन कब रोकनी है। सुविधा के लिए, हम सीधे पैकेज में प्रदान की गई HfEngine क्लास का उपयोग करते हैं ताकि एक LLM इंजन मिल सके जो Hugging Face के Inference API को कॉल करता है।

और हम [meta-llama/Llama-3.3-70B-Instruct](meta-llama/Llama-3.3-70B-Instruct) का उपयोग llm इंजन के रूप में करते हैं क्योंकि:
- इसमें लंबा 128k कॉन्टेक्स्ट है, जो लंबे स्रोत दस्तावेजों को प्रोसेस करने में मददगार है
- यह हर समय HF के Inference API पर मुफ्त में उपलब्ध है!

_नोट:_ Inference API विभिन्न मानदंडों के आधार पर मॉडल होस्ट करता है, और डिप्लॉय किए गए मॉडल बिना पूर्व सूचना के अपडेट या बदले जा सकते हैं। इसके बारे में अधिक जानें [यहां](https://huggingface.co/docs/api-inference/supported-models) पढ़ें।

```py
from smolagents import InferenceClientModel, CodeAgent

agent = CodeAgent(
    tools=[retriever_tool], model=InferenceClientModel(model_id="meta-llama/Llama-3.3-70B-Instruct"), max_steps=4, verbosity_level=2
)
```

CodeAgent को इनिशियलाइज करने पर, इसे स्वचालित रूप से एक डिफ़ॉल्ट सिस्टम प्रॉम्प्ट दिया गया है जो LLM इंजन को चरण-दर-चरण प्रोसेस करने और कोड स्निपेट्स के रूप में टूल कॉल जनरेट करने के लिए कहता है, लेकिन आप आवश्यकतानुसार इस प्रॉम्प्ट टेम्पलेट को अपने से बदल सकते हैं।

जब CodeAgent का `.run()` मेथड लॉन्च किया जाता है, तो एजेंट LLM इंजन को कॉल करने का कार्य करता है, और टूल कॉल्स को निष्पादित करता है, यह सब एक लूप में होता है, जो तब तक चलता है जब तक टूल final_answer के साथ अंतिम उत्तर के रूप में नहीं बुलाया जाता।

```py
agent_output = agent.run("For a transformers model training, which is slower, the forward or the backward pass?")

print("Final output:")
print(agent_output)
```




<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/examples/rag.md" />

### Text-to-SQL
https://huggingface.co/docs/smolagents/v1.22.0/hi/examples/text_to_sql.md

# Text-to-SQL

<DocNotebookDropdown
  classNames="absolute z-10 right-0 top-0"
  options={[
    {label: "Mixed", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/text_to_sql.ipynb"},
    {label: "PyTorch", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/text_to_sql.ipynb"},
    {label: "TensorFlow", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/text_to_sql.ipynb"},
    {label: "Mixed", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/text_to_sql.ipynb"},
    {label: "PyTorch", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/text_to_sql.ipynb"},
    {label: "TensorFlow", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/text_to_sql.ipynb"},
]} />

इस ट्यूटोरियल में, हम देखेंगे कि कैसे `smolagents` का उपयोग करके एक एजेंट को SQL का उपयोग करने के लिए लागू किया जा सकता है।

> आइए सबसे महत्वपूर्ण प्रश्न से शुरू करें: इसे साधारण क्यों नहीं रखें और एक सामान्य text-to-SQL पाइपलाइन का उपयोग करें?

एक सामान्य text-to-SQL पाइपलाइन कमजोर होती है, क्योंकि उत्पन्न SQL क्वेरी गलत हो सकती है। इससे भी बुरी बात यह है कि क्वेरी गलत हो सकती है, लेकिन कोई एरर नहीं दिखाएगी, बल्कि बिना किसी अलार्म के गलत/बेकार आउटपुट दे सकती है।


👉 इसके बजाय, एक एजेंट सिस्टम आउटपुट का गंभीरता से निरीक्षण कर सकता है और तय कर सकता है कि क्वेरी को बदलने की जरूरत है या नहीं, इस प्रकार इसे बेहतर प्रदर्शन में मदद मिलती है।

आइए इस एजेंट को बनाएं! 💪

पहले, हम SQL एनवायरनमेंट सेटअप करते हैं:
```py
from sqlalchemy import (
    create_engine,
    MetaData,
    Table,
    Column,
    String,
    Integer,
    Float,
    insert,
    inspect,
    text,
)

engine = create_engine("sqlite:///:memory:")
metadata_obj = MetaData()

# create city SQL table
table_name = "receipts"
receipts = Table(
    table_name,
    metadata_obj,
    Column("receipt_id", Integer, primary_key=True),
    Column("customer_name", String(16), primary_key=True),
    Column("price", Float),
    Column("tip", Float),
)
metadata_obj.create_all(engine)

rows = [
    {"receipt_id": 1, "customer_name": "Alan Payne", "price": 12.06, "tip": 1.20},
    {"receipt_id": 2, "customer_name": "Alex Mason", "price": 23.86, "tip": 0.24},
    {"receipt_id": 3, "customer_name": "Woodrow Wilson", "price": 53.43, "tip": 5.43},
    {"receipt_id": 4, "customer_name": "Margaret James", "price": 21.11, "tip": 1.00},
]
for row in rows:
    stmt = insert(receipts).values(**row)
    with engine.begin() as connection:
        cursor = connection.execute(stmt)
```

### Agent बनाएं

अब आइए हमारी SQL टेबल को एक टूल द्वारा पुनर्प्राप्त करने योग्य बनाएं। 

टूल का विवरण विशेषता एजेंट सिस्टम द्वारा LLM के prompt में एम्बेड किया जाएगा: यह LLM को टूल का उपयोग करने के बारे में जानकारी देता है। यहीं पर हम SQL टेबल का वर्णन करना चाहते हैं।

```py
inspector = inspect(engine)
columns_info = [(col["name"], col["type"]) for col in inspector.get_columns("receipts")]

table_description = "Columns:\n" + "\n".join([f"  - {name}: {col_type}" for name, col_type in columns_info])
print(table_description)
```

```text
Columns:
  - receipt_id: INTEGER
  - customer_name: VARCHAR(16)
  - price: FLOAT
  - tip: FLOAT
```

अब आइए हमारा टूल बनाएं। इसे निम्नलिखित की आवश्यकता है: (अधिक जानकारी के लिए [टूल doc](../tutorials/tools) पढ़ें)
- एक डॉकस्ट्रिंग जिसमें आर्ग्युमेंट्स की सूची वाला `Args:` भाग हो।
- इनपुट और आउटपुट दोनों पर टाइप हिंट्स।

```py
from smolagents import tool

@tool
def sql_engine(query: str) -> str:
    """
    Allows you to perform SQL queries on the table. Returns a string representation of the result.
    The table is named 'receipts'. Its description is as follows:
        Columns:
        - receipt_id: INTEGER
        - customer_name: VARCHAR(16)
        - price: FLOAT
        - tip: FLOAT

    Args:
        query: The query to perform. This should be correct SQL.
    """
    output = ""
    with engine.connect() as con:
        rows = con.execute(text(query))
        for row in rows:
            output += "\n" + str(row)
    return output
```

अब आइए एक एजेंट बनाएं जो इस टूल का लाभ उठाता है।

हम `CodeAgent` का उपयोग करते हैं, जो smolagents का मुख्य एजेंट क्लास है: एक एजेंट जो कोड में एक्शन लिखता है और ReAct फ्रेमवर्क के अनुसार पिछले आउटपुट पर पुनरावृत्ति कर सकता है।

मॉडल वह LLM है जो एजेंट सिस्टम को संचालित करता है। `InferenceClientModel` आपको HF के Inference API का उपयोग करके LLM को कॉल करने की अनुमति देता है, या तो सर्वरलेस या डेडिकेटेड एंडपॉइंट के माध्यम से, लेकिन आप किसी भी प्रोप्राइटरी API का भी उपयोग कर सकते हैं।

```py
from smolagents import CodeAgent, InferenceClientModel

agent = CodeAgent(
    tools=[sql_engine],
    model=InferenceClientModel(model_id="meta-llama/Meta-Llama-3.1-8B-Instruct"),
)
agent.run("Can you give me the name of the client who got the most expensive receipt?")
```

### लेवल 2: टेबल जॉइन्स

अब आइए इसे और चुनौतीपूर्ण बनाएं! हम चाहते हैं कि हमारा एजेंट कई टेबल्स के बीच जॉइन को संभाल सके। 

तो आइए हम प्रत्येक receipt_id के लिए वेटर्स के नाम रिकॉर्ड करने वाली एक दूसरी टेबल बनाते हैं!

```py
table_name = "waiters"
receipts = Table(
    table_name,
    metadata_obj,
    Column("receipt_id", Integer, primary_key=True),
    Column("waiter_name", String(16), primary_key=True),
)
metadata_obj.create_all(engine)

rows = [
    {"receipt_id": 1, "waiter_name": "Corey Johnson"},
    {"receipt_id": 2, "waiter_name": "Michael Watts"},
    {"receipt_id": 3, "waiter_name": "Michael Watts"},
    {"receipt_id": 4, "waiter_name": "Margaret James"},
]
for row in rows:
    stmt = insert(receipts).values(**row)
    with engine.begin() as connection:
        cursor = connection.execute(stmt)
```
चूंकि हमने टेबल को बदल दिया है, हम LLM को इस टेबल की जानकारी का उचित उपयोग करने देने के लिए इस टेबल के विवरण के साथ `SQLExecutorTool` को अपडेट करते हैं।

```py
updated_description = """Allows you to perform SQL queries on the table. Beware that this tool's output is a string representation of the execution output.
It can use the following tables:"""

inspector = inspect(engine)
for table in ["receipts", "waiters"]:
    columns_info = [(col["name"], col["type"]) for col in inspector.get_columns(table)]

    table_description = f"Table '{table}':\n"

    table_description += "Columns:\n" + "\n".join([f"  - {name}: {col_type}" for name, col_type in columns_info])
    updated_description += "\n\n" + table_description

print(updated_description)
```
चूंकि यह रिक्वेस्ट पिछले वाले से थोड़ी कठिन है, हम LLM इंजन को अधिक शक्तिशाली [Qwen/Qwen2.5-Coder-32B-Instruct](https://huggingface.co/Qwen/Qwen2.5-Coder-32B-Instruct) का उपयोग करने के लिए स्विच करेंगे!

```py
sql_engine.description = updated_description

agent = CodeAgent(
    tools=[sql_engine],
    model=InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct"),
)

agent.run("Which waiter got more total money from tips?")
```
यह सीधे काम करता है! सेटअप आश्चर्यजनक रूप से सरल था, है ना?

यह उदाहरण पूरा हो गया! हमने इन अवधारणाओं को छुआ है:
- नए टूल्स का निर्माण।
- टूल के विवरण को अपडेट करना।
- एक मजबूत LLM में स्विच करने से एजेंट की तर्कशक्ति में मदद मिलती है।

✅ अब आप वह text-to-SQL सिस्टम बना सकते हैं जिसका आपने हमेशा सपना देखा है! ✨

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/examples/text_to_sql.md" />

### सुरक्षित कोड एक्जीक्यूशन
https://huggingface.co/docs/smolagents/v1.22.0/hi/tutorials/secure_code_execution.md

# सुरक्षित कोड एक्जीक्यूशन

<DocNotebookDropdown
  classNames="absolute z-10 right-0 top-0"
  options={[
    {label: "Mixed", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/secure_code_execution.ipynb"},
    {label: "PyTorch", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/secure_code_execution.ipynb"},
    {label: "TensorFlow", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/secure_code_execution.ipynb"},
    {label: "Mixed", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/secure_code_execution.ipynb"},
    {label: "PyTorch", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/secure_code_execution.ipynb"},
    {label: "TensorFlow", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/secure_code_execution.ipynb"},
]} />

> [!TIP]
> यदि आप एजेंट्स बनाने में नए हैं, तो सबसे पहले [एजेंट्स का परिचय](../conceptual_guides/intro_agents) और [smolagents की गाइडेड टूर](../guided_tour) पढ़ना सुनिश्चित करें।

### कोड Agents

[कई](https://huggingface.co/papers/2402.01030) [शोध](https://huggingface.co/papers/2411.01747) [पत्रों](https://huggingface.co/papers/2401.00812) ने दिखाया है कि LLM द्वारा अपनी क्रियाओं (टूल कॉल्स) को कोड में लिखना, टूल कॉलिंग के वर्तमान मानक प्रारूप से बहुत बेहतर है, जो industry में "टूल्स नेम्स और आर्ग्यूमेंट्स को JSON के रूप में लिखने" के विभिन्न रूप हैं।

कोड बेहतर क्यों है? क्योंकि हमने अपनी कोड भाषाओं को विशेष रूप से कंप्यूटर द्वारा की जाने वाली क्रियाओं को व्यक्त करने के लिए तैयार किया है। यदि JSON स्निपेट्स एक बेहतर तरीका होता, तो यह पैकेज JSON स्निपेट्स में लिखा गया होता और शैतान हम पर हंस रहा होता।

कोड कंप्यूटर पर क्रियाएँ व्यक्त करने का बेहतर तरीका है। इसमें बेहतर है:
- **कंपोज़ेबिलिटी:** क्या आप JSON क्रियाओं को एक-दूसरे के भीतर नेस्ट कर सकते हैं, या बाद में पुन: उपयोग करने के लिए JSON क्रियाओं का एक सेट परिभाषित कर सकते हैं, जैसे आप बस एक पायथन फ़ंक्शन परिभाषित कर सकते हैं?
- **ऑब्जेक्ट प्रबंधन:** JSON में `generate_image` जैसी क्रिया का आउटपुट कैसे स्टोर करें?
- **सामान्यता:** कोड किसी भी कंप्यूटर कार्य को व्यक्त करने के लिए बनाया गया है।
- **LLM प्रशिक्षण कॉर्पस में प्रतिनिधित्व:** क्यों न इस आशीर्वाद का लाभ उठाएं कि उच्च गुणवत्ता वाले कोड उदाहरण पहले से ही LLM प्रशिक्षण डेटा में शामिल हैं?

यह नीचे दी गई छवि में दर्शाया गया है, जो [Executable Code Actions Elicit Better LLM Agents](https://huggingface.co/papers/2402.01030) से ली गई है।

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/code_vs_json_actions.png">

यही कारण है कि हमने कोड एजेंट्स, इस मामले में पायथन एजेंट्स पर जोर दिया, जिसका मतलब सुरक्षित पायथन इंटरप्रेटर बनाने पर अधिक प्रयास करना था।

### लोकल पायथन इंटरप्रेटर

डिफ़ॉल्ट रूप से, `CodeAgent` LLM-जनरेटेड कोड को आपके एनवायरनमेंट में चलाता है।
यह एक्जीक्यूशन वैनिला पायथन इंटरप्रेटर द्वारा नहीं किया जाता: हमने एक अधिक सुरक्षित `LocalPythonExecutor` को शुरू से फिर से बनाया है।
यह इंटरप्रेटर सुरक्षा के लिए डिज़ाइन किया गया है:
 - इम्पोर्ट्स को उपयोगकर्ता द्वारा स्पष्ट रूप से पास की गई सूची तक सीमित करना
 - इनफिनिट लूप्स और रिसोर्स ब्लोटिंग को रोकने के लिए ऑपरेशंस की संख्या को कैप करना
 - कोई भी ऐसा ऑपरेशन नहीं करेगा जो पूर्व-परिभाषित नहीं है

हमने इसे कई उपयोग मामलों में इस्तेमाल किया है, और कभी भी एनवायरनमेंट को कोई नुकसान नहीं देखा। 

हालांकि यह समाधान पूरी तरह से सुरक्षित नहीं है: कोई ऐसे अवसरों की कल्पना कर सकता है जहां दुर्भावनापूर्ण कार्यों के लिए फाइन-ट्यून किए गए LLM अभी भी आपके एनवायरनमेंट को नुकसान पहुंचा सकते हैं। उदाहरण के लिए यदि आपने छवियों को प्रोसेस करने के लिए `Pillow` जैसे मासूम पैकेज की अनुमति दी है, तो LLM आपकी हार्ड ड्राइव को ब्लोट करने के लिए हजारों छवियों को सेव कर सकता है।
यदि आपने खुद LLM इंजन चुना है तो यह निश्चित रूप से संभावित नहीं है, लेकिन यह हो सकता है।

तो यदि आप अतिरिक्त सावधानी बरतना चाहते हैं, तो आप नीचे वर्णित रिमोट कोड एक्जीक्यूशन विकल्प का उपयोग कर सकते हैं।

### E2B कोड एक्जीक्यूटर

अधिकतम सुरक्षा के लिए, आप कोड को सैंडबॉक्स्ड एनवायरनमेंट में चलाने के लिए E2B के साथ हमारे एकीकरण का उपयोग कर सकते हैं। यह एक रिमोट एक्जीक्यूशन सेवा है जो आपके कोड को एक आइसोलेटेड कंटेनर में चलाती है, जिससे कोड का आपके स्थानीय एनवायरनमेंट को प्रभावित करना असंभव हो जाता है।

इसके लिए, आपको अपना E2B अकाउंट सेटअप करने और अपने एनवायरनमेंट वेरिएबल्स में अपना `E2B_API_KEY` सेट करने की आवश्यकता होगी। अधिक जानकारी के लिए [E2B की क्विकस्टार्ट डॉक्यूमेंटेशन](https://e2b.dev/docs/quickstart) पर जाएं।

फिर आप इसे `pip install e2b-code-interpreter python-dotenv` के साथ इंस्टॉल कर सकते हैं।

अब आप तैयार हैं!

कोड एक्जीक्यूटर को E2B पर सेट करने के लिए, बस अपने `CodeAgent` को इनिशियलाइज़ करते समय `executor_type="e2b"` फ्लैग पास करें।
ध्यान दें कि आपको `additional_authorized_imports` में सभी टूल की डिपेंडेंसीज़ जोड़नी चाहिए, ताकि एक्जीक्यूटर उन्हें इंस्टॉल करे।

```py
from smolagents import CodeAgent, VisitWebpageTool, InferenceClientModel
agent = CodeAgent(
    tools = [VisitWebpageTool()],
    model=InferenceClientModel(),
    additional_authorized_imports=["requests", "markdownify"],
    executor_type="e2b"
)

agent.run("What was Abraham Lincoln's preferred pet?")
```

E2B कोड एक्जीक्यूशन वर्तमान में मल्टी-एजेंट्स के साथ काम नहीं करता है - क्योंकि कोड ब्लॉब में एक एजेंट कॉल करना जो रिमोटली एक्जीक्यूट किया जाना चाहिए, यह एक गड़बड़ है। लेकिन हम इसे जोड़ने पर काम कर रहे हैं!


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/tutorials/secure_code_execution.md" />

### Tools
https://huggingface.co/docs/smolagents/v1.22.0/hi/tutorials/tools.md

# Tools

<DocNotebookDropdown
  classNames="absolute z-10 right-0 top-0"
  options={[
    {label: "Mixed", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tools.ipynb"},
    {label: "PyTorch", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/tools.ipynb"},
    {label: "TensorFlow", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/tools.ipynb"},
    {label: "Mixed", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tools.ipynb"},
    {label: "PyTorch", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/tools.ipynb"},
    {label: "TensorFlow", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/tools.ipynb"},
]} />

यहाँ, हम एडवांस्ड tools उपयोग देखेंगे।

> [!TIP]
> यदि आप एजेंट्स बनाने में नए हैं, तो सबसे पहले [एजेंट्स का परिचय](../conceptual_guides/intro_agents) और [smolagents की गाइडेड टूर](../guided_tour) पढ़ना सुनिश्चित करें।

- [Tools](#tools)
    - [टूल क्या है, और इसे कैसे बनाएं?](#टूल-क्या-है-और-इसे-कैसे-बनाएं)
    - [अपना टूल हब पर शेयर करें](#अपना-टूल-हब-पर-शेयर-करें)
    - [स्पेस को टूल के रूप में इम्पोर्ट करें](#स्पेस-को-टूल-के-रूप-में-इम्पोर्ट-करें)
    - [LangChain टूल्स का उपयोग करें](#LangChain-टूल्स-का-उपयोग-करें)
    - [अपने एजेंट के टूलबॉक्स को मैनेज करें](#अपने-एजेंट-के-टूलबॉक्स-को-मैनेज-करें)
    - [टूल्स का कलेक्शन उपयोग करें](#टूल्स-का-कलेक्शन-उपयोग-करें)

### टूल क्या है और इसे कैसे बनाएं

टूल मुख्य रूप से एक फ़ंक्शन है जिसे एक LLM एजेंटिक सिस्टम में उपयोग कर सकता है।

लेकिन इसका उपयोग करने के लिए, LLM को एक API दी जाएगी: नाम, टूल विवरण, इनपुट प्रकार और विवरण, आउटपुट प्रकार।

इसलिए यह केवल एक फ़ंक्शन नहीं हो सकता। यह एक क्लास होनी चाहिए।

तो मूल रूप से, टूल एक क्लास है जो एक फ़ंक्शन को मेटाडेटा के साथ रैप करती है जो LLM को समझने में मदद करती है कि इसका उपयोग कैसे करें।

यह कैसा दिखता है:

```python
from smolagents import Tool

class HFModelDownloadsTool(Tool):
    name = "model_download_counter"
    description = """
    This is a tool that returns the most downloaded model of a given task on the Hugging Face Hub.
    It returns the name of the checkpoint."""
    inputs = {
        "task": {
            "type": "string",
            "description": "the task category (such as text-classification, depth-estimation, etc)",
        }
    }
    output_type = "string"

    def forward(self, task: str):
        from huggingface_hub import list_models

        model = next(iter(list_models(filter=task, sort="downloads", direction=-1)))
        return model.id

model_downloads_tool = HFModelDownloadsTool()
```

कस्टम टूल `Tool` को सबक्लास करता है उपयोगी मेथड्स को इनहेरिट करने के लिए। चाइल्ड क्लास भी परिभाषित करती है:
- एक `name` एट्रिब्यूट, जो टूल के नाम से संबंधित है। नाम आमतौर पर बताता है कि टूल क्या करता है। चूंकि कोड एक टास्क के लिए सबसे अधिक डाउनलोड वाले मॉडल को रिटर्न करता है, इसलिए इसे `model_download_counter` नाम दें।
- एक `description` एट्रिब्यूट एजेंट के सिस्टम प्रॉम्प्ट को पॉपुलेट करने के लिए उपयोग किया जाता है।
- एक `inputs` एट्रिब्यूट, जो `"type"` और `"description"` keys वाला डिक्शनरी है। इसमें जानकारी होती है जो पायथन इंटरप्रेटर को इनपुट के बारे में शिक्षित विकल्प चुनने में मदद करती है।
- एक `output_type` एट्रिब्यूट, जो आउटपुट टाइप को निर्दिष्ट करता है। `inputs` और `output_type` दोनों के लिए टाइप [Pydantic formats](https://docs.pydantic.dev/latest/concepts/json_schema/#generating-json-schema) होने चाहिए, वे इनमें से कोई भी हो सकते हैं: `~AUTHORIZED_TYPES()`।
- एक `forward` मेथड जिसमें एक्जीक्यूट किया जाने वाला इन्फरेंस कोड होता है।

एजेंट में उपयोग किए जाने के लिए इतना ही चाहिए!

टूल बनाने का एक और तरीका है। [guided_tour](../guided_tour) में, हमने `@tool` डेकोरेटर का उपयोग करके एक टूल को लागू किया। [tool()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.tool) डेकोरेटर सरल टूल्स को परिभाषित करने का अनुशंसित तरीका है, लेकिन कभी-कभी आपको इससे अधिक की आवश्यकता होती है: अधिक स्पष्टता के लिए एक क्लास में कई मेथड्स का उपयोग करना, या अतिरिक्त क्लास एट्रिब्यूट्स का उपयोग करना।

इस स्थिति में, आप ऊपर बताए अनुसार [Tool](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool) को सबक्लास करके अपना टूल बना सकते हैं।

### अपना टूल हब पर शेयर करें

आप टूल पर [push_to_hub()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool.push_to_hub) को कॉल करके अपना कस्टम टूल हब पर शेयर कर सकते हैं। सुनिश्चित करें कि आपने हब पर इसके लिए एक रिपॉजिटरी बनाई है और आप रीड एक्सेस वाला टोकन उपयोग कर रहे हैं।

```python
model_downloads_tool.push_to_hub("{your_username}/hf-model-downloads", token="<YOUR_HUGGINGFACEHUB_API_TOKEN>")
```

हब पर पुश करने के लिए काम करने के लिए, आपके टूल को कुछ नियमों का पालन करना होगा:
- सभी मेथड्स सेल्फ-कंटेन्ड हैं, यानी उनके आर्ग्स से आने वाले वेरिएबल्स का उपयोग करें।
- उपरोक्त बिंदु के अनुसार, **सभी इम्पोर्ट्स को सीधे टूल के फ़ंक्शंस के भीतर परिभाषित किया जाना चाहिए**, अन्यथा आपको अपने कस्टम टूल के साथ [save()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool.save) या [push_to_hub()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool.push_to_hub) को कॉल करने का प्रयास करते समय एरर मिलेगा।
- यदि आप `__init__` विधि को सबक्लास करते हैं, तो आप इसे `self` के अलावा कोई अन्य आर्ग्यूमेंट नहीं दे सकते। ऐसा इसलिए है क्योंकि किसी विशिष्ट टूल इंस्टेंस के इनिशियलाइजेशन के दौरान सेट किए गए तर्कों को आर्ग्यूमेंट्स करना कठिन होता है, जो उन्हें हब पर ठीक से साझा करने से रोकता है। और वैसे भी, एक विशिष्ट क्लास बनाने का विचार यह है कि आप हार्ड-कोड के लिए आवश्यक किसी भी चीज़ के लिए क्लास विशेषताएँ पहले से ही सेट कर सकते हैं (बस `your_variable=(...)` को सीधे `class YourTool(Tool):` पंक्ति के अंतर्गत सेट करें ). और निश्चित रूप से आप अभी भी `self.your_variable` को असाइन करके अपने कोड में कहीं भी एक क्लास विशेषता बना सकते हैं।


एक बार जब आपका टूल हब पर पुश हो जाता है, तो आप इसे विज़ुअलाइज़ कर सकते हैं। [यहाँ](https://huggingface.co/spaces/m-ric/hf-model-downloads) `model_downloads_tool` है जिसे मैंने पुश किया है। इसमें एक अच्छा ग्रेडियो इंटरफ़ेस है।

टूल फ़ाइलों में गहराई से जाने पर, आप पा सकते हैं कि सारी टूल लॉजिक [tool.py](https://huggingface.co/spaces/m-ric/hf-model-downloads/blob/main/tool.py) के अंतर्गत है। यहीं आप किसी और द्वारा शेयर किए गए टूल का निरीक्षण कर सकते हैं।

फिर आप टूल को [load_tool()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.load_tool) के साथ लोड कर सकते हैं या [from_hub()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool.from_hub) के साथ बना सकते हैं और इसे अपने एजेंट में `tools` पैरामीटर में पास कर सकते हैं।
चूंकि टूल्स को चलाने का मतलब कस्टम कोड चलाना है, आपको यह सुनिश्चित करना होगा कि आप रिपॉजिटरी पर भरोसा करते हैं, इसलिए हम हब से टूल लोड करने के लिए `trust_remote_code=True` पास करने की आवश्यकता रखते हैं।

```python
from smolagents import load_tool, CodeAgent

model_download_tool = load_tool(
    "{your_username}/hf-model-downloads",
    trust_remote_code=True
)
```

### स्पेस को टूल के रूप में इम्पोर्ट करें

आप [Tool.from_space()](/docs/smolagents/v1.22.0/hi/reference/tools#smolagents.Tool.from_space) मेथड का उपयोग करके हब से एक स्पेस को सीधे टूल के रूप में इम्पोर्ट कर सकते हैं!

आपको केवल हब पर स्पेस की ID, इसका नाम, और एक विवरण प्रदान करने की आवश्यकता है जो आपके एजेंट को समझने में मदद करेगा कि टूल क्या करता है। अंदर से, यह स्पेस को कॉल करने के लिए [`gradio-client`](https://pypi.org/project/gradio-client/) लाइब्रेरी का उपयोग करेगा।

उदाहरण के लिए, चलिए हब से [FLUX.1-dev](https://huggingface.co/black-forest-labs/FLUX.1-dev) स्पेस को इम्पोर्ट करें और इसका उपयोग एक इमेज जनरेट करने के लिए करें।

```python
image_generation_tool = Tool.from_space(
    "black-forest-labs/FLUX.1-schnell",
    name="image_generator",
    description="Generate an image from a prompt"
)

image_generation_tool("A sunny beach")
```
और देखो, यह तुम्हारी छवि है! 🏖️

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/sunny_beach.webp">

फिर आप इस टूल का उपयोग किसी अन्य टूल की तरह कर सकते हैं। उदाहरण के लिए, चलिए प्रॉम्प्ट `a rabbit wearing a space suit` को सुधारें और इसकी एक इमेज जनरेट करें। यह उदाहरण यह भी दिखाता है कि आप एजेंट को अतिरिक्त आर्ग्यूमेंट्स कैसे पास कर सकते हैं।

```python
from smolagents import CodeAgent, InferenceClientModel

model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")
agent = CodeAgent(tools=[image_generation_tool], model=model)

agent.run(
    "Improve this prompt, then generate an image of it.", additional_args={'user_prompt': 'A rabbit wearing a space suit'}
)
```

```text
=== Agent thoughts:
improved_prompt could be "A bright blue space suit wearing rabbit, on the surface of the moon, under a bright orange sunset, with the Earth visible in the background"

Now that I have improved the prompt, I can use the image generator tool to generate an image based on this prompt.
>>> Agent is executing the code below:
image = image_generator(prompt="A bright blue space suit wearing rabbit, on the surface of the moon, under a bright orange sunset, with the Earth visible in the background")
final_answer(image)
```

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/rabbit_spacesuit_flux.webp">

यह कितना कूल है? 🤩

### LangChain टूल्स का उपयोग करें

हम LangChain को पसंद करते हैं और मानते हैं कि इसके पास टूल्स का एक बहुत आकर्षक संग्रह है।
LangChain से एक टूल इम्पोर्ट करने के लिए, `from_langchain()` मेथड का उपयोग करें।

यहाँ बताया गया है कि आप LangChain वेब सर्च टूल का उपयोग करके परिचय के सर्च रिजल्ट को कैसे फिर से बना सकते हैं।
इस टूल को काम करने के लिए `pip install langchain google-search-results -q` की आवश्यकता होगी।
```python
from langchain.agents import load_tools

search_tool = Tool.from_langchain(load_tools(["serpapi"])[0])

agent = CodeAgent(tools=[search_tool], model=model)

agent.run("How many more blocks (also denoted as layers) are in BERT base encoder compared to the encoder from the architecture proposed in Attention is All You Need?")
```

### अपने एजेंट के टूलबॉक्स को मैनेज करें

आप एजेंट के टूलबॉक्स को `agent.tools` एट्रिब्यूट में एक टूल जोड़कर या बदलकर मैनेज कर सकते हैं, क्योंकि यह एक स्टैंडर्ड डिक्शनरी है।

चलिए केवल डिफ़ॉल्ट टूलबॉक्स के साथ इनिशियलाइज़ किए गए मौजूदा एजेंट में `model_download_tool` जोड़ें।

```python
from smolagents import InferenceClientModel

model = InferenceClientModel(model_id="Qwen/Qwen2.5-Coder-32B-Instruct")

agent = CodeAgent(tools=[], model=model, add_base_tools=True)
agent.tools[model_download_tool.name] = model_download_tool
```
अब हम नए टूल का लाभ उठा सकते हैं।

```python
agent.run(
    "Can you give me the name of the model that has the most downloads in the 'text-to-video' task on the Hugging Face Hub but reverse the letters?"
)
```


> [!TIP]
> एजेंट में बहुत अधिक टूल्स न जोड़ने से सावधान रहें: यह कमजोर LLM इंजन को ओवरव्हेल्म कर सकता है।


### टूल्स का कलेक्शन उपयोग करें

आप `ToolCollection` ऑब्जेक्ट का उपयोग करके टूल कलेक्शंस का लाभ उठा सकते हैं। यह या तो हब से एक कलेक्शन या MCP सर्वर टूल्स को लोड करने का समर्थन करता है।

#### हब में कलेक्शन से टूल कलेक्शन

आप उस कलेक्शन के स्लग के साथ इसका लाभ उठा सकते हैं जिसका आप उपयोग करना चाहते हैं।
फिर उन्हें अपने एजेंट को इनिशियलाइज़ करने के लिए एक लिस्ट के रूप में पास करें, और उनका उपयोग शुरू करें!

```py
from smolagents import ToolCollection, CodeAgent

image_tool_collection = ToolCollection.from_hub(
    collection_slug="huggingface-tools/diffusion-tools-6630bb19a942c2306a2cdb6f",
    token="<YOUR_HUGGINGFACEHUB_API_TOKEN>"
)
agent = CodeAgent(tools=[*image_tool_collection.tools], model=model, add_base_tools=True)

agent.run("Please draw me a picture of rivers and lakes.")
```

स्टार्ट को तेज करने के लिए, टूल्स केवल तभी लोड होते हैं जब एजेंट द्वारा कॉल किए जाते हैं।

#### किसी भी MCP सर्वर से टूल कलेक्शन

[glama.ai](https://glama.ai/mcp/servers) या [smithery.ai](https://smithery.ai/) पर उपलब्ध सैकड़ों MCP सर्वर्स से टूल्स का लाभ उठाएं।

MCP सर्वर्स टूल्स को निम्नानुसार `ToolCollection` ऑब्जेक्ट में लोड किया जा सकता है:

```py
from smolagents import ToolCollection, CodeAgent
from mcp import StdioServerParameters

server_parameters = StdioServerParameters(
    command="uv",
    args=["--quiet", "pubmedmcp@0.1.3"],
    env={"UV_PYTHON": "3.12", **os.environ},
)

with ToolCollection.from_mcp(server_parameters, trust_remote_code=True) as tool_collection:
    agent = CodeAgent(tools=[*tool_collection.tools], add_base_tools=True)
    agent.run("Please find a remedy for hangover.")
```

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/tutorials/tools.md" />

### अच्छे Agents का निर्माण
https://huggingface.co/docs/smolagents/v1.22.0/hi/tutorials/building_good_agents.md

# अच्छे Agents का निर्माण

<DocNotebookDropdown
  classNames="absolute z-10 right-0 top-0"
  options={[
    {label: "Mixed", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/building_good_agents.ipynb"},
    {label: "PyTorch", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/building_good_agents.ipynb"},
    {label: "TensorFlow", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/building_good_agents.ipynb"},
    {label: "Mixed", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/building_good_agents.ipynb"},
    {label: "PyTorch", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/building_good_agents.ipynb"},
    {label: "TensorFlow", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/building_good_agents.ipynb"},
]} />

एक ऐसा एजेंट बनाने में जो काम करता है और जो काम नहीं करता है, इसमें ज़मीन-आसमान का अंतर है।
हम कैसे ऐसे एजेंट्स बना सकते हैं जो बाद वाली श्रेणी में आते हैं?
इस गाइड में, हम एजेंट्स बनाने के लिए सर्वोत्तम प्रक्रियाएँ के बारे में बात करेंगे।

> [!TIP]
> यदि आप एजेंट्स बनाने में नए हैं, तो पहले [एजेंट्स का परिचय](../conceptual_guides/intro_agents) और [smolagents की गाइडेड टूर](../guided_tour) पढ़ना सुनिश्चित करें।

### सर्वश्रेष्ठ एजेंटिक सिस्टम सबसे सरल होते हैं: वर्कफ़्लो को जितना हो सके उतना सरल बनाएं

अपने वर्कफ़्लो में एक LLM को कुछ एजेंसी देने से त्रुटियों का जोखिम होता है।

अच्छी तरह से प्रोग्राम किए गए एजेंटिक सिस्टम में वैसे भी अच्छी एरर लॉगिंग और रीट्राई मैकेनिज्म होते हैं, जिससे LLM इंजन अपनी गलतियों को सुधारने का मौका मिलता है। लेकिन LLM त्रुटि के जोखिम को अधिकतम कम करने के लिए, आपको अपना वर्कफ़्लो सरल बनाना चाहिए!

आइए [एजेंट्स का परिचय](../conceptual_guides/intro_agents) से उदाहरण पर फिर से विचार करें: एक सर्फ ट्रिप कंपनी के लिए उपयोगकर्ता प्रश्नों का उत्तर देने वाला बॉट।
एजेंट को हर बार जब एक नए सर्फ स्पॉट के बारे में पूछा जाता है तो "travel distance API" और "weather API" के लिए 2 अलग-अलग कॉल करने देने के बजाय, आप केवल एक एकीकृत टूल "return_spot_information" बना सकते हैं, एक फंक्शन जो दोनों APIs को एक साथ कॉल करता है और उनके संयोजित आउटपुट को उपयोगकर्ता को वापस करता है।

यह लागत, देरी और त्रुटि जोखिम को कम करेगा!

मुख्य दिशानिर्देश है: LLM कॉल्स की संख्या को जितना हो सके उतना कम करें।

इससे कुछ निष्कर्ष निकलते हैं:
- जब भी संभव हो, दो APIs के हमारे उदाहरण की तरह 2 टूल्स को एक में समूहित करें।
- जब भी संभव हो, लॉजिक एजेंटिक निर्णयों के बजाय डिटरमिनिस्टिक फंक्शंस पर आधारित होनी चाहिए।

### LLM इंजन को जानकारी के प्रवाह में सुधार करें

याद रखें कि आपका LLM इंजन एक *बुद्धिमान* रोबोट की तरह है, जो एक कमरे में बंद है, और बाहरी दुनिया के साथ इसका एकमात्र संचार दरवाजे के नीचे से नोट्स पास करना है।

यह किसी भी ऐसी चीज के बारे में नहीं जानेगा जिसे आप स्पष्ट रूप से अपने प्रॉम्प्ट में नहीं डालते हैं।

इसलिए पहले अपने कार्य को बहुत स्पष्ट बनाने से शुरू करें!
चूंकि एक एजेंट LLM द्वारा संचालित होता है, आपके कार्य के निर्माण में छोटे बदलाव भी पूरी तरह से अलग परिणाम दे सकते हैं।

फिर, टूल के उपयोग में अपने एजेंट की ओर जानकारी के प्रवाह में सुधार करें।

पालन करने के लिए विशेष दिशानिर्देश:
- प्रत्येक टूल को वह सब कुछ लॉग करना चाहिए (टूल की `forward` मेथड के अंदर केवल `print` स्टेटमेंट्स का उपयोग करके) जो LLM इंजन के लिए उपयोगी हो सकता है।
  - विशेष रूप से, टूल एक्जीक्यूशन गलतियों पर विस्तृत लॉगिंग बहुत मदद करेगी!

उदाहरण के लिए, यहाँ एक टूल है जो लोकेशन और डेट-टाइम के आधार पर मौसम डेटा प्राप्त करता है:

पहले, यहाँ एक खराब रूप है:
```python
import datetime
from smolagents import tool

def get_weather_report_at_coordinates(coordinates, date_time):
    # Dummy function, returns a list of [temperature in °C, risk of rain on a scale 0-1, wave height in m]
    return [28.0, 0.35, 0.85]

def convert_location_to_coordinates(location):
    # Returns dummy coordinates
    return [3.3, -42.0]

@tool
def get_weather_api(location: str, date_time: str) -> str:
    """
    Returns the weather report.

    Args:
        location: the name of the place that you want the weather for.
        date_time: the date and time for which you want the report.
    """
    lon, lat = convert_location_to_coordinates(location)
    date_time = datetime.strptime(date_time)
    return str(get_weather_report_at_coordinates((lon, lat), date_time))
```

# यह खराब क्यों है?
- `date_time` के लिए उपयोग किए जाने वाले फॉर्मेट की सटीकता का कोई उल्लेख नहीं है।  
- यह स्पष्ट नहीं है कि स्थान (location) को किस प्रकार निर्दिष्ट किया जाना चाहिए।  
- त्रुटियों को स्पष्ट रूप से इंगित करने के लिए कोई लॉगिंग मेकैनिज्म मौजूद नहीं है, जैसे कि स्थान गलत फॉर्मेट में होना या `date_time` का सही ढंग से फॉर्मेट न होना।  
- आउटपुट फॉर्मेट समझने में कठिन है।  

यदि टूल कॉल विफल हो जाती है, तो मेमोरी में लॉग की गई एरर ट्रेस LLM को टूल की समस्याओं को ठीक करने के लिए रिवर्स इंजीनियरिंग में मदद कर सकती है। लेकिन इतना सारा काम LLM को ही क्यों करने देना?

इस टूल को बेहतर तरीके से बनाने का एक उदाहरण इस प्रकार हो सकता है:

```python
@tool
def get_weather_api(location: str, date_time: str) -> str:
    """
    Returns the weather report.

    Args:
        location: the name of the place that you want the weather for. Should be a place name, followed by possibly a city name, then a country, like "Anchor Point, Taghazout, Morocco".
        date_time: the date and time for which you want the report, formatted as '%m/%d/%y %H:%M:%S'.
    """
    lon, lat = convert_location_to_coordinates(location)
    try:
        date_time = datetime.strptime(date_time)
    except Exception as e:
        raise ValueError("Conversion of `date_time` to datetime format failed, make sure to provide a string in format '%m/%d/%y %H:%M:%S'. Full trace:" + str(e))
    temperature_celsius, risk_of_rain, wave_height = get_weather_report_at_coordinates((lon, lat), date_time)
    return f"Weather report for {location}, {date_time}: Temperature will be {temperature_celsius}°C, risk of rain is {risk_of_rain*100:.0f}%, wave height is {wave_height}m."
```

सामान्य तौर पर, अपने LLM का बोझ को कम करने के लिए, खुद से यह अच्छा सवाल पूछें: "यदि मैं नया और अनुभवहीन हूं और इस टूल का पहली बार उपयोग कर रहा हूं, तो इस टूल के साथ प्रोग्रामिंग करना और अपनी गलतियों को ठीक करना मेरे लिए कितना आसान होगा?"

### एजेंट को अधिक तर्क (arguments) दें

अपने एजेंट को कार्य का वर्णन करने वाले साधारण स्ट्रिंग से आगे बढ़कर कुछ अतिरिक्त ऑब्जेक्ट्स देने के लिए, आप `additional_args` का उपयोग कर सकते हैं। यह आपको किसी भी प्रकार का ऑब्जेक्ट पास करने की सुविधा देता है:


```py
from smolagents import CodeAgent, InferenceClientModel

model_id = "meta-llama/Llama-3.3-70B-Instruct"

agent = CodeAgent(tools=[], model=InferenceClientModel(model_id=model_id), add_base_tools=True)

agent.run(
    "Why does Mike not know many people in New York?",
    additional_args={"mp3_sound_file_url":'https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/recording.mp3'}
)
```
उदाहरण के लिए, आप इस `additional_args` आर्ग्यूमेंट का उपयोग उन इमेजेज़ या स्ट्रिंग्स को पास करने के लिए कर सकते हैं जिन्हें आप चाहते हैं कि आपका एजेंट उपयोग करे।



## अपने एजेंट को डिबग कैसे करें

### 1. एक अधिक शक्तिशाली LLM का उपयोग करें

एजेंटिक वर्कफ़्लो में, कुछ त्रुटियां वास्तविक होती हैं, जबकि कुछ अन्य त्रुटियां आपके LLM इंजन के सही तरीके से तर्क न कर पाने की वजह से होती हैं।  
उदाहरण के लिए, इस ट्रेस को देखें, जहां मैंने एक `CodeAgent` से एक कार की तस्वीर बनाने के लिए कहा:
```
==================================================================================================== New task ====================================================================================================
Make me a cool car picture
──────────────────────────────────────────────────────────────────────────────────────────────────── New step ────────────────────────────────────────────────────────────────────────────────────────────────────
Agent is executing the code below: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
image_generator(prompt="A cool, futuristic sports car with LED headlights, aerodynamic design, and vibrant color, high-res, photorealistic")
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────

Last output from code snippet: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png
Step 1:

- Time taken: 16.35 seconds
- Input tokens: 1,383
- Output tokens: 77
──────────────────────────────────────────────────────────────────────────────────────────────────── New step ────────────────────────────────────────────────────────────────────────────────────────────────────
Agent is executing the code below: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
final_answer("/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png")
──────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
Print outputs:

Last output from code snippet: ───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png
Final answer:
/var/folders/6m/9b1tts6d5w960j80wbw9tx3m0000gn/T/tmpx09qfsdd/652f0007-3ee9-44e2-94ac-90dae6bb89a4.png
```
उपयोगकर्ता को, एक इमेज लौटाए जाने के बजाय, उन्हें एक पाथ लौटाया जाता है।
यह सिस्टम से एक बग की तरह दिख सकता है, लेकिन वास्तव में एजेंटिक सिस्टम ने त्रुटि नहीं की: यह केवल इसलिए है कि LLM ब्रेन ने इमेज आउटपुट को एक वेरिएबल में सेव करने की गलती की।
इस प्रकार यह इमेज को फिर से एक्सेस नहीं कर सकता है सिवाय इमेज को सेव करते समय लॉग किए गए पाथ का उपयोग करके, इसलिए यह इमेज के बजाय पाथ लौटाता है।

अपने एजेंट को डीबग करने का पहला कदम इस प्रकार है "एक अधिक शक्तिशाली LLM का उपयोग करें"। `Qwen2/5-72B-Instruct` जैसे विकल्प वह गलती नहीं करते।

### 2. अधिक मार्गदर्शन / अधिक जानकारी प्रदान करें

आप कम शक्तिशाली मॉडल्स का भी उपयोग कर सकते हैं, बशर्ते आप उन्हें अधिक प्रभावी ढंग से मार्गदर्शन करें।

अपने आप को अपने मॉडल की जगह रखें: यदि आप कार्य को हल करने वाला मॉडल होते, तो क्या आप उपलब्ध जानकारी (सिस्टम प्रॉम्प्ट + कार्य निर्माण + टूल विवरण से) के साथ संघर्ष करते?

क्या आपको कुछ अतिरिक्त स्पष्टीकरण की आवश्यकता होती?

अतिरिक्त जानकारी प्रदान करने के लिए, हम तुरंत सिस्टम प्रॉम्प्ट को बदलने की सलाह नहीं देते हैं: डिफ़ॉल्ट सिस्टम प्रॉम्प्ट में कई समायोजन हैं जिन्हें आप तब तक नहीं बिगाड़ना चाहते जब तक आप प्रॉम्प्ट को बहुत अच्छी तरह से नहीं समझते।
अपने LLM इंजन को मार्गदर्शन करने के बेहतर तरीके हैं:
- यदि यह कार्य को हल करने के बारे में है: इन सभी विवरणों को कार्य में जोड़ें। यह कार्य 100 पेज लंबा हो सकता है
- यदि यह टूल्स के उपयोग के बारे में है: आपके टूल्स की विवरण विशेषता।

### 3. सिस्टम प्रॉम्प्ट बदलें (आमतौर पर यह सलाह नहीं दी जाती)

यदि उपरोक्त स्पष्टीकरण पर्याप्त नहीं हैं, तो आप सिस्टम प्रॉम्प्ट बदल सकते हैं।

आइए देखें कि यह कैसे काम करता है। उदाहरण के लिए, आइए [CodeAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.CodeAgent) के लिए डिफ़ॉल्ट सिस्टम प्रॉम्प्ट की जाँच करें (नीचे दिया गया वर्जन जीरो-शॉट उदाहरणों को छोड़कर छोटा किया गया है)।

```python
print(agent.prompt_templates["system_prompt"])
```
Here is what you get:
```text
You are an expert assistant who can solve any task using code blobs. You will be given a task to solve as best you can.
To do so, you have been given access to a list of tools: these tools are basically Python functions which you can call with code.
To solve the task, you must plan forward to proceed in a series of steps, in a cycle of 'Thought:', 'Code:', and 'Observation:' sequences.

At each step, in the 'Thought:' sequence, you should first explain your reasoning towards solving the task and the tools that you want to use.
Then in the 'Code:' sequence, you should write the code in simple Python. The code sequence must end with '<end_code>' sequence.
During each intermediate step, you can use 'print()' to save whatever important information you will then need.
These print outputs will then appear in the 'Observation:' field, which will be available as input for the next step.
In the end you have to return a final answer using the `final_answer` tool.

Here are a few examples using notional tools:
---
Task: "Generate an image of the oldest person in this document."

Thought: I will proceed step by step and use the following tools: `document_qa` to find the oldest person in the document, then `image_generator` to generate an image according to the answer.
Code:
```py
answer = document_qa(document=document, question="Who is the oldest person mentioned?")
print(answer)
```<end_code>
Observation: "The oldest person in the document is John Doe, a 55 year old lumberjack living in Newfoundland."

Thought: I will now generate an image showcasing the oldest person.
Code:
```py
image = image_generator("A portrait of John Doe, a 55-year-old man living in Canada.")
final_answer(image)
```<end_code>

---
Task: "What is the result of the following operation: 5 + 3 + 1294.678?"

Thought: I will use python code to compute the result of the operation and then return the final answer using the `final_answer` tool
Code:
```py
result = 5 + 3 + 1294.678
final_answer(result)
```<end_code>

---
Task:
"Answer the question in the variable `question` about the image stored in the variable `image`. The question is in French.
You have been provided with these additional arguments, that you can access using the keys as variables in your python code:
{'question': 'Quel est l'animal sur l'image?', 'image': 'path/to/image.jpg'}"

Thought: I will use the following tools: `translator` to translate the question into English and then `image_qa` to answer the question on the input image.
Code:
```py
translated_question = translator(question=question, src_lang="French", tgt_lang="English")
print(f"The translated question is {translated_question}.")
answer = image_qa(image=image, question=translated_question)
final_answer(f"The answer is {answer}")
```<end_code>

---
Task:
In a 1979 interview, Stanislaus Ulam discusses with Martin Sherwin about other great physicists of his time, including Oppenheimer.
What does he say was the consequence of Einstein learning too much math on his creativity, in one word?

Thought: I need to find and read the 1979 interview of Stanislaus Ulam with Martin Sherwin.
Code:
```py
pages = search(query="1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein")
print(pages)
```<end_code>
Observation:
No result found for query "1979 interview Stanislaus Ulam Martin Sherwin physicists Einstein".

Thought: The query was maybe too restrictive and did not find any results. Let's try again with a broader query.
Code:
```py
pages = search(query="1979 interview Stanislaus Ulam")
print(pages)
```<end_code>
Observation:
Found 6 pages:
[Stanislaus Ulam 1979 interview](https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/)

[Ulam discusses Manhattan Project](https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/)

(truncated)

Thought: I will read the first 2 pages to know more.
Code:
```py
for url in ["https://ahf.nuclearmuseum.org/voices/oral-histories/stanislaus-ulams-interview-1979/", "https://ahf.nuclearmuseum.org/manhattan-project/ulam-manhattan-project/"]:
    whole_page = visit_webpage(url)
    print(whole_page)
    print("\n" + "="*80 + "\n")  # Print separator between pages
```<end_code>
Observation:
Manhattan Project Locations:
Los Alamos, NM
Stanislaus Ulam was a Polish-American mathematician. He worked on the Manhattan Project at Los Alamos and later helped design the hydrogen bomb. In this interview, he discusses his work at
(truncated)

Thought: I now have the final answer: from the webpages visited, Stanislaus Ulam says of Einstein: "He learned too much mathematics and sort of diminished, it seems to me personally, it seems to me his purely physics creativity." Let's answer in one word.
Code:
```py
final_answer("diminished")
```<end_code>

---
Task: "Which city has the highest population: Guangzhou or Shanghai?"

Thought: I need to get the populations for both cities and compare them: I will use the tool `search` to get the population of both cities.
Code:
```py
for city in ["Guangzhou", "Shanghai"]:
    print(f"Population {city}:", search(f"{city} population")
```<end_code>
Observation:
Population Guangzhou: ['Guangzhou has a population of 15 million inhabitants as of 2021.']
Population Shanghai: '26 million (2019)'

Thought: Now I know that Shanghai has the highest population.
Code:
```py
final_answer("Shanghai")
```<end_code>

---
Task: "What is the current age of the pope, raised to the power 0.36?"

Thought: I will use the tool `wiki` to get the age of the pope, and confirm that with a web search.
Code:
```py
pope_age_wiki = wiki(query="current pope age")
print("Pope age as per wikipedia:", pope_age_wiki)
pope_age_search = web_search(query="current pope age")
print("Pope age as per google search:", pope_age_search)
```<end_code>
Observation:
Pope age: "The pope Francis is currently 88 years old."

Thought: I know that the pope is 88 years old. Let's compute the result using python code.
Code:
```py
pope_current_age = 88 ** 0.36
final_answer(pope_current_age)
```<end_code>

Above example were using notional tools that might not exist for you. On top of performing computations in the Python code snippets that you create, you only have access to these tools:
{%- for tool in tools.values() %}
- {{ tool.to_tool_calling_prompt() }}
{%- endfor %}

{%- if managed_agents and managed_agents.values() | list %}
You can also give tasks to team members.
Calling a team member works similarly to calling a tool: provide the task description as the 'task' argument. Since this team member is a real human, be as detailed and verbose as necessary in your task description.
You can also include any relevant variables or context using the 'additional_args' argument.
Here is a list of the team members that you can call:
{%- for agent in managed_agents.values() %}
- {{ agent.name }}: {{ agent.description }}
{%- endfor %}
{%- endif %}

Here are the rules you should always follow to solve your task:
1. Always provide a 'Thought:' sequence, and a 'Code:\n```py' sequence ending with '```<end_code>' sequence, else you will fail.
2. Use only variables that you have defined!
3. Always use the right arguments for the tools. DO NOT pass the arguments as a dict as in 'answer = wiki({'query': "What is the place where James Bond lives?"})', but use the arguments directly as in 'answer = wiki(query="What is the place where James Bond lives?")'.
4. Take care to not chain too many sequential tool calls in the same code block, especially when the output format is unpredictable. For instance, a call to search has an unpredictable return format, so do not have another tool call that depends on its output in the same block: rather output results with print() to use them in the next block.
5. Call a tool only when needed, and never re-do a tool call that you previously did with the exact same parameters.
6. Don't name any new variable with the same name as a tool: for instance don't name a variable 'final_answer'.
7. Never create any notional variables in our code, as having these in your logs will derail you from the true variables.
8. You can use imports in your code, but only from the following list of modules: {{authorized_imports}}
9. The state persists between code executions: so if in one step you've created variables or imported modules, these will all persist.
10. Don't give up! You're in charge of solving the task, not providing directions to solve it.

Now Begin! If you solve the task correctly, you will receive a reward of $1,000,000.
```

जैसा कि आप देख सकते हैं, `"{{ tool.description }}"` जैसे प्लेसहोल्डर्स हैं: इनका उपयोग एजेंट इनिशियलाइजेशन के समय टूल्स या मैनेज्ड एजेंट्स के कुछ स्वचालित रूप से जनरेट किए गए विवरणों को डालने के लिए किया जाएगा।

इसलिए जबकि आप `system_prompt` पैरामीटर में अपने कस्टम प्रॉम्प्ट को आर्गुमेंट के रूप में पास करके इस सिस्टम प्रॉम्प्ट टेम्पलेट को ओवरराइट कर सकते हैं, आपके नए सिस्टम प्रॉम्प्ट में निम्नलिखित प्लेसहोल्डर्स होने चाहिए:
- टूल विवरण डालने के लिए।
  ```
  {%- for tool in tools.values() %}
  - {{ tool.to_tool_calling_prompt() }}
  {%- endfor %}
  ```
- यदि कोई मैनेज्ड एजेंट्स हैं तो उनके लिए विवरण डालने के लिए।
  ```
  {%- if managed_agents and managed_agents.values() | list %}
  You can also give tasks to team members.
  Calling a team member works similarly to calling a tool: provide the task description as the 'task' argument. Since this team member is a real human, be as detailed and verbose as necessary in your task description.
  You can also include any relevant variables or context using the 'additional_args' argument.
  Here is a list of the team members that you can call:
  {%- for agent in managed_agents.values() %}
  - {{ agent.name }}: {{ agent.description }}
  {%- endfor %}
  {%- endif %}
  ```
- केवल `CodeAgent` के लिए: अधिकृत इम्पोर्ट्स की सूची डालने के लिए `"{{authorized_imports}}"`।

फिर आप सिस्टम प्रॉम्प्ट को निम्नानुसार बदल सकते हैं:

```py
agent.prompt_templates["system_prompt"] = agent.prompt_templates["system_prompt"] + "\nHere you go!"
```

This also works with the [ToolCallingAgent](/docs/smolagents/v1.22.0/hi/reference/agents#smolagents.ToolCallingAgent).


### 4. अतिरिक्त योजना

हम पूरक योजना चरण के लिए एक मॉडल प्रदान करते हैं, जिसे एजेंट सामान्य क्रियाओं के चरणों के बीच नियमित रूप से चला सकता है। इस चरण में कोई टूल कॉल नहीं होती है, LLM से केवल उन तथ्यों की सूची को अपडेट करने के लिए कहा जाता है जो उसे ज्ञात हैं और इन तथ्यों के आधार पर उसे अगले कदमों के बारे में विचार करना होता है।

```py
from smolagents import load_tool, CodeAgent, InferenceClientModel, WebSearchTool
from dotenv import load_dotenv

load_dotenv()

# Import tool from Hub
image_generation_tool = load_tool("m-ric/text-to-image", trust_remote_code=True)

search_tool = WebSearchTool()

agent = CodeAgent(
    tools=[search_tool],
    model=InferenceClientModel(model_id="Qwen/Qwen2.5-72B-Instruct"),
    planning_interval=3 # This is where you activate planning!
)

# Run it!
result = agent.run(
    "How long would a cheetah at full speed take to run the length of Pont Alexandre III?",
)
```


<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/tutorials/building_good_agents.md" />

### OpenTelemetry के साथ runs का निरीक्षण
https://huggingface.co/docs/smolagents/v1.22.0/hi/tutorials/inspect_runs.md

# OpenTelemetry के साथ runs का निरीक्षण

<DocNotebookDropdown
  classNames="absolute z-10 right-0 top-0"
  options={[
    {label: "Mixed", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/inspect_runs.ipynb"},
    {label: "PyTorch", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/inspect_runs.ipynb"},
    {label: "TensorFlow", value: "https://colab.research.google.com/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/inspect_runs.ipynb"},
    {label: "Mixed", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/inspect_runs.ipynb"},
    {label: "PyTorch", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/pytorch/inspect_runs.ipynb"},
    {label: "TensorFlow", value: "https://studiolab.sagemaker.aws/import/github/huggingface/notebooks/blob/main/smolagents_doc/hi/tensorflow/inspect_runs.ipynb"},
]} />

> [!TIP]
> यदि आप एजेंट्स बनाने में नए हैं, तो पहले [एजेंट्स का परिचय](../conceptual_guides/intro_agents) और [smolagents की गाइडेड टूर](../guided_tour) पढ़ना सुनिश्चित करें।

### Agents runs को लॉग क्यों करें?

Agent runs को डीबग करना जटिल होता है।

यह सत्यापित करना कठिन है कि एक रन ठीक से चला या नहीं, क्योंकि एजेंट वर्कफ़्लो [डिज़ाइन के अनुसार अप्रत्याशित](../conceptual_guides/intro_agents) होते हैं (यदि वे प्रत्याशित होते, तो आप पुराने अच्छे कोड का ही उपयोग कर रहे होते)।

और रन का निरीक्षण करना भी कठिन है: मल्टी-स्टेप एजेंट्स जल्दी ही कंसोल को लॉग से भर देते हैं, और अधिकांश त्रुटियां केवल "LLM dumb" प्रकार की त्रुटियां होती हैं, जिनसे LLM अगले चरण में बेहतर कोड या टूल कॉल लिखकर स्वयं को सुधार लेता है।

इसलिए बाद के निरीक्षण और मॉनिटरिंग के लिए प्रोडक्शन में agent runs को रिकॉर्ड करने के लिए इंस्ट्रुमेंटेशन का उपयोग करना आवश्यक है!

हमने agent runs को इंस्ट्रुमेंट करने के लिए [OpenTelemetry](https://opentelemetry.io/) मानक को अपनाया है।

इसका मतलब है कि आप बस कुछ इंस्ट्रुमेंटेशन कोड चला सकते हैं, फिर अपने एजेंट्स को सामान्य रूप से चला सकते हैं, और सब कुछ आपके प्लेटफॉर्म में लॉग हो जाता है।

यह इस प्रकार होता है:
पहले आवश्यक पैकेज इंस्टॉल करें। यहां हम [Phoenix by Arize AI](https://github.com/Arize-ai/phoenix) इंस्टॉल करते हैं क्योंकि यह लॉग्स को एकत्र और निरीक्षण करने का एक अच्छा समाधान है, लेकिन इस संग्रह और निरीक्षण भाग के लिए आप अन्य OpenTelemetry-कम्पैटिबल प्लेटफॉर्म्स का उपयोग कर सकते हैं।

```shell
pip install smolagents
pip install arize-phoenix opentelemetry-sdk opentelemetry-exporter-otlp openinference-instrumentation-smolagents
```

फिर कलेक्टर को बैकग्राउंड में चलाएं।

```shell
python -m phoenix.server.main serve
```

अंत में, अपने एजेंट्स को ट्रेस करने और ट्रेस को नीचे परिभाषित एंडपॉइंट पर Phoenix को भेजने के लिए `SmolagentsInstrumentor` को सेट करें।

```python
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

from openinference.instrumentation.smolagents import SmolagentsInstrumentor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import ConsoleSpanExporter, SimpleSpanProcessor

endpoint = "http://0.0.0.0:6006/v1/traces"
trace_provider = TracerProvider()
trace_provider.add_span_processor(SimpleSpanProcessor(OTLPSpanExporter(endpoint)))

SmolagentsInstrumentor().instrument(tracer_provider=trace_provider)
```
तब आप अपने एजेंट चला सकते हैं!

```py
from smolagents import (
    CodeAgent,
    ToolCallingAgent,
    WebSearchTool,
    VisitWebpageTool,
    InferenceClientModel,
)

model = InferenceClientModel()

managed_agent = ToolCallingAgent(
    tools=[WebSearchTool(), VisitWebpageTool()],
    model=model,
    name="managed_agent",
    description="This is an agent that can do web search.",
)

manager_agent = CodeAgent(
    tools=[],
    model=model,
    managed_agents=[managed_agent],
)
manager_agent.run(
    "If the US keeps its 2024 growth rate, how many years will it take for the GDP to double?"
)
```
और फिर आप अपने रन का निरीक्षण करने के लिए `http://0.0.0.0:6006/projects/` पर जा सकते हैं!

<img src="https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/smolagents/inspect_run_phoenix.png">

आप देख सकते हैं कि CodeAgent ने अपने मैनेज्ड ToolCallingAgent को (वैसे, मैनेज्ड एजेंट एक CodeAgent भी हो सकता था) U.S. 2024 ग्रोथ रेट के लिए वेब सर्च चलाने के लिए कॉल किया। फिर मैनेज्ड एजेंट ने अपनी रिपोर्ट लौटाई और मैनेजर एजेंट ने अर्थव्यवस्था के दोगुना होने का समय गणना करने के लिए उस पर कार्य किया! अच्छा है, है ना?

<EditOnGithub source="https://github.com/huggingface/smolagents/blob/main/docs/source/hi/tutorials/inspect_runs.md" />
