AI एजेंट · पाठ

साझा किए जा सकने वाले एजेंट टूल डिज़ाइन करना

पुनः उपयोग के लिए टूल स्कीमा मानक, दस्तावेज़ीकरण आवश्यकताएँ और पैकेजिंग।

पाठ 1, कुल 4 में से13 चरण

साझा किए जा सकने वाले एजेंट टूल डिज़ाइन करना, CoddyKit पर AI एजेंट का एक निःशुल्क पाठ है। यह 4 में से 1वाँ पाठ है। आप नीचे पूरा पाठ निःशुल्क पढ़ सकते हैं—फिर अंतर्निहित कोड संपादक और 24/7 एआई ट्यूटर के साथ ब्राउज़र में इसका व्यावहारिक अभ्यास कर सकते हैं। यह AI एजेंट सीखने के मार्ग का हिस्सा है और आपकी प्रगति वेब तथा CoddyKit ऐप पर सिंक होती रहती है। AI एजेंट पाठ्यक्रम में कुल 4 पाठ शामिल हैं।

किसी टूल को साझा करने योग्य क्या बनाता है

साझा करने योग्य एजेंट टूल ऐसा टूल है जिसे अन्य डेवलपर उसका स्रोत कोड पढ़े बिना अपने एजेंट सिस्टम में जोड़ सकते हैं। इसमें स्पष्ट, मशीन-पठनीय स्कीमा, मानव-पठनीय README, अच्छी तरह परिभाषित त्रुटि कोड और अनुमानित व्यवहार होता है। इसे स्क्रिप्ट नहीं, बल्कि लाइब्रेरी समझें।

टूल स्कीमा मानक

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

TOOL_SCHEMA_TEMPLATE = {
    'name': 'get_weather',
    'description': 'Returns current weather conditions for a city. '
                   'Use when the user asks about weather or temperature.',
    'version': '1.2.0',
    'parameters': {
        'type': 'object',
        'properties': {
            'city': {
                'type': 'string',
                'description': 'City name (e.g., London, Tokyo)',
                'minLength': 1,
                'maxLength': 100
            },
            'units': {
                'type': 'string',
                'enum': ['celsius', 'fahrenheit'],
                'default': 'celsius',
                'description': 'Temperature unit'
            }
        },
        'required': ['city']
    },
    'returns': {
        'type': 'object',
        'properties': {
            'temperature': {'type': 'number'},
            'condition': {'type': 'string'},
            'humidity_pct': {'type': 'number'}
        }
    },
    'rate_limit': {'calls_per_minute': 60}
}

if __name__ == '__main__':
    print(f"Tool: {TOOL_SCHEMA_TEMPLATE['name']} (v{TOOL_SCHEMA_TEMPLATE['version']})")
    print('Description:', TOOL_SCHEMA_TEMPLATE['description'])
    print('Required params:', TOOL_SCHEMA_TEMPLATE['parameters']['required'])

त्रुटि कोड

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

from enum import Enum

class ToolErrorCode(Enum):
    INVALID_PARAMS = 'INVALID_PARAMS'
    NOT_FOUND = 'NOT_FOUND'
    RATE_LIMITED = 'RATE_LIMITED'
    UPSTREAM_ERROR = 'UPSTREAM_ERROR'
    TIMEOUT = 'TIMEOUT'
    UNAUTHORISED = 'UNAUTHORISED'
    INTERNAL_ERROR = 'INTERNAL_ERROR'

class ToolError(Exception):
    def __init__(self, code: ToolErrorCode, message: str, details: dict = None):
        self.code = code
        self.message = message
        self.details = details or {}

    def to_dict(self) -> dict:
        return {
            'error': True,
            'code': self.code.value,
            'message': self.message,
            'details': self.details
        }

try:
    raise ToolError(
        ToolErrorCode.NOT_FOUND,
        'City not found in database',
        {'city': 'Atlantis', 'suggestion': 'Did you mean Athens?'}
    )
except ToolError as e:
    print(e.to_dict())

इनपुट सत्यापन

निष्पादन से पहले स्कीमा के अनुसार इनपुट का सत्यापन करें। स्वचालित सत्यापन के लिए jsonschema का उपयोग करें। अमान्य इनपुट को टूल के तर्क में गहराई तक जाकर अस्पष्ट विफलताएँ पैदा करने देने के बजाय, स्पष्ट त्रुटि के साथ तुरंत विफल हों।

import jsonschema  # pip install jsonschema

def validate_tool_input(params: dict, schema: dict) -> dict:
    """
    Validate params against schema.
    Returns validated (and default-filled) params.
    Raises ToolError on validation failure.
    """
    try:
        # Fill in defaults
        filled = dict(params)
        for prop, definition in schema['properties'].items():
            if prop not in filled and 'default' in definition:
                filled[prop] = definition['default']

        # Validate against schema
        jsonschema.validate(instance=filled, schema=schema)
        return filled

    except jsonschema.ValidationError as e:
        raise ToolError(
            ToolErrorCode.INVALID_PARAMS,
            f'Validation failed: {e.message}',
            {'path': list(e.path), 'schema_path': list(e.schema_path)}
        )

# Example usage:
try:
    params = validate_tool_input({'city': 'London'}, TOOL_SCHEMA_TEMPLATE['parameters'])
    print('Valid params:', params)
except ToolError as e:
    print('Error:', e.to_dict())

स्कीमा में उपयोग के उदाहरण

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

TOOL_WITH_EXAMPLES = {
    'name': 'search_knowledge_base',
    'description': 'Search the company knowledge base for documentation.',
    'parameters': {
        'type': 'object',
        'properties': {
            'query': {'type': 'string'},
            'top_k': {'type': 'integer', 'default': 5, 'minimum': 1, 'maximum': 20}
        },
        'required': ['query']
    },
    'examples': [
        {
            'description': 'Search for onboarding docs',
            'input': {'query': 'how to onboard new users', 'top_k': 3},
            'output': {'results': [{'title': 'User Onboarding Guide', 'score': 0.95}]}
        },
        {
            'description': 'Search with default top_k',
            'input': {'query': 'API authentication'},
            'output': {'results': [{'title': 'API Auth Docs', 'score': 0.88}]}
        }
    ]
}

if __name__ == '__main__':
    print('Tool:', TOOL_WITH_EXAMPLES['name'])
    for ex in TOOL_WITH_EXAMPLES['examples']:
        print(f" - {ex['description']}: input={ex['input']} -> output={ex['output']}")

टूल में दर-सीमा निर्धारण

बाहरी एपीआई कॉल करने वाले टूल को दर-सीमाओं का पालन करना चाहिए। टोकन बकेट या स्लाइडिंग विंडो का उपयोग करके प्रति-टूल दर-सीमा निर्धारक लागू करें। सीमा पार होने पर पुनःप्रयास के लिए बचे सेकंड के साथ मानक RATE_LIMITED त्रुटि लौटाएँ।

import time
from collections import deque

class SlidingWindowRateLimiter:
    def __init__(self, max_calls: int, window_seconds: int):
        self.max_calls = max_calls
        self.window = window_seconds
        self._calls = deque()  # timestamps of recent calls

    def check(self) -> tuple:
        """
        Returns (allowed: bool, retry_after_seconds: float)
        """
        now = time.time()
        # Remove calls outside the window
        while self._calls and self._calls[0] < now - self.window:
            self._calls.popleft()

        if len(self._calls) >= self.max_calls:
            oldest = self._calls[0]
            retry_after = (oldest + self.window) - now
            return False, round(retry_after, 1)

        self._calls.append(now)
        return True, 0.0

weather_limiter = SlidingWindowRateLimiter(max_calls=10, window_seconds=60)
allowed, retry = weather_limiter.check()
if not allowed:
    raise ToolError(ToolErrorCode.RATE_LIMITED,
                    f'Rate limit exceeded. Retry in {retry}s',
                    {'retry_after': retry})

पाइथन पैकेज के रूप में पैकेजिंग

अपने टूल को इंस्टॉल किए जा सकने वाले पाइथन पैकेज के रूप में संरचित करें, ताकि अन्य डेवलपर एक ही pip install कमांड से इसे अपने एजेंट में जोड़ सकें। पैकेज सार्वजनिक एपीआई के रूप में get_tool_definition() फ़ंक्शन और execute(params) फ़ंक्शन उपलब्ध कराता है।

# Directory structure:
# agent_tool_weather/
#   __init__.py
#   tool.py
#   schema.py
#   pyproject.toml
#   README.md

# agent_tool_weather/tool.py
from .schema import SCHEMA
from .errors import ToolError, ToolErrorCode

def get_tool_definition() -> dict:
    return SCHEMA

def execute(params: dict) -> dict:
    validated = validate_tool_input(params, SCHEMA['parameters'])
    city = validated['city']
    units = validated['units']
    return _fetch_weather(city, units)

def _fetch_weather(city: str, units: str) -> dict:
    import requests
    url = f'https://api.weather.example.com/current?city={city}&units={units}'
    response = requests.get(url, headers={'X-API-Key': 'YOUR_KEY'}, timeout=5)
    if response.status_code == 404:
        raise ToolError(ToolErrorCode.NOT_FOUND, f'City not found: {city}')
    response.raise_for_status()
    return response.json()

टूल README लिखना

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

README_TEMPLATE = '''
# agent-tool-weather

Get real-time weather conditions for any city.

## Installation

pip install agent-tool-weather

## Setup

import os
os.environ["WEATHER_API_KEY"] = "your-key-here"

## Usage

from agent_tool_weather import get_tool_definition, execute

# In your agent
tool_def = get_tool_definition()

# Execute
result = execute({"city": "Tokyo", "units": "celsius"})
print(result)
# {"temperature": 22.5, "condition": "Partly cloudy", "humidity_pct": 65}

## Parameters

| Name  | Type   | Required | Default  | Description     |
|-------|--------|----------|----------|-----------------|
| city  | string | Yes      | -        | City name       |
| units | string | No       | celsius  | celsius or fahrenheit |

## Error Codes

- INVALID_PARAMS: Parameter validation failed
- NOT_FOUND: City not found
- RATE_LIMITED: 60 calls/minute limit exceeded
- UPSTREAM_ERROR: Weather API unavailable
'''

print(README_TEMPLATE[:300])

साझा करने योग्य टूल का परीक्षण

साझा करने योग्य टूल में स्वचालित परीक्षण होने चाहिए, जिनमें सामान्य सफल पथ, प्रत्येक त्रुटि कोड, सीमांत स्थितियाँ (खाली स्ट्रिंग, अधिकतम मान) और दर-सीमा निर्धारण का व्यवहार शामिल हो। परीक्षण दस्तावेज़ीकरण होते हैं — वे ठीक-ठीक दिखाते हैं कि टूल कैसे व्यवहार करता है।

import pytest

def test_valid_city_returns_weather(mock_weather_api):
    result = execute({'city': 'London'})
    assert 'temperature' in result
    assert 'condition' in result
    assert isinstance(result['temperature'], (int, float))

def test_missing_required_param_raises_error():
    with pytest.raises(ToolError) as exc_info:
        execute({})  # city is required
    assert exc_info.value.code == ToolErrorCode.INVALID_PARAMS

def test_unknown_city_raises_not_found(mock_weather_api_404):
    with pytest.raises(ToolError) as exc_info:
        execute({'city': 'Atlantis'})
    assert exc_info.value.code == ToolErrorCode.NOT_FOUND

def test_default_units_is_celsius():
    params = validate_tool_input({'city': 'Paris'}, TOOL_SCHEMA_TEMPLATE['parameters'])
    assert params['units'] == 'celsius'

def test_rate_limit_enforced():
    limiter = SlidingWindowRateLimiter(max_calls=2, window_seconds=60)
    limiter.check()  # call 1
    limiter.check()  # call 2
    allowed, _ = limiter.check()  # call 3 — should fail
    assert not allowed

OpenAI फ़ंक्शन-कॉलिंग-संगत प्रारूप

OpenAI और Claude के मूल टूल-उपयोग एपीआई के साथ संगतता के लिए सुनिश्चित करें कि आपका टूल स्कीमा ठीक उसी प्रारूप में हो जिसकी वे एपीआई अपेक्षा करती हैं। get_openai_schema() मेथड आपके आंतरिक स्कीमा को OpenAI-संगत प्रारूप में बदलता है।

def get_openai_schema(tool_schema: dict) -> dict:
    """Convert internal tool schema to OpenAI function-calling format."""
    return {
        'type': 'function',
        'function': {
            'name': tool_schema['name'],
            'description': tool_schema['description'],
            'parameters': tool_schema['parameters']
        }
    }

def get_anthropic_schema(tool_schema: dict) -> dict:
    """Convert to Anthropic tool format."""
    return {
        'name': tool_schema['name'],
        'description': tool_schema['description'],
        'input_schema': tool_schema['parameters']
    }

# Usage in an agent:
openai_tools = [get_openai_schema(t) for t in [TOOL_SCHEMA_TEMPLATE]]
anthropic_tools = [get_anthropic_schema(t) for t in [TOOL_SCHEMA_TEMPLATE]]
print('OpenAI format:', openai_tools[0]['function']['name'])
print('Anthropic format:', anthropic_tools[0]['name'])

अपने टूल का संस्करण निर्धारण

सिमेंटिक वर्ज़निंग का उपयोग करें: MAJOR.MINOR.PATCH। स्कीमा में असंगत बदलाव होने पर MAJOR बढ़ाएँ, वैकल्पिक पैरामीटर जोड़ने पर MINOR और बग ठीक करने पर PATCH बढ़ाएँ। संस्करण को स्कीमा में संग्रहीत करें और get_tool_definition() के माध्यम से उपलब्ध कराएँ।

VERSION = '1.2.0'

def bump_version(current: str, change_type: str) -> str:
    parts = list(map(int, current.split('.')))
    if change_type == 'major':
        return f'{parts[0]+1}.0.0'
    if change_type == 'minor':
        return f'{parts[0]}.{parts[1]+1}.0'
    if change_type == 'patch':
        return f'{parts[0]}.{parts[1]}.{parts[2]+1}'
    raise ValueError(f'Unknown change_type: {change_type}')

# Breaking change (removed required param) -> major
print(bump_version('1.2.0', 'major'))  # 2.0.0
# Added optional param -> minor
print(bump_version('1.2.0', 'minor'))  # 1.3.0
# Bug fix -> patch
print(bump_version('1.2.0', 'patch'))  # 1.2.1

ज्ञान-जाँच

साझा करने योग्य टूल स्कीमा का कौन-सा भाग एजेंट फ़्रेमवर्क को टूल के निष्पादन फ़ंक्शन को कॉल करने से पहले इनपुट का स्वचालित रूप से सत्यापन करने देता है?

पुनरावलोकन: साझा करने योग्य एजेंट टूल का डिज़ाइन

इस पाठ की मुख्य बातें:

  • स्कीमा: नाम, विवरण, संस्करण, पैरामीटर (JSON स्कीमा), लौटाए गए मान, दर_सीमा
  • त्रुटि कोड: कोड, संदेश और विवरण वाला मानक ToolError
  • इनपुट सत्यापन: jsonschema निष्पादन से पहले पैरामीटर स्कीमा के अनुसार सत्यापन करता है
  • उदाहरण: कुछ-शॉट संदर्भ के रूप में स्कीमा में शामिल
  • दर-सीमा निर्धारण: RATE_LIMITED त्रुटि और पुनःप्रयास_के_बाद के साथ स्लाइडिंग विंडो
  • पैकेजिंग: README, परीक्षणों और संस्करण निर्धारण वाला pip से इंस्टॉल किया जा सकने वाला पैकेज

अगला विषय: प्लगइन की खोज और डायनेमिक टूल लोडिंग।

शुरुआत निःशुल्क

एआई शिक्षक के साथ AI एजेंट सीखें — निःशुल्क

अपने ब्राउज़र में वास्तविक कोड लिखें और चलाएँ, चौबीसों घंटे एआई शिक्षक से तुरंत सहायता पाएँ, और वेब या ऐप पर वहीं से शुरू करें जहाँ आपने छोड़ा था।

पाठ्यक्रम
60
पाठ
239

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

क्या “साझा किए जा सकने वाले एजेंट टूल डिज़ाइन करना” पाठ निःशुल्क है?

हाँ—“साझा किए जा सकने वाले एजेंट टूल डिज़ाइन करना” का पूरा पाठ यहाँ वेब पर निःशुल्क पढ़ा जा सकता है। इंटरैक्टिव अभ्यास (अंतर्निहित कोड संपादक और 24/7 एआई ट्यूटर) करने और AI एजेंट पाठ्यक्रम का बाकी हिस्सा अनलॉक करने के लिए CoddyKit PRO लें। AI एजेंट पाठ्यक्रम में कुल 4 पाठ शामिल हैं।

“साझा किए जा सकने वाले एजेंट टूल डिज़ाइन करना” में मैं क्या सीखूँगा?

पुनः उपयोग के लिए टूल स्कीमा मानक, दस्तावेज़ीकरण आवश्यकताएँ और पैकेजिंग। आप ब्राउज़र में सीधे चलाए जाने वाले व्यावहारिक कोड के साथ AI एजेंट का अभ्यास करते हैं, और पाठ पूरा करते समय 24/7 एआई ट्यूटर आपके प्रश्नों के उत्तर देता है।

क्या AI एजेंट शुरू करने के लिए मुझे किसी अनुभव की आवश्यकता है?

पहले के अनुभव की आवश्यकता नहीं है। CoddyKit पर AI एजेंट शुरुआती से लेकर उन्नत शिक्षार्थियों तक सभी के लिए व्यवस्थित किया गया है, इसलिए आप यहीं से या शुरुआत से सीखना शुरू कर सकते हैं और अपनी गति से आगे बढ़ सकते हैं। यह 4 में से 1वाँ पाठ है।

“साझा किए जा सकने वाले एजेंट टूल डिज़ाइन करना” पाठ पूरा करने में कितना समय लगता है?

CoddyKit का अधिकांश पाठ लगभग 5–10 मिनट में पूरा हो जाता है। हर पाठ छोटा और संवादात्मक है, इसलिए आप लगातार प्रगति करते हैं और वेब या ऐप पर वहीं से सीखना जारी रख सकते हैं जहाँ आपने छोड़ा था।

क्या मैं इस AI एजेंट पाठ में कोड लिख और चला सकता हूँ?

हाँ। हर AI एजेंट पाठ में एक अंतर्निर्मित कोड संपादक शामिल है, जिससे आप सीधे अपने ब्राउज़र में वास्तविक कोड लिख और चला सकते हैं और तुरंत एआई प्रतिक्रिया पा सकते हैं—स्थानीय सेटअप की आवश्यकता नहीं है।

इस पाठ्यक्रम के सभी पाठ

  1. साझा किए जा सकने वाले एजेंट टूल डिज़ाइन करना
  2. प्लगइन खोज और पंजीकरण
  3. टूल संस्करण-निर्धारण और संगतता
  4. एजेंट प्लगइन बाज़ार बनाना
← AI एजेंट पर वापस जाएँ