मुख्य सामग्री पर जाएं

OpenAI Agents SDK ट्यूटोरियल: ऐसे AI सिस्टम बनाना जो कार्रवाई करते हैं

OpenAI के Agents SDK के साथ बुद्धिमान AI एप्लिकेशन बनाना सीखें। यह व्यापक गाइड एजेंट बनाना, टूल्स लागू करना, संरचित आउटपुट और एकाधिक एजेंट्स का समन्वय कवर करता है।
अपडेट किया गया 24 सित॰ 2026  · 12 मि॰ पढ़ें

AI के साथ खोजें

ChatGPTClaudePerplexity

कृत्रिम बुद्धिमत्ता का क्षेत्र केवल प्रश्नों का उत्तर देने वाली प्रणालियों से बदलकर उन प्रणालियों की ओर बढ़ रहा है जो स्वयं कार्रवाई कर सकती हैं। OpenAI का नया Agents SDK इस प्रवृत्ति के अग्रिम पंक्ति में है, जो डेवलपर्स को ऐसे AI एप्लिकेशन बनाने के लिए एक व्यावहारिक ढांचा देता है जो स्वयं निर्णय लेते हैं और कार्रवाई करते हैं। यह टूलकिट AI विकास के अगले चरण का प्रतिनिधित्व करता है, जहाँ सिस्टम केवल सवालों के जवाब नहीं देते, बल्कि सक्रिय रूप से समस्याएँ हल करते हैं।

Agents SDK बड़े भाषा मॉडलों को टूल उपयोग और विशिष्टीकृत एजेंट्स के बीच समन्वय करने की क्षमता के साथ जोड़ता है। यह Python के साथ बनाया गया है और सरलता तथा शक्ति के बीच संतुलन प्रदान करता है — सिर्फ कुछ कोर कॉन्सेप्ट्स जैसे एजेंट्स, टूल्स, हैंडऑफ्स और गार्डरेइल्स का उपयोग करते हुए। यह तरीका उन डेवलपर्स के लिए इसे सुलभ बनाता है जो एजेंट व्यवहार की जटिल अंतर्निहित यांत्रिकी को प्रबंधित किए बिना परिष्कृत AI सिस्टम बनाना चाहते हैं।

इस ट्यूटोरियल में, हम OpenAI Agents SDK के साथ व्यावहारिक एप्लिकेशन बनाना सीखेंगे। बेसिक एजेंट निर्माण से शुरू करते हुए, हम टूल्स लागू करने, एकाधिक एजेंट्स का समन्वय करने और गार्डरेइल्स के माध्यम से सुरक्षा सुनिश्चित करने तक बढ़ेंगे। यह ज्ञान आपको ऐसे AI सिस्टम विकसित करने में सक्षम बनाएगा जो विभिन्न कार्यों को संभाल सकें और वर्तमान AI विकास दृष्टिकोणों से संबंधित कौशल प्रदान करेगा।

यदि आप OpenAI के साथ काम करने में नए हैं, तो हमारी OpenAI Fundamentals स्किल ट्रैक देखें ताकि आप गति पकड़ सकें। आप नीचे OpenAI Agents SDK के लिए हमारा वीडियो ट्यूटोरियल भी देख सकते हैं।

OpenAI Agents SDK के साथ काम करने के लिए पूर्वापेक्षाएँ

OpenAI Agents SDK में उतरने से पहले, कुछ बुनियादी अवधारणाओं को समझना और अपना परिवेश सही ढंग से सेट करना महत्वपूर्ण है। इस अनुभाग में वह सब शामिल है जो आपको अपना पहला एजेंट लिखने से पहले जानना चाहिए।

आवश्यक ज्ञान

इस ट्यूटोरियल से अधिकतम लाभ पाने के लिए, आपको इन बातों में सहज होना चाहिए:

  • मध्यम स्तर का Python प्रोग्रामिंग: आपको फंक्शंस, क्लासेस, async/await पैटर्न्स और टाइप हिंट्स समझने चाहिए
  • OpenAI API का बेसिक उपयोग: OpenAI मॉडलों को रिक्वेस्ट भेजने और रिस्पॉन्स संभालने की जानकारी
  • बड़े भाषा मॉडल (LLMs): LLMs कैसे काम करते हैं, उनकी क्षमताएँ/सीमाएँ का वैचारिक समझ
  • Pydantic: डेटा वैलिडेशन के लिए Pydantic का बेसिक ज्ञान सहायक होगा, क्योंकि Agents SDK में इसका व्यापक उपयोग होता है
  • असिंक्रोनस प्रोग्रामिंग: Python में async/await पैटर्न्स की जानकारी, क्योंकि Agents SDK असिंक्रोनस एक्जीक्यूशन पर आधारित है

यदि आपको इनमें से कुछ क्षेत्रों में अपना ज्ञान मजबूत करने की आवश्यकता है, तो DataCamp कई उत्कृष्ट संसाधन प्रदान करता है:

  • Working with the OpenAI API — OpenAI के मॉडलों के साथ इंटरैक्ट करने की बुनियादी बातें सीखें।
  • OpenAI Fundamentals Track — OpenAI तकनीकों के लिए एक व्यापक लर्निंग पाथ।
  • GPT-4.5 का अवलोकन — GPT मॉडलों की नवीनतम क्षमताओं के बारे में जानें।
  • GPT-4.5 के साथ फंक्शन कॉलिंग — एजेंट्स में टूल उपयोग को समझने के लिए आवश्यक पृष्ठभूमि।
  • GPT-4.5 API का उपयोग — एडवांस्ड मॉडलों के साथ काम करने के लिए व्यावहारिक गाइड।

एजेंट्स के लिए प्रमुख अवधारणाएँ

कोडिंग शुरू करने से पहले, आइए कुछ प्रमुख अवधारणाओं को स्पष्ट करें जो Agents SDK के केंद्र में हैं:

  1. Agents: AI सिस्टम जो टूल्स का उपयोग कर सकते हैं और कार्यों को पूरा करने के लिए निर्णय ले सकते हैं
  2. Tools: फंक्शंस जिन्हें एजेंट्स वेब सर्च या डेटाबेस एक्सेस जैसे कार्य करने के लिए कॉल कर सकते हैं
  3. Handoffs: विशिष्टीकृत एजेंट्स के बीच नियंत्रण स्थानांतरित करने के तंत्र
  4. Guardrails: इनपुट और आउटपुट को वैलिडेट करने वाले सुरक्षा उपाय जो उपयुक्त व्यवहार सुनिश्चित करते हैं

इन अवधारणाओं और उनके संबंधों को समझना आपको अधिक प्रभावी एजेंट-आधारित एप्लिकेशन बनाने में मदद करेगा। आप हमारे AI एजेंट्स को समझने के गाइड में और जान सकते हैं। 

OpenAI Agents वातावरण सेटअप

आइए अपना डेवलपमेंट वातावरण सेट करें ताकि OpenAI Agents SDK के साथ काम करने के लिए आवश्यक हर चीज मौजूद हो:

आवश्यक पैकेज इंस्टॉल करना

सबसे पहले एक वर्चुअल वातावरण बनाएँ और सक्रिय करें:

# Create and activate a virtual environment (run in your terminal)
python -m venv agents-env
source agents-env/bin/activate  # On Windows: agents-env\Scripts\activate

इसके बाद, OpenAI Agents SDK और python-dotenv इंस्टॉल करें:

pip install openai-agents python-dotenv

API की प्रबंधन के लिए python-dotenv का उपयोग

API की के साथ काम करते समय, उन्हें अपने कोड से बाहर रखना एक सर्वश्रेष्ठ अभ्यास है। python-dotenv पैकेज वातावरण चरों को प्रबंधित करने का एक सुरक्षित तरीका प्रदान करता है:

  1. अपने प्रोजेक्ट डायरेक्टरी में .env नामक फ़ाइल बनाएँ
  2. अपनी OpenAI API की इस फ़ाइल में जोड़ें:

OPENAI_API_KEY=your-api-key-here

3. अपने कोड में वातावरण चरों को लोड करें और उपयोग करें:

import os
from dotenv import load_dotenv
from agents import Agent, Runner

# Load environment variables from .env file
load_dotenv()

# Access your API key
api_key = os.getenv("OPENAI_API_KEY")
if not api_key:
   raise ValueError("OPENAI_API_KEY not found in .env file")

यह तरीका संवेदनशील जानकारी को आपके कोड से बाहर रखता है, जो विशेष रूप से महत्वपूर्ण है यदि आप अपना काम साझा कर रहे हैं या प्रकाशित कर रहे हैं।

async फंक्शंस के साथ काम करना

OpenAI Agents SDK में असिंक्रोनस प्रोग्रामिंग का व्यापक उपयोग होता है। अलग-अलग वातावरणों में async फंक्शंस के साथ इस प्रकार काम करें:

Python स्क्रिप्ट्स (.py फाइलें) में

सामान्य Python स्क्रिप्ट्स में, आपको async फंक्शंस को निष्पादित करने के लिए asyncio.run() का उपयोग करना होगा:

import asyncio
from agents import Agent, Runner

async def main():
   agent = Agent(
       name="Test Agent",
       instructions="You are a helpful assistant that provides concise responses."
   )
   result = await Runner.run(agent, "Hello! Are you working correctly?")
   print(result.final_output)

if __name__ == "__main__":
   asyncio.run(main())  # Run the async function

Jupyter नोटबुक्स में

Jupyter नोटबुक्स में पहले से एक इवेंट लूप चल रहा होता है, इसलिए आपको asyncio.run() का उपयोग नहीं करना चाहिए। इसके बजाय, आप async फंक्शंस को सीधे await कर सकते हैं:

from agents import Agent, Runner

# No need for asyncio.run() in notebooks
agent = Agent(
   name="Test Agent",
   instructions="You are a helpful assistant that provides concise responses."
)
result = await Runner.run(agent, "Hello! Are you working correctly?")
print(result.final_output)

यदि आप नोटबुक में asyncio.run() का उपयोग करने का प्रयास करते हैं, तो आपको इस तरह की त्रुटियाँ मिलेंगी:

RuntimeError: asyncio.run() cannot be called from a running event loop

यह स्क्रिप्ट्स और नोटबुक्स के बीच कोड कॉपी करते समय किए जाने वाले सबसे आम समायोजनों में से एक है। इस ट्यूटोरियल में, मैं मुख्य रूप से नोटबुक-फ्रेंडली सिंटैक्स का उपयोग करूँगा क्योंकि अधिकांश पाठक Jupyter का उपयोग करेंगे।

अपनी इंस्टॉलेशन का परीक्षण

आइए सुनिश्चित करें कि सब कुछ सही ढंग से सेट है:

from agents import Agent, Runner
from dotenv import load_dotenv

load_dotenv()

# For Jupyter notebooks:
agent = Agent(
   name="Test Agent",
   instructions="You are a helpful assistant that provides concise responses."
)
result = await Runner.run(agent, "Hello! Are you working correctly?")
print(result.final_output)

# For Python scripts, you'd use:
# async def test_installation():
#     agent = Agent(
#         name="Test Agent",
#         instructions="You are a helpful assistant that provides concise responses."
#     )
#     result = await Runner.run(agent, "Hello! Are you working correctly?")
#     print(result.final_output)
#
# if __name__ == "__main__":
#     asyncio.run(test_installation())

# Hello! Yes, I'm here and ready to help. How can I assist you today?

इस सेटअप के पूरा होने के साथ, आप OpenAI Agents SDK के साथ एप्लिकेशन बनाना शुरू करने के लिए तैयार हैं।

OpenAI Agents SDK के साथ शुरुआत

OpenAI Agents SDK के केंद्र में Agent क्लास है, जो ऐसे AI सिस्टम बनाने के लिए आपका प्राथमिक इंटरफेस है जो निर्देशों को समझ और उनके आधार पर कार्रवाई कर सके। आइए विभिन्न परिदृश्यों के लिए एजेंट्स बनाना और कॉन्फ़िगर करना सीखें।

इस SDK में एक एजेंट ऐसा AI सिस्टम दर्शाता है जो निर्देशों का पालन कर सकता है और, वैकल्पिक रूप से, कार्यों को पूरा करने के लिए टूल्स का उपयोग कर सकता है। एक बेसिक एजेंट बनाने के लिए कुछ आवश्यक पैरामीटर पर्याप्त हैं:

from agents import Agent

basic_agent = Agent(
   name="My First Agent",
   instructions="You are a helpful assistant that provides factual information.",
   model="gpt-4o"  # Optional: defaults to "gpt-4o" if not specified
)

एजेंट के तीन प्राथमिक घटक होते हैं:

  1. नाम: आपके एजेंट के लिए एक पहचानकर्ता, जो लॉगिंग और डीबगिंग में मदद करता है
  2. निर्देश: एजेंट के व्यवहार और उद्देश्य को परिभाषित करने वाला मुख्य “सिस्टम प्रॉम्प्ट”
  3. मॉडल: एजेंट को संचालित करने वाला अंतर्निहित भाषा मॉडल (डिफॉल्ट GPT-4o)

हालाँकि यह बेसिक सेटअप शुरू करने के लिए पर्याप्त है, Agent क्लास कई अतिरिक्त मॉडल कॉन्फ़िगरेशन विकल्प प्रदान करता है जो आपको LLM के व्यवहार पर अधिक नियंत्रण देते हैं:

from agents import ModelSettings


advanced_agent = Agent(
   name="Advanced Assistant",
   instructions="""You are a professional, concise assistant who always provides
   accurate information. When you don't know something, clearly state that.
   Focus on giving actionable insights when answering questions.""",
   model="gpt-4o",
   model_settings=ModelSettings(
       temperature=0.3,  # Lower for more deterministic outputs (0.0-2.0)
       max_tokens=1024,  # Maximum length of response
   ),
   tools=[]  # We'll cover tools in a later section
)

निर्देश और कॉन्फ़िगरेशन

निर्देश पैरामीटर संभवतः एजेंट डिज़ाइन का सबसे महत्वपूर्ण पहलू है। यह एजेंट के व्यवहार, टोन और क्षमताओं को निर्देशित करने वाले “सिस्टम प्रॉम्प्ट” की तरह कार्य करता है। प्रभावी निर्देश लिखना कला और विज्ञान दोनों है:

निर्देश लिखने के लिए सर्वोत्तम अभ्यास

  1. विशिष्ट बनें: एजेंट की भूमिका, व्यक्तित्व और सीमाओं को स्पष्ट रूप से परिभाषित करें
  2. सीमाएँ निर्धारित करें: स्पष्ट रूप से बताएं कि एजेंट किन विषयों या कार्यों से बचे
  3. इंटरैक्शन पैटर्न परिभाषित करें: समझाएँ कि एजेंट विभिन्न प्रकार के इनपुट्स को कैसे संभाले
  4. ज्ञान की सीमाएँ स्थापित करें: स्पष्ट करें कि एजेंट को क्या पता होना चाहिए और कब उसे अनिश्चितता स्वीकार करनी चाहिए

Agent में एक description पैरामीटर भी शामिल है, जो एजेंट का मानव-पठनीय विवरण है, और तब उपयोग होता है जब एजेंट टूल्स/हैंडऑफ्स के अंदर उपयोग किया जाता है।

कॉन्फ़िगरेशन विकल्प

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

  • temperature: प्रतिक्रियाओं में रैंडमनेस को नियंत्रित करता है (0.0–2.0)
    • कम मान (0.1–0.4) अधिक निर्धारक, केंद्रित प्रतिक्रियाएँ देते हैं
    • उच्च मान (0.7–1.0) अधिक रचनात्मक, विविध आउटपुट बनाते हैं
  • max_tokens: एजेंट प्रतिक्रियाओं की लंबाई सीमित करता है
    • संक्षिप्त आउटपुट सुनिश्चित करने या लागत नियंत्रित करने में उपयोगी
    • डिफॉल्ट मॉडल के अनुसार अलग होता है, लेकिन अधिकांश उपयोग मामलों के लिए पर्याप्त रूप से अधिक होता है
  • model: अंतर्निहित LLM का चयन करता है
    • “gpt-4o” अधिकांश उपयोग मामलों के लिए सर्वश्रेष्ठ प्रदर्शन देता है
    • “gpt-4o-mini” प्रदर्शन और लागत के बीच अच्छा संतुलन देता है
    • “gpt-3.5-turbo” कम जटिल कार्यों के लिए उपलब्ध है जहाँ गति और लागत प्राथमिकता हैं

ये कॉन्फ़िगरेशन विकल्प विभिन्न एप्लिकेशनों के अनुरूप एजेंट के व्यवहार को अनुकूलित करने के लिए एक शक्तिशाली ढांचा प्रदान करते हैं। हम आपको अलग-अलग सेटिंग्स के साथ प्रयोग करने के लिए प्रोत्साहित करते हैं ताकि आप देखें कि वे आपके एजेंट की प्रतिक्रियाओं को कैसे प्रभावित करती हैं और अपने विशेष उपयोग मामले के लिए सर्वोत्तम कॉन्फ़िगरेशन खोजें।

Open AI Agents SKD उदाहरण: एक विशेषीकृत मौसम सहायक बनाना

अब, आइए इन अवधारणाओं को एक साथ लाते हुए एक व्यावहारिक उदाहरण बनाते हैं: एक विशिष्टीकृत मौसम सूचना सहायक। यह उदाहरण दर्शाता है कि कैसे अच्छी तरह परिभाषित विशेषज्ञता, क्षमताओं और सीमाओं वाला एजेंट बनाया जाए:

from agents import Agent, Runner
from dotenv import load_dotenv

# Load environment variables (API key)
load_dotenv()

# Define detailed instructions for our weather assistant
weather_instructions = """
You are a weather information assistant who helps users understand weather patterns and phenomena.

YOUR EXPERTISE:
- Explaining weather concepts and terminology
- Describing how different weather systems work
- Answering questions about climate and seasonal patterns
- Explaining the science behind weather events

LIMITATIONS:
- You cannot provide real-time weather forecasts for specific locations
- You don't have access to current weather data
- You should not make predictions about future weather events

STYLE:
- Use clear, accessible language that non-meteorologists can understand
- Include interesting weather facts when relevant
- Be enthusiastic about meteorology and climate science
"""

# Create our specialized weather assistant
weather_assistant = Agent(
   name="WeatherWise",
   instructions=weather_instructions,
   model="gpt-3.5-turbo",
   model_settings=ModelSettings(
       temperature=0.5,  # Balanced temperature for natural but focused responses
       max_tokens=256,  # Maximum length of response
   )
)

अपना पहला एजेंट चलाना

एजेंट बनाने के बाद, आप इसे Runner क्लास का उपयोग करके चला सकते हैं। यह क्लास एजेंट कार्यों के निष्पादन और वार्तालाप प्रवाह का प्रबंधन करती है:

# For Jupyter notebooks:
result = await Runner.run(
   weather_assistant, "Can you tell me about the relationship between climate change and extreme weather events?"
)

print(result.final_output)

—--------

Absolutely! Climate change is closely linked to the increase in frequency and intensity of extreme weather events. As the Earth's climate warms due to the buildup of greenhouse gases in the atmosphere, it disrupts the balance of our planet's climate systems.

Here's how climate change influences extreme weather events:
1. **Heatwaves**: Rising global temperatures lead to more frequent and severe heatwaves. These events can have serious impacts on human health, agriculture, and ecosystems.

2. **Intense Storms**: Warmer oceans provide more energy to fuel hurricanes, typhoons, and other tropical storms, leading to stronger and more destructive events.

3. **Heavy Rainfall**: A warmer atmosphere can hold more moisture, resulting in heavier rainfall during storms. This can lead to flooding and landslides.

4. **Droughts**: Climate change can exacerbate drought conditions in certain regions, impacting water resources, agriculture, and ecosystems.

5. **Wildfires**: Higher temperatures and drier conditions increase the likelihood of wildfires, which can be more frequent and intense.

It's important to note that while climate change doesn't directly cause specific weather events, it can increase the likelihood and severity of extreme weather occurrences. Scientists continue to study these connections to better understand and prepare for the impacts of

Python स्क्रिप्ट्स के लिए, आपको asyncio दृष्टिकोण का उपयोग करना होगा:

# For Python scripts:
import asyncio

async def run_agent_example():
   result = await Runner.run(weather_assistant, "Can you tell me about the relationship between climate change and extreme weather events?")
   print(result.final_output)

if __name__ == "__main__":
   asyncio.run(run_agent_example())

इस अनुभाग में, हमने OpenAI Agents SDK के साथ एजेंट्स बनाने और चलाने की बुनियादी बातें कवर कीं। अगले भाग में, हम अपने एजेंट्स में टूल्स जोड़कर इन अवधारणाओं का विस्तार करेंगे, जिससे उनकी क्षमताएँ उल्लेखनीय रूप से बढ़ेंगी।

टूल्स के साथ काम करना

OpenAI Agents SDK की वास्तविक शक्ति तब सामने आती है जब आप अपने एजेंट्स को टूल्स से लैस करते हैं। टूल्स एजेंट्स को बाहरी प्रणालियों के साथ इंटरैक्ट करने, डेटा एक्सेस करने और ऐसी कार्रवाइयाँ करने में सक्षम बनाते हैं जो केवल टेक्स्ट जनरेशन से परे हों। Agents SDK तीन मुख्य प्रकार के टूल्स सपोर्ट करता है: होस्टेड टूल्स, फंक्शन टूल्स और एजेंट-एज़-टूल्स।

होस्टेड टूल्स

होस्टेड टूल्स OpenAI के सर्वरों पर भाषा मॉडलों के साथ चलते हैं। ये टूल्स बिल्ट-इन क्षमताएँ प्रदान करते हैं, जिनके लिए आपको जटिल कार्यक्षमता लागू करने की आवश्यकता नहीं होती।

WebSearchTool: एक रिसर्च असिस्टेंट बनाना

WebSearchTool आपके एजेंट को वेब पर नवीनतम जानकारी खोजने की क्षमता देता है। यह खासकर उन कार्यों के लिए मूल्यवान है जिनके लिए मॉडल के प्रशिक्षण डेटा से परे वर्तमान ज्ञान की आवश्यकता होती है।

from agents import Agent, Runner, WebSearchTool
from dotenv import load_dotenv

load_dotenv()

# Create a research assistant with web search capability
research_assistant = Agent(
   name="Research Assistant",
   instructions="""You are a research assistant that helps users find and summarize information.
   When asked about a topic:
   1. Search the web for relevant, up-to-date information
   2. Synthesize the information into a clear, concise summary
   3. Structure your response with headings and bullet points when appropriate
   4. Always cite your sources at the end of your response
  
   If the information might be time-sensitive or rapidly changing, mention when the search was performed.
   """,
   tools=[WebSearchTool()]
)

async def research_topic(topic):
   result = await Runner.run(research_assistant, f"Please research and summarize: {topic}. Only return the found links with very minimal text.")
   return result.final_output

# Usage example (in Jupyter notebook)
summary = await research_topic("Latest developments in personal productivity apps.")
print(summary[:512])

—----------------

Here are some recent developments in personal productivity apps:

- **AI Integration in Productivity Tools**: Startups like Anthropic are developing AI agents capable of performing routine tasks across different applications, aiming to streamline workflows and reduce the need for multiple apps. ([ft.com](https://www.ft.com/content/a0e54dd5-b270-42cc-8c4c-18a0b8b3e6cc?utm_source=openai))

- **Read AI's Expansion**: Read AI, a productivity startup, secured $50 million in funding, valuing the company at $450 m

इस उदाहरण में, हमने एक रिसर्च असिस्टेंट बनाया है जो वेब खोज सकता है और जानकारी को एक सुसंगत सारांश में संश्लेषित कर सकता है। WebSearchTool को काम करने के लिए किसी पैरामीटर की आवश्यकता नहीं होती, लेकिन आप आवश्यकता के अनुसार इसके व्यवहार को कस्टमाइज़ कर सकते हैं:

# Customized search tool with location context
location_aware_search = WebSearchTool(
   user_location="San Francisco, CA",  # Provides geographic context for local search queries
   search_context_size=3  # Number of search results to consider in the response
)

user_location पैरामीटर विशेष रूप से उन क्वेरीज़ के लिए उपयोगी है जो भौगोलिक संदर्भ से लाभान्वित होती हैं, जैसे स्थानीय सेवाएँ या क्षेत्रीय जानकारी। search_context_size पैरामीटर इस बात को नियंत्रित करने में मदद करता है कि प्रतिक्रिया बनाते समय मॉडल कितने सर्च परिणामों पर विचार करे।

फंक्शन टूल्स

फंक्शन टूल्स आपको किसी भी Python फंक्शन के साथ अपने एजेंट का विस्तार करने देते हैं। यहीं Agents SDK की वास्तविक लचीलापन झलकता है, जो किसी भी API, डेटाबेस, या लोकल सर्विस के साथ एकीकरण सक्षम करता है।

मौसम पूर्वानुमान टूल

आइए एक व्यावहारिक उदाहरण बनाते हैं जो थर्ड-पार्टी वेदर API के साथ एकीकृत हो:

import os
import requests
from datetime import datetime
from typing import Optional, List
from dataclasses import dataclass

from agents import Agent, Runner, function_tool
from dotenv import load_dotenv

load_dotenv()


@dataclass
class WeatherInfo:
   temperature: float
   feels_like: float
   humidity: int
   description: str
   wind_speed: float
   pressure: int
   location_name: str
   rain_1h: Optional[float] = None
   visibility: Optional[int] = None


@function_tool
def get_weather(lat: float, lon: float) -> str:
   """Get the current weather for a specified location using OpenWeatherMap API.

   Args:
       lat: Latitude of the location (-90 to 90)
       lon: Longitude of the location (-180 to 180)
   """
   # Get API key from environment variables
   WEATHER_API_KEY = os.getenv("OPENWEATHERMAP_API_KEY")

   # Build URL with parameters
   url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={WEATHER_API_KEY}&units=metric"

   try:
       response = requests.get(url)
       response.raise_for_status()
       data = response.json()

       # Extract weather data from the response
       weather_info = WeatherInfo(
           temperature=data["main"]["temp"],
           feels_like=data["main"]["feels_like"],
           humidity=data["main"]["humidity"],
           description=data["weather"][0]["description"],
           wind_speed=data["wind"]["speed"],
           pressure=data["main"]["pressure"],
           location_name=data["name"],
           visibility=data.get("visibility"),
           rain_1h=data.get("rain", {}).get("1h"),
       )

       # Build the response string
       weather_report = f"""
       Weather in {weather_info.location_name}:
       - Temperature: {weather_info.temperature}°C (feels like {weather_info.feels_like}°C)
       - Conditions: {weather_info.description}
       - Humidity: {weather_info.humidity}%
       - Wind speed: {weather_info.wind_speed} m/s
       - Pressure: {weather_info.pressure} hPa
       """
       return weather_report

   except requests.exceptions.RequestException as e:
       return f"Error fetching weather data: {str(e)}"

यह वेदर API फंक्शन टूल OpenWeatherMap API और हमारे एजेंट के बीच पुल का काम करता है। यह भौगोलिक निर्देशांकों द्वारा रियल-टाइम मौसम डेटा लाता है और उसे पढ़ने योग्य रिपोर्ट में फ़ॉर्मैट करता है। 

कोड एक WeatherInfo डेटा क्लास परिभाषित करता है जो टाइप्ड फ़ील्ड्स (तापमान, आर्द्रता, आदि) के साथ डेटा को संरचित करता है, जिससे यह व्यवस्थित और मेंटेन करने योग्य बनता है। @function_tool डेकोरेटर हमारे Python फंक्शन को एक ऐसे टूल में बदल देता है जिसका उपयोग एजेंट कर सकता है, और फंक्शन के सिग्नेचर और डॉकस्ट्रिंग से स्वतः स्कीमा बनाता है।

कॉल किए जाने पर, यह फंक्शन वातावरण चरों से सुरक्षित रूप से API की प्राप्त करता है, OpenWeatherMap को HTTP अनुरोध करता है और JSON रिस्पॉन्स को प्रोसेस करता है। 

यह वर्षा जैसे वैकल्पिक डेटा फ़ील्ड्स को सुरक्षित रूप से संभालता है और सब कुछ एक स्पष्ट वेदर रिपोर्ट में फ़ॉर्मैट करता है, जिसमें API अनुरोध विफल होने पर एरर हैंडलिंग भी शामिल है। इससे हमारा एजेंट API विवरण समझे बिना एक सुसंगत, मानव-पठनीय फ़ॉर्मैट में वर्तमान मौसम जानकारी प्रदान कर सकता है।

# Create a weather assistant
weather_assistant = Agent(
   name="Weather Assistant",
   instructions="""You are a weather assistant that can provide current weather information.
  
   When asked about weather, use the get_weather tool to fetch accurate data.
   If the user doesn't specify a country code and there might be ambiguity,
   ask for clarification (e.g., Paris, France vs. Paris, Texas).
  
   Provide friendly commentary along with the weather data, such as clothing suggestions
   or activity recommendations based on the conditions.
   """,
   tools=[get_weather]
)

वेदर असिस्टेंट चलाने के लिए:

async def main():
   runner = Runner()
  
   simple_request = await runner.run(weather_assistant, "What are your capabilities?")
  
   request_with_location = await runner.run(weather_assistant, "What's the weather like in Tashkent right now?")
  
   print(simple_request.final_output)
   print("-"*70)
   print(request_with_location.final_output)

await main()

Output:

I can provide you with the current weather conditions for any location around the world. Just give me the location details, and I'll fetch the weather data for you. I can also offer tips on activities or clothing based on the weather. If you have a specific city in mind, let me know, and I'll get to work!
----------------------------------------------------------------------
The weather in Tashkent is currently lovely with a clear sky. It's around 19.8°C, but it might feel slightly cooler at 18.6°C. The humidity is quite low at 26%, making it a pleasant day to be outdoors. A gentle breeze is blowing at 3.09 m/s, and the air pressure is steady at 1023 hPa.

It's a great time for a picnic in the park or a leisurely walk. Light clothing should be perfect for this weather. Enjoy your day in Tashkent!

प्रतिक्रिया से सिद्ध होता है कि एजेंट ने वेदर टूल का सफलतापूर्वक उपयोग किया। इसने प्रॉम्प्ट से शहर का नाम अलग किया, अपनी ज्ञात जानकारी से उसके निर्देशांक निकाले, और उन्हें lat और lon के रूप में टूल को पास किया।

एजेंट्स को टूल्स के रूप में

Agents SDK आपको स्वयं एजेंट्स को टूल्स के रूप में उपयोग करने देता है, जिससे एक पदानुक्रमित संरचना संभव होती है जहाँ विशेषज्ञ एजेंट्स एक समन्वयक के अधीन काम करते हैं। यह जटिल वर्कफ़्लो के लिए एक शक्तिशाली पैटर्न है।

from agents import Agent, Runner
from dotenv import load_dotenv

load_dotenv()

# Specialist agents
note_taking_agent = Agent(
   name="Note Manager",
   instructions="You help users take and organize notes efficiently.",
   # In a real application, this agent would have note-taking tools
)

task_management_agent = Agent(
   name="Task Manager",
   instructions="You help users manage tasks, deadlines, and priorities.",
   # In a real application, this agent would have task management tools
)

# Coordinator agent that uses specialists as tools
productivity_assistant = Agent(
   name="Productivity Assistant",
   instructions="""You are a productivity assistant that helps users organize their work and personal life.
  
   For note-taking questions or requests, use the note_taking tool.
   For task and deadline management, use the task_management tool.
  
   Help the user decide which tool is appropriate based on their request,
   and coordinate between different aspects of productivity.
   """,
   tools=[
       note_taking_agent.as_tool(
           tool_name="note_taking",
           tool_description="For taking, organizing, and retrieving notes and information"
       ),
       task_management_agent.as_tool(
           tool_name="task_management",
           tool_description="For managing tasks, setting deadlines, and tracking priorities"
       )
   ]
)

इस उदाहरण में:

  1. हम दो विशेषज्ञ एजेंट बनाते हैं, प्रत्येक एक केंद्रित डोमेन विशेषज्ञता के साथ।
  2. फिर हम एक समन्वयक एजेंट बनाते हैं जो इन विशेषज्ञों को डेलिगेट कर सकता है।
  3. हम प्रत्येक विशेषज्ञ एजेंट को .as_tool() मेथड का उपयोग करके एक टूल में बदलते हैं, निर्दिष्ट करते हुए:
  • एक tool_name जिसे समन्वयक टूल को संदर्भित करने के लिए उपयोग करेगा।
  • एक tool_description जो समन्वयक को समझने में मदद करता है कि इस टूल का उपयोग कब करना है।

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

प्रोडक्टिविटी असिस्टेंट का उपयोग करने के लिए:

async def main():
   runner = Runner()
  
   result = await runner.run(productivity_assistant, "I need to keep track of my project deadlines")
   print(result.final_output)

await main()

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

अब जब हम समझ गए हैं कि अपने एजेंट्स को टूल्स से कैसे लैस करें, अगली चुनौती उनके आउटपुट को संभालना और संरचित करना है। अगले अनुभाग में, हम एजेंट प्रतिक्रियाओं को प्रोसेस करने की तकनीकों का पता लगाएंगे—बेसिक टेक्स्ट आउटपुट से लेकर जटिल संरचित डेटा तक—ताकि हमें वही सूचना प्रारूप मिले जिसकी हमारे एप्लिकेशनों को आवश्यकता है।

OpenAI एजेंट आउटपुट को समझना

एजेंट्स के साथ काम करते समय, मुक्त-रूप टेक्स्ट के बजाय संरचित जानकारी प्राप्त करना आपके एप्लिकेशनों को अधिक विश्वसनीय बना सकता है। OpenAI Agents SDK एजेंट्स से सीधे संरचित आउटपुट प्राप्त करने का एक स्वच्छ, बिल्ट-इन तरीका प्रदान करता है।

Pydantic मॉडलों के साथ संरचित आउटपुट

SDK आपको एजेंट बनाते समय output_type पैरामीटर निर्दिष्ट करके ठीक वही डेटा संरचना परिभाषित करने देता है जो आप अपने एजेंट से लौटाना चाहते हैं:

from pydantic import BaseModel
from typing import List, Optional
from agents import Agent, Runner
from dotenv import load_dotenv

load_dotenv()
True
First, we define our data models using Pydantic:
# Define person data model
class Person(BaseModel):
   name: str
   role: Optional[str]
   contact: Optional[str]


# Define meeting data model
class Meeting(BaseModel):
   date: str
   time: str
   location: Optional[str]
   duration: Optional[str]


# Define task data model
class Task(BaseModel):
   description: str
   assignee: Optional[str]
   deadline: Optional[str]
   priority: Optional[str]


# Define the complete email data model
class EmailData(BaseModel):
   subject: str
   sender: Person
   recipients: List[Person]
   main_points: List[str]
   meetings: List[Meeting]
   tasks: List[Task]
   next_steps: Optional[str]

ये मॉडल परिभाषित करते हैं कि हम अपने निकाले गए डेटा की संरचना कैसी चाहते हैं। प्रत्येक क्लास उस विशिष्ट प्रकार की जानकारी का प्रतिनिधित्व करता है जिसे हम ईमेल से निकालना चाहते हैं।

अब, हम एक ऐसा एजेंट बनाते हैं जो output_type पैरामीटर सेट करके हमारे संरचित फ़ॉर्मैट में डेटा आउटपुट करेगा:

# Create an email extraction agent with structured output
email_extractor = Agent(
   name="Email Extractor",
   instructions="""You are an assistant that extracts structured information from emails.
  
   When given an email, carefully identify:
   - Subject and main points
   - People mentioned (names, roles, contact info)
   - Meetings (dates, times, locations)
   - Tasks or action items (with assignees and deadlines)
   - Next steps or follow-ups
  
   Extract this information as structured data. If something is unclear or not mentioned,
   leave those fields empty rather than making assumptions.
   """,
   output_type=EmailData,  # This tells the agent to return data in EmailData format
)

जब आप output_type निर्दिष्ट करते हैं, तो एजेंट सादा टेक्स्ट प्रतिक्रियाओं के बजाय स्वतः संरचित डेटा उत्पन्न करेगा। इससे मैनुअल JSON पार्सिंग या regex एक्सट्रैक्शन की आवश्यकता समाप्त हो जाती है।

आइए इस एक्सट्रैक्टर का एक सैंपल ईमेल के साथ उपयोग करें:

sample_email = """
From: Alex Johnson <alex.j@techcorp.com>
To: Team Development <team-dev@techcorp.com>
CC: Sarah Wong <sarah.w@techcorp.com>, Miguel Fernandez <miguel.f@techcorp.com>
Subject: Project Phoenix Update and Next Steps

Hi team,

I wanted to follow up on yesterday's discussion about Project Phoenix and outline our next steps.

Key points from our discussion:
- The beta testing phase has shown promising results with 85% positive feedback
- We're still facing some performance issues on mobile devices
- The client has requested additional features for the dashboard

Let's schedule a follow-up meeting this Friday, June 15th at 2:00 PM in Conference Room B. The meeting should last about 1.5 hours, and we'll need to prepare the updated project timeline.

Action items:
1. Sarah to address the mobile performance issues by June 20th (High priority)
2. Miguel to create mock-ups for the new dashboard features by next Monday
3. Everyone to review the beta testing feedback document and add comments by EOD tomorrow

If you have any questions before Friday's meeting, feel free to reach out.

Best regards,
Alex Johnson
Senior Project Manager
(555) 123-4567
"""

अब SDK कन्वर्ज़न संभालता है, इसलिए ईमेल प्रोसेस करना काफी सरल हो जाता है:

async def process_email(email_text):
   runner = Runner()
   result = await runner.run(
       email_extractor,
       f"Please extract information from this email:\n\n{email_text}"
   )

   # The result is already a structured EmailData object
   return result


# Process the sample email
result = await process_email(sample_email)

# Display the extracted information
result = result.final_output

print(f"Subject: {result.subject}")
print(f"From: {result.sender.name} ({result.sender.role})")
print("\nMain points:")
for point in result.main_points:
   print(f"- {point}")

print("\nMeetings:")
for meeting in result.meetings:
   print(f"- {meeting.date} at {meeting.time}, Location: {meeting.location}")

print("\nTasks:")
for task in result.tasks:
   print(f"- {task.description}")
   print(
       f"  Assignee: {task.assignee}, Deadline: {task.deadline}, Priority: {task.priority}"
   )
—----------

Subject: Project Phoenix Update and Next Steps
From: Alex Johnson (Senior Project Manager)

Main points:
- 85% positive feedback from beta testing
- Performance issues on mobile devices
- Client requested additional dashboard features

Meetings:
- June 15th at 2:00 PM, Location: Conference Room B

Tasks:
- Address mobile performance issues
 Assignee: Sarah, Deadline: June 20th, Priority: High
- Create mock-ups for new dashboard features
 Assignee: Miguel, Deadline: Next Monday, Priority: None
- Review beta testing feedback document and add comments
 Assignee: Everyone, Deadline: EOD tomorrow, Priority: None

यह कोड हमारे पहले के तरीके की तुलना में काफी स्वच्छ है क्योंकि:

  1. हमें रिस्पॉन्स से JSON को मैन्युअली निकालने और पार्स करने की ज़रूरत नहीं है।
  2. SDK एजेंट के आउटपुट को हमारे Pydantic मॉडल में कन्वर्ट करता है।
  3. हम सीधे संरचित डेटा प्रॉपर्टीज़ (जैसे result.final_output.subject) तक पहुँच सकते हैं।
  4. टाइप वैलिडेशन स्वतः होता है, इसलिए हमें पता है कि डेटा हमारे मॉडल से मेल खाता है।

विभिन्न आउटपुट प्रकारों के साथ काम करना

output_type पैरामीटर किसी भी ऐसे प्रकार के साथ काम करता है जिसे Pydantic के TypeAdapter में रैप किया जा सके:

# For simple lists
agent_with_list_output = Agent(
   name="List Generator",
   instructions="Generate lists of items based on the user's request.",
   output_type=list[str],  # Returns a list of strings
)

# For dictionaries
agent_with_dict_output = Agent(
   name="Dictionary Generator",
   instructions="Create key-value pairs based on the input.",
   output_type=dict[
       str, int
   ],  # Returns a dictionary with string keys and integer values
)

# For simple primitive types
agent_with_bool_output = Agent(
   name="Decision Maker",
   instructions="Answer yes/no questions with True or False.",
   output_type=bool,  # Returns a boolean
)

संरचित आउटपुट के लाभ

output_type पैरामीटर का उपयोग कई फायदे देता है:

  1. डायरेक्ट इंटीग्रेशन: आपके एजेंट आउटपुट्स स्वतः Python ऑब्जेक्ट्स के रूप में उपलब्ध होते हैं।
  2. टाइप सेफ्टी: SDK सुनिश्चित करता है कि आउटपुट आपकी परिभाषित संरचना से मेल खाते हैं।
  3. सरल कोड: मैनुअल JSON पार्सिंग या एरर हैंडलिंग की आवश्यकता नहीं।
  4. बेहतर प्रदर्शन: SDK कुशलता से कन्वर्ज़न संभालता है।
  5. IDE सपोर्ट: आपका IDE संरचित आउटपुट प्रॉपर्टीज़ के लिए ऑटोकंप्लीशन दे सकता है।

स्पष्ट डेटा मॉडल परिभाषित करके और output_type पैरामीटर का उपयोग करके, आपके एजेंट्स ठीक वही डेटा स्ट्रक्चर उत्पन्न कर सकते हैं जिसकी आपके एप्लिकेशन को आवश्यकता है, जिससे एकीकरण सहज होता है और आपके कोड की जटिलता कम होती है।

अगले भाग में, हम एजेंट्स के बीच हैंडऑफ्स का पता लगाएंगे, जो आपको ऐसे विशिष्टीकृत एजेंट्स बनाने की अनुमति देते हैं जो जटिल कार्यों पर मिलकर काम कर सकें। ये हैंडऑफ्स एजेंट्स के बीच जानकारी को एक सुसंगत, टाइप-सेफ तरीके से पास करने के लिए संरचित आउटपुट का उपयोग कर सकते हैं।

Handoffs: एजेंट्स के बीच डेलिगेशन

जटिल एप्लिकेशनों में, अलग-अलग कार्य अक्सर अलग-अलग विशेषज्ञता क्षेत्रों की मांग करते हैं। OpenAI Agents SDK “हैंडऑफ्स” को सपोर्ट करता है, जो एक एजेंट को नियंत्रण किसी अन्य विशिष्टीकृत एजेंट को सौंपने देता है। यह सुविधा विशेष रूप से उन सिस्टम्स में मूल्यवान है जो विविध उपयोगकर्ता अनुरोधों को संभालते हैं, जैसे कस्टमर सपोर्ट एप्लिकेशन जहाँ अलग-अलग एजेंट्स बिलिंग पूछताछ, तकनीकी सहायता, या अकाउंट मैनेजमेंट संभाल सकते हैं।

बेसिक हैंडऑफ्स बनाना

सबसे सरल रूप में, हैंडऑफ्स आपको कई एजेंट्स को इस तरह जोड़ने देते हैं कि वे उपयुक्त होने पर नियंत्रण स्थानांतरित कर सकें। आइए एक सरल कस्टमर सर्विस सिस्टम बनाते हैं जिसमें एक ट्रायेज एजेंट विशेषज्ञों को हैंडऑफ कर सके:

from agents import Agent, handoff, Runner
from dotenv import load_dotenv

load_dotenv()

# Create specialist agents
billing_agent = Agent(
   name="Billing Agent",
   instructions="""You are a billing specialist who helps customers with payment issues.
   Focus on resolving billing inquiries, subscription changes, and refund requests.
   If asked about technical problems or account settings, explain that you specialize
   in billing and payment matters only.""",
)

technical_agent = Agent(
   name="Technical Agent",
   instructions="""You are a technical support specialist who helps with product issues.
   Assist users with troubleshooting, error messages, and how-to questions.
   Focus on resolving technical problems only.""",
)

# Create a triage agent that can hand off to specialists
triage_agent = Agent(
   name="Customer Service",
   instructions="""You are the initial customer service contact who helps direct
   customers to the right specialist.
  
   If the customer has billing or payment questions, hand off to the Billing Agent.
   If the customer has technical problems or how-to questions, hand off to the Technical Agent.
   For general inquiries or questions about products, you can answer directly.
  
   Always be polite and helpful, and ensure a smooth transition when handing off to specialists.""",
   handoffs=[billing_agent, technical_agent],  # Direct handoff to specialist agents
)

इस उदाहरण में, हमने तीन एजेंट्स वाला एक सिस्टम बनाया है:

  • दो विशेषज्ञ एजेंट्स जिनकी केंद्रित विशेषज्ञता है
  • एक ट्रायेज एजेंट जो विशेषज्ञों को डेलिगेट कर सकता है

ध्यान दें कि हम बस विशेषज्ञ एजेंट्स को ट्रायेज एजेंट के handoffs पैरामीटर में शामिल करते हैं। Agents SDK स्वतः उपयुक्त हैंडऑफ टूल्स बनाता है जिनका ट्रायेज एजेंट आवश्यकता होने पर उपयोग कर सकता है।

आइए सिस्टम को क्रियान्वयन में देखें:

async def handle_customer_request(request):
   runner = Runner()
   result = await runner.run(triage_agent, request)
   return result


# Example customer inquiries
billing_inquiry = (
   "I was charged twice for my subscription last month. Can I get a refund?"
)
technical_inquiry = (
   "The app keeps crashing when I try to upload photos. How can I fix this? Give me the shortest solution possible."
)
general_inquiry = "What are your business hours?"

# Process the different types of inquiries
billing_response = await handle_customer_request(billing_inquiry)
print(f"Billing inquiry response:\n{billing_response.final_output}\n")

technical_response = await handle_customer_request(technical_inquiry)
print(f"Technical inquiry response:\n{technical_response.final_output}\n")

general_response = await handle_customer_request(general_inquiry)
print(f"General inquiry response:\n{general_response.final_output}")

जब ट्रायेज एजेंट को बिलिंग से संबंधित प्रश्न मिलता है, तो वह पहचान लेगा कि Billing Agent इसे बेहतर तरीके से संभाल सकता है और हैंडऑफ करेगा। तकनीकी प्रश्नों को तकनीकी एजेंट को सौंप दिया जाएगा। सामान्य प्रश्नों का उत्तर वह अपनी क्षमताओं के भीतर सीधे देगा। आउटपुट इस प्रकार है:

Billing inquiry response:
I can help with that. Could you please provide the transaction details or the date of the charges? This will help me locate the duplicate charge and process a refund for you.

Technical inquiry response:
Try these steps:

1. Restart the app.
2. Update to the latest app version.
3. Clear the app cache.
4. Restart your device.

If it persists, reinstall the app.

General inquiry response:
Our business hours are Monday to Friday, 9 AM to 5 PM. If you need assistance outside these hours, feel free to reach out and we'll get back to you as soon as possible. Is there anything else I can help you with?

हैंडऑफ्स को कस्टमाइज़ करना

हैंडऑफ्स पर अधिक नियंत्रण के लिए, आप handoffs पैरामीटर में सीधे एजेंट देने के बजाय handoff() फंक्शन का उपयोग कर सकते हैं:

from agents import Agent, handoff, RunContextWrapper
from datetime import datetime

# Create an agent that handles account-related questions
account_agent = Agent(
   name="Account Management",
   instructions="""You help customers with account-related issues such as
   password resets, account settings, and profile updates.""",
)


# Custom handoff callback function
async def log_account_handoff(ctx: RunContextWrapper[None]):
   print(
       f"[LOG] Account handoff triggered at {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
   )
   # In a real app, you might log to a database or alert a human supervisor


# Create a triage agent with customized handoffs
enhanced_triage_agent = Agent(
   name="Enhanced Customer Service",
   instructions="""You are the initial customer service contact who directs
   customers to the right specialist.
  
   If the customer has billing or payment questions, hand off to the Billing Agent.
   If the customer has technical problems, hand off to the Technical Agent.
   If the customer needs to change account settings, hand off to the Account Management agent.
   For general inquiries, you can answer directly.""",
   handoffs=[
       billing_agent,  # Basic handoff
       handoff(  # Customized handoff
           agent=account_agent,
           on_handoff=log_account_handoff,  # Callback function
           tool_name_override="escalate_to_account_team",  # Custom tool name
           tool_description_override="Transfer the customer to the account management team for help with account settings, password resets, etc.",
       ),
       technical_agent,  # Basic handoff
   ],
)

result = await Runner.run(
   enhanced_triage_agent, "I need to change my password."
)

आउटपुट:

[LOG] Account handoff triggered at 2025-03-16 17:45:48

handoff() फंक्शन आपको यह करने देता है:

  • on_handoff के साथ एक कस्टम कॉलबैक निर्दिष्ट करें
  • डिफॉल्ट टूल नाम को ओवरराइड करें (आम तौर पर “transfer_to_[agent_name]”)
  • एक कस्टम टूल विवरण प्रदान करें
  • इनपुट हैंडलिंग कॉन्फ़िगर करें (नीचे इस पर अधिक)

हैंडऑफ्स के दौरान डेटा पास करना

कभी-कभी, आप चाहेंगे कि पहला एजेंट किसी अन्य एजेंट को हैंडऑफ करते समय अतिरिक्त संदर्भ या मेटाडेटा प्रदान करे। Agents SDK इसे input_type पैरामीटर के माध्यम से सपोर्ट करता है:

from pydantic import BaseModel
from typing import Optional
from agents import Agent, handoff, RunContextWrapper


# Define the data structure to pass during handoff
class EscalationData(BaseModel):
   reason: str
   priority: Optional[str]
   customer_tier: Optional[str]


# Handoff callback that processes the escalation data
async def process_escalation(ctx: RunContextWrapper, input_data: EscalationData):
   print(f"[ESCALATION] Reason: {input_data.reason}")
   print(f"[ESCALATION] Priority: {input_data.priority}")
   print(f"[ESCALATION] Customer tier: {input_data.customer_tier}")

   # You might use this data to prioritize responses, alert human agents, etc.


# Create an escalation agent
escalation_agent = Agent(
   name="Escalation Agent",
   instructions="""You handle complex or sensitive customer issues that require
   special attention. Always address the customer's concerns with extra care and detail.""",
)

# Create a service agent that can escalate with context
service_agent = Agent(
   name="Service Agent",
   instructions="""You are a customer service agent who handles general inquiries.
  
   For complex issues, escalate to the Escalation Agent and provide:
   - The reason for escalation
   - Priority level (Low, Normal, High, Urgent)
   - Customer tier if mentioned (Standard, Premium, VIP)""",
   handoffs=[
       handoff(
           agent=escalation_agent,
           on_handoff=process_escalation,
           input_type=EscalationData,
       )
   ],
)

इस सेटअप के साथ, जब सर्विस एजेंट एस्केलेशन एजेंट को हैंडऑफ करने का निर्णय लेता है, तो वह यह बताते हुए संरचित डेटा प्रदान करेगा कि एस्केलेशन क्यों हो रहा है। सिस्टम इस डेटा को EscalationData मॉडल के विरुद्ध वैलिडेट करेगा और फिर उसे process_escalation कॉलबैक को पास करेगा।

हैंडऑफ्स बनाम एजेंट-एज़-टूल का उपयोग कब करें

Agents SDK एजेंट्स को साथ काम कराने के दो तरीके देता है: हैंडऑफ्स और एजेंट्स को टूल्स के रूप में उपयोग करना (जैसा कि हमने पिछले भाग में देखा)। प्रत्येक दृष्टिकोण का उपयोग कब करें, यह यहाँ है:

हैंडऑफ्स का उपयोग करें जब:

  • आप पूरी तरह से नियंत्रण किसी अन्य एजेंट को स्थानांतरित करना चाहते हैं
  • वार्तालाप किसी विशेषज्ञ के साथ जारी रहना चाहिए
  • आप एक ऐसा वर्कफ़्लो बना रहे हैं जहाँ अलग-अलग चरण अलग-अलग एजेंट्स संभालते हैं

एजेंट-एज़-टूल्स का उपयोग करें जब:

  • प्राथमिक एजेंट को किसी विशेषज्ञ से परामर्श करना हो लेकिन नियंत्रण अपने पास रखना हो
  • आप किसी विशेषज्ञ की प्रतिक्रिया को बड़े उत्तर के हिस्से के रूप में शामिल करना चाहते हैं
  • आप एक पदानुक्रमित सिस्टम बना रहे हैं जहाँ एक समन्वयक उप-कार्यों को डेलिगेट करता है

दोनों दृष्टिकोणों को परिष्कृत सिस्टम्स में संयोजित किया जा सकता है, जहाँ मुख्य एजेंट कभी-कभी विशेषज्ञों से परामर्श करता है (उन्हें टूल्स के रूप में उपयोग करके) और उपयुक्त होने पर कभी-कभी नियंत्रण पूरी तरह सौंप देता है।

हैंडऑफ्स अलग-अलग विशेषज्ञों के बीच ज़िम्मेदारी के संक्रमण वाले जटिल एजेंट सिस्टम बनाने का एक शक्तिशाली तंत्र प्रदान करते हैं। अपनी एजेंट आर्किटेक्चर डिज़ाइन करते समय, यह विचार करें कि आपके विशिष्ट उपयोग मामले के लिए कौन-सा दृष्टिकोण सबसे उपयुक्त है ताकि सबसे अच्छा उपयोगकर्ता अनुभव बनाया जा सके।

निष्कर्ष और अगले कदम

हमने OpenAI Agents SDK के मुख्य घटकों का अन्वेषण किया—बेसिक एजेंट बनाने से लेकर फंक्शन टूल्स लागू करने और विशेषज्ञ एजेंट्स के बीच हैंडऑफ्स प्रबंधित करने तक। हमने देखा कि Pydantic मॉडलों का उपयोग करके संरचित आउटपुट कैसे हमारे एप्लिकेशनों को अधिक विश्वसनीय और मेंटेन करने योग्य बनाते हैं, और कैसे डेलिगेशन तथा विशेषज्ञता के माध्यम से जटिल कार्यों को संभालने वाले एजेंट सिस्टम डिज़ाइन किए जाते हैं।

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

जैसे-जैसे AI एजेंट्स आधुनिक एप्लिकेशनों के केंद्र में आते जा रहे हैं, इस ट्यूटोरियल के माध्यम से आपने जो कौशल विकसित किए हैं वे परिष्कृत AI सिस्टम बनाने के लिए ठोस आधार प्रदान करते हैं। अपनी सीखने की यात्रा जारी रखें जैसे संसाधनों के साथ DataCamp का AI सीखने का गाइड, और याद रखें कि प्रभावी एजेंट डिज़ाइन जितना विज्ञान है उतनी ही कला भी — जिसके लिए पुनरावृत्ति, परीक्षण, और उपयोगकर्ता आवश्यकताओं तथा AI क्षमताओं की गहरी समझ आवश्यक है।

OpenAI Agents SDK FAQs

OpenAI Agents SDK क्या है?

OpenAI Agents SDK एक Python फ्रेमवर्क है जो डेवलपर्स को ऐसे AI एप्लिकेशन बनाने में सक्षम बनाता है जो निर्णय ले सकते हैं और कार्रवाई कर सकते हैं। यह बड़े भाषा मॉडलों को टूल्स और समन्वय क्षमताओं के साथ जोड़ता है, जिससे आप ऐसे सिस्टम बना सकते हैं जो केवल क्वेरी का उत्तर देने के बजाय स्वायत्त रूप से जटिल समस्याएँ हल कर सकें।

SDK में एजेंट्स कौन-कौन से टूल्स का उपयोग कर सकते हैं?

SDK तीन मुख्य प्रकार के टूल्स सपोर्ट करता है: होस्टेड टूल्स (जैसे WebSearchTool जो OpenAI के सर्वरों पर चलते हैं), फंक्शन टूल्स (कस्टम Python फंक्शंस जो एजेंट क्षमताओं का विस्तार करते हैं), और एजेंट-एज़-टूल्स (विशेषज्ञ एजेंट्स को अन्य एजेंट्स के लिए टूल्स के रूप में उपयोग करना)। ये एजेंट्स को वेब सर्च करने, APIs एक्सेस करने, या विशेषज्ञ एजेंट्स को डेलिगेट करने जैसे कार्य करने में सक्षम बनाते हैं।

Agents SDK में संरचित आउटपुट कैसे काम करते हैं?

संरचित आउटपुट Pydantic मॉडलों का उपयोग करते हैं ताकि आप ठीक वही डेटा संरचना परिभाषित कर सकें जो आप अपने एजेंट से लौटाना चाहते हैं। एजेंट बनाते समय output_type पैरामीटर सेट करके, आपको मुक्त-रूप टेक्स्ट के बजाय ठीक से फ़ॉर्मैट किए गए डेटा ऑब्जेक्ट्स मिलते हैं। इससे एप्लिकेशन अधिक विश्वसनीय होते हैं और एजेंट प्रतिक्रियाओं की मैनुअल पार्सिंग की आवश्यकता समाप्त हो जाती है।

हैंडऑफ्स और एजेंट-एज़-टूल्स में क्या अंतर है?

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

OpenAI Agents SDK में कौन-सी उन्नत सुविधाएँ उपलब्ध हैं?

कोर फंक्शनैलिटी से आगे, SDK रीयल-टाइम अपडेट्स के लिए स्ट्रीमिंग, डीबगिंग और ऑब्ज़र्वेबिलिटी के लिए ट्रेसिंग, जटिल वर्कफ़्लोज़ के लिए मल्टी-एजेंट ऑर्केस्ट्रेशन, वार्तालाप स्थिति बनाए रखने के लिए संदर्भ प्रबंधन, और सुरक्षित एजेंट व्यवहार सुनिश्चित करने के लिए गार्डरेइल्स जैसी सुविधाएँ प्रदान करता है। ये क्षमताएँ डेवलपर्स को परिष्कृत, प्रोडक्शन-रेडी एजेंट सिस्टम बनाने में मदद करती हैं।


Bexruz (Bex) Tuychiev's photo
Author
Bexruz (Bex) Tuychiev
LinkedIn

मैं 2 से अधिक वर्षों के अनुभव वाला डेटा साइंस कंटेंट क्रिएटर हूँ और Medium पर सबसे बड़े फॉलोइंग्स में से एक रखता हूँ। मुझे एआई और एमएल पर विस्तार से लेख लिखना पसंद है, जिसमें हल्का-सा व्यंग्यात्मक अंदाज रहता है—क्योंकि कुछ तो करना पड़ता है ताकि वे कम उबाऊ लगें। मैंने 130 से अधिक लेख और एक DataCamp कोर्स तैयार किया है, और एक और बन रहा है। मेरा कंटेंट 50 लाख से अधिक लोगों ने देखा है, जिनमें से 20 हज़ार लोग Medium और LinkedIn पर फॉलोअर्स बन गए। 

विषय
एआई एजेंट्स
OpenAI
कृत्रिम बुद्धिमत्ता

शीर्ष DataCamp कोर्स

कोर्स

OpenAI API के साथ काम करना

3 घंटा
181.9K
OpenAI API के साथ AI-संचालित एप्लिकेशन विकसित करना शुरू करें। ChatGPT जैसे लोकप्रिय AI अनुप्रयोगों के पीछे की कार्यक्षमता के बारे में जानें।
विवरण देखेंRight Arrow
पाठ्यक्रम शुरू करें
और देखेंRight Arrow