بخش ۰۲: فراخوانی توابع در مدل‌های زبان کوچک (SLMs)

January 29, 2026 · View on GitHub

فهرست مطالب

  1. فراخوانی توابع چیست؟
  2. نحوه عملکرد فراخوانی توابع
  3. سناریوهای کاربردی
  4. راه‌اندازی فراخوانی توابع با Phi-4-mini و Ollama
  5. کار با فراخوانی توابع Qwen3
  6. یکپارچه‌سازی محلی Foundry
  7. بهترین روش‌ها و رفع مشکلات
  8. مثال‌های پیشرفته

فراخوانی توابع چیست؟

فراخوانی توابع یک قابلیت قدرتمند است که به مدل‌های زبان کوچک (SLMs) اجازه می‌دهد با ابزارها، APIها و سرویس‌های خارجی تعامل داشته باشند. به جای محدود شدن به داده‌های آموزشی خود، SLMها اکنون می‌توانند:

  • اتصال به APIهای خارجی (سرویس‌های آب‌وهوا، پایگاه‌های داده، موتورهای جستجو)
  • اجرای توابع خاص بر اساس درخواست‌های کاربران
  • دریافت اطلاعات لحظه‌ای از منابع مختلف
  • انجام وظایف محاسباتی از طریق ابزارهای تخصصی
  • زنجیره‌سازی عملیات متعدد برای جریان‌های کاری پیچیده

این قابلیت، SLMها را از تولیدکننده‌های متن ایستا به عامل‌های هوش مصنوعی پویا تبدیل می‌کند که قادر به انجام وظایف واقعی هستند.

نحوه عملکرد فراخوانی توابع

فرآیند فراخوانی توابع یک جریان کاری سیستماتیک را دنبال می‌کند:

۱. یکپارچه‌سازی ابزارها

  • ابزارهای خارجی: SLMها می‌توانند به APIهای آب‌وهوا، پایگاه‌های داده، سرویس‌های وب و سیستم‌های خارجی دیگر متصل شوند.
  • تعریف توابع: هر ابزار با پارامترهای خاص، قالب‌های ورودی/خروجی و توضیحات تعریف می‌شود.
  • سازگاری API: ابزارها از طریق رابط‌های استاندارد (مانند REST APIها، SDKها و غیره) یکپارچه می‌شوند.

۲. تعریف توابع

توابع با سه مؤلفه کلیدی تعریف می‌شوند:

{
  "name": "function_name",
  "description": "Clear description of what the function does",
  "parameters": {
    "parameter_name": {
      "description": "What this parameter represents",
      "type": "data_type",
      "default": "default_value"
    }
  }
}

۳. تشخیص قصد

  • پردازش زبان طبیعی: SLM ورودی کاربر را برای درک قصد تحلیل می‌کند.
  • تطبیق توابع: تعیین می‌کند که کدام تابع(ها) برای برآورده کردن درخواست لازم است.
  • استخراج پارامترها: پارامترهای مورد نیاز را از پیام کاربر شناسایی و استخراج می‌کند.

۴. تولید خروجی JSON

SLM یک JSON ساختاری تولید می‌کند که شامل موارد زیر است:

  • نام تابع برای فراخوانی
  • پارامترهای مورد نیاز با مقادیر مناسب
  • زمینه اجرا و متاداده‌ها

۵. اجرای خارجی

  • اعتبارسنجی پارامترها: اطمینان حاصل می‌کند که تمام پارامترهای مورد نیاز موجود و به درستی قالب‌بندی شده‌اند.
  • اجرای تابع: برنامه تابع مشخص شده را با پارامترهای ارائه شده اجرا می‌کند.
  • مدیریت خطا: شکست‌ها، زمان‌های انتظار و پاسخ‌های نامعتبر را مدیریت می‌کند.

۶. یکپارچه‌سازی پاسخ

  • پردازش نتیجه: خروجی تابع به SLM بازگردانده می‌شود.
  • یکپارچه‌سازی زمینه: SLM نتایج را در پاسخ خود ادغام می‌کند.
  • ارتباط با کاربر: اطلاعات را به صورت طبیعی و مکالمه‌ای ارائه می‌دهد.

سناریوهای کاربردی

بازیابی داده‌ها

تبدیل پرسش‌های زبان طبیعی به درخواست‌های API ساختاریافته:

  • "سفارش‌های اخیرم را نشان بده" → پرسش پایگاه داده با شناسه کاربر و فیلترهای تاریخ
  • "آب‌وهوای توکیو چطور است؟" → فراخوانی API آب‌وهوا با پارامتر مکان
  • "ایمیل‌های جان از هفته گذشته را پیدا کن" → پرسش سرویس ایمیل با فرستنده و فیلترهای تاریخ

اجرای عملیات

تبدیل درخواست‌های کاربر به فراخوانی توابع خاص:

  • "یک جلسه برای فردا ساعت ۲ بعدازظهر برنامه‌ریزی کن" → یکپارچه‌سازی API تقویم
  • "یک پیام به تیم ارسال کن" → API پلتفرم ارتباطی
  • "از فایل‌هایم نسخه پشتیبان تهیه کن" → عملیات سیستم فایل

وظایف محاسباتی

مدیریت عملیات پیچیده ریاضی یا منطقی:

  • "بهره مرکب را برای ۱۰,۰۰۰ دلار با نرخ ۵٪ به مدت ۱۰ سال محاسبه کن" → تابع محاسبات مالی
  • "این مجموعه داده را برای روندها تحلیل کن" → ابزارهای تحلیل آماری
  • "این مسیر را برای تحویل بهینه کن" → الگوریتم‌های بهینه‌سازی مسیر

جریان‌های کاری پردازش داده‌ها

زنجیره‌سازی چندین فراخوانی تابع برای عملیات پیچیده:

  1. بازیابی داده‌ها از منابع مختلف
  2. تجزیه و اعتبارسنجی اطلاعات
  3. تبدیل داده‌ها به قالب مورد نیاز
  4. ذخیره نتایج در سیستم‌های مناسب
  5. تولید گزارش‌ها یا تجسم‌ها

یکپارچه‌سازی UI/UX

امکان به‌روزرسانی‌های پویا در رابط کاربری:

  • "داده‌های فروش را روی داشبورد نشان بده" → تولید و نمایش نمودار
  • "نقشه را با مکان‌های جدید به‌روزرسانی کن" → یکپارچه‌سازی داده‌های جغرافیایی
  • "نمایش موجودی را تازه‌سازی کن" → همگام‌سازی داده‌های لحظه‌ای

راه‌اندازی فراخوانی توابع با Phi-4-mini و Ollama

Phi-4-mini مایکروسافت از فراخوانی توابع تک و موازی از طریق Ollama پشتیبانی می‌کند. در اینجا نحوه راه‌اندازی آن آمده است:

پیش‌نیازها

  • نسخه Ollama 0.5.13 یا بالاتر
  • مدل Phi-4-mini (توصیه شده: phi4-mini:3.8b-fp16)

مراحل نصب

۱. نصب و اجرای Phi-4-mini

# Download the model (if not already present)
ollama run phi4-mini:3.8b-fp16

# Verify the model is available
ollama list

۲. ایجاد قالب ModelFile سفارشی

به دلیل محدودیت‌های فعلی در قالب‌های پیش‌فرض Ollama، باید یک ModelFile سفارشی با قالب زیر ایجاد کنید:

TEMPLATE """
{{- if .Messages }}
{{- if or .System .Tools }}<|system|>
{{ if .System }}{{ .System }}
{{- end }}
In addition to plain text responses, you can chose to call one or more of the provided functions.
Use the following rule to decide when to call a function:
* if the response can be generated from your internal knowledge (e.g., as in the case of queries like "What is the capital of Poland?"), do so
* if you need external information that can be obtained by calling one or more of the provided functions, generate a function calls
If you decide to call functions:
* prefix function calls with functools marker (no closing marker required)
* all function calls should be generated in a single JSON list formatted as functools[{"name": [function name], "arguments": [function arguments as JSON]}, ...]
* follow the provided JSON schema. Do not hallucinate arguments or values. Do to blindly copy values from the provided samples
* respect the argument type formatting. E.g., if the type if number and format is float, write value 7 as 7.0
* make sure you pick the right functions that match the user intent
Available functions as JSON spec:
{{- if .Tools }}
{{ .Tools }}
{{- end }}<|end|>
{{- end }}
{{- range .Messages }}
{{- if ne .Role "system" }}<|{{ .Role }}|>
{{- if and .Content (eq .Role "tools") }}
{"result": {{ .Content }}}
{{- else if .Content }}
{{ .Content }}
{{- else if .ToolCalls }}
functools[
{{- range .ToolCalls }}{{ "{" }}"name": "{{ .Function.Name }}", "arguments": {{ .Function.Arguments }}{{ "}" }}
{{- end }}]
{{- end }}<|end|>
{{- end }}
{{- end }}<|assistant|>
{{ else }}
{{- if .System }}<|system|>
{{ .System }}<|end|>{{ end }}{{ if .Prompt }}<|user|>
{{ .Prompt }}<|end|>{{ end }}<|assistant|>
{{ end }}{{ .Response }}{{ if .Response }}<|user|>{{ end }}
"""

۳. ایجاد مدل سفارشی

# Save the template above as 'Modelfile' and run:
ollama create phi4-mini-fc:3.8b-fp16 -f ./Modelfile

مثال فراخوانی تابع تک

import json
import requests

# Define the tool/function
tools = [
    {
        "name": "get_weather",
        "description": "Get current weather information for a location",
        "parameters": {
            "location": {
                "description": "The city or location name",
                "type": "str",
                "default": "New York"
            },
            "units": {
                "description": "Temperature units (celsius or fahrenheit)",
                "type": "str",
                "default": "celsius"
            }
        }
    }
]

# Create the message with system prompt including tools
messages = [
    {
        "role": "system",
        "content": "You are a helpful weather assistant",
        "tools": json.dumps(tools)
    },
    {
        "role": "user",
        "content": "What's the weather like in London today?"
    }
]

# Make request to Ollama API
response = requests.post(
    "http://localhost:11434/api/chat",
    json={
        "model": "phi4-mini-fc:3.8b-fp16",
        "messages": messages,
        "stream": False
    }
)

print(response.json())

مثال فراخوانی تابع موازی

import json
import requests

# Define multiple tools for parallel execution
AGENT_TOOLS = {
    "booking_flight": {
        "name": "booking_flight",
        "description": "Book a flight ticket",
        "parameters": {
            "departure": {
                "description": "Departure airport code",
                "type": "str"
            },
            "destination": {
                "description": "Destination airport code", 
                "type": "str"
            },
            "outbound_date": {
                "description": "Departure date (YYYY-MM-DD)",
                "type": "str"
            },
            "return_date": {
                "description": "Return date (YYYY-MM-DD)",
                "type": "str"
            }
        }
    },
    "booking_hotel": {
        "name": "booking_hotel",
        "description": "Book a hotel room",
        "parameters": {
            "city": {
                "description": "City name for hotel booking",
                "type": "str"
            },
            "check_in_date": {
                "description": "Check-in date (YYYY-MM-DD)",
                "type": "str"
            },
            "check_out_date": {
                "description": "Check-out date (YYYY-MM-DD)",
                "type": "str"
            }
        }
    }
}

SYSTEM_PROMPT = """
You are my travel agent with some tools available.
"""

messages = [
    {
        "role": "system",
        "content": SYSTEM_PROMPT,
        "tools": json.dumps(AGENT_TOOLS)
    },
    {
        "role": "user", 
        "content": "I need to travel from London to New York from March 21 2025 to March 27 2025. Please book both flight and hotel."
    }
]

# The model will generate parallel function calls
response = requests.post(
    "http://localhost:11434/api/chat",
    json={
        "model": "phi4-mini-fc:3.8b-fp16",
        "messages": messages,
        "stream": False
    }
)

print(response.json())

کار با فراخوانی توابع Qwen3

Qwen3 قابلیت‌های پیشرفته فراخوانی توابع را با عملکرد و انعطاف‌پذیری عالی ارائه می‌دهد. در اینجا نحوه پیاده‌سازی آن آمده است:

استفاده از چارچوب Qwen-Agent

Qwen-Agent یک چارچوب سطح بالا ارائه می‌دهد که پیاده‌سازی فراخوانی توابع را ساده می‌کند:

نصب

pip install -U "qwen-agent[gui,rag,code_interpreter,mcp]"

تنظیمات اولیه

import os
from qwen_agent.agents import Assistant

# Configure the LLM
llm_cfg = {
    'model': 'Qwen3-8B',
    # Option 1: Use Alibaba Model Studio
    'model_type': 'qwen_dashscope',
    'api_key': os.getenv('DASHSCOPE_API_KEY'),
    
    # Option 2: Use local deployment
    # 'model_server': 'http://localhost:8000/v1',
    # 'api_key': 'EMPTY',
    
    # Optional configuration for thinking mode
    'generate_cfg': {
        'thought_in_content': True,  # Include reasoning in response
    }
}

# Define tools using MCP (Model Context Protocol)
tools = [
    {
        'mcpServers': {
            'time': {
                'command': 'uvx',
                'args': ['mcp-server-time', '--local-timezone=Asia/Shanghai']
            },
            'fetch': {
                'command': 'uvx', 
                'args': ['mcp-server-fetch']
            }
        }
    },
    'code_interpreter',  # Built-in code execution tool
]

# Create the assistant
bot = Assistant(llm=llm_cfg, function_list=tools)

# Example usage
messages = [
    {
        'role': 'user', 
        'content': 'What time is it now? Also, fetch the latest news from https://example.com/news'
    }
]

# Generate response with function calling
for response in bot.run(messages=messages):
    print(response)

پیاده‌سازی توابع سفارشی

می‌توانید توابع سفارشی برای Qwen3 تعریف کنید:

import json
from qwen_agent.tools.base import BaseTool

class WeatherTool(BaseTool):
    description = 'Get weather information for a specific location'
    parameters = [
        {
            'name': 'location',
            'type': 'string', 
            'description': 'City or location name',
            'required': True
        },
        {
            'name': 'units',
            'type': 'string',
            'description': 'Temperature units (celsius or fahrenheit)',
            'required': False,
            'default': 'celsius'
        }
    ]
    
    def call(self, params: str, **kwargs) -> str:
        """Execute the weather lookup"""
        params_dict = json.loads(params)
        location = params_dict.get('location')
        units = params_dict.get('units', 'celsius')
        
        # Simulate weather API call
        weather_data = {
            'location': location,
            'temperature': '22°C' if units == 'celsius' else '72°F',
            'condition': 'Partly cloudy',
            'humidity': '65%'
        }
        
        return json.dumps(weather_data)

# Use the custom tool
tools = [WeatherTool()]
bot = Assistant(llm=llm_cfg, function_list=tools)

messages = [{'role': 'user', 'content': 'What\'s the weather in Tokyo?'}]
response = bot.run(messages=messages)
print(list(response)[-1])

ویژگی‌های پیشرفته Qwen3

کنترل حالت تفکر

Qwen3 از تغییر پویا بین حالت‌های تفکر و غیرتفکر پشتیبانی می‌کند:

# Enable thinking mode for complex reasoning
messages = [
    {
        'role': 'user',
        'content': '/think Solve this complex math problem: If a train travels 120 km in 1.5 hours, and another train travels 200 km in 2.5 hours, which train is faster and by how much?'
    }
]

# Disable thinking mode for simple queries
messages = [
    {
        'role': 'user', 
        'content': '/no_think What is the capital of France?'
    }
]

فراخوانی توابع چندمرحله‌ای

Qwen3 در زنجیره‌سازی چندین فراخوانی تابع عالی عمل می‌کند:

# Complex workflow example
messages = [
    {
        'role': 'user',
        'content': '''
        I need to prepare for a business meeting:
        1. Check my calendar for conflicts tomorrow
        2. Get weather forecast for the meeting location (San Francisco)
        3. Find recent news about the client company (TechCorp)
        4. Calculate travel time from my office to their headquarters
        '''
    }
]

# Qwen3 will automatically determine the sequence of function calls needed

یکپارچه‌سازی محلی Foundry

Foundry Local مایکروسافت یک API سازگار با OpenAI برای اجرای مدل‌ها به صورت محلی با حفظ حریم خصوصی و عملکرد بهبود یافته ارائه می‌دهد.

راه‌اندازی و نصب

ویندوز

نصب‌کننده را از صفحه انتشار Foundry Local دانلود کرده و دستورالعمل‌های نصب را دنبال کنید.

macOS

brew tap microsoft/foundrylocal
brew install foundrylocal

استفاده اولیه

import openai
from foundry_local import FoundryLocalManager

# Initialize with model alias
alias = "phi-3.5-mini"  # Or any supported model
manager = FoundryLocalManager(alias)

# Create OpenAI client pointing to local endpoint
client = openai.OpenAI(
    base_url=manager.endpoint,
    api_key=manager.api_key
)

# Define functions for the model
functions = [
    {
        "name": "calculate_tax",
        "description": "Calculate tax amount based on income and rate",
        "parameters": {
            "type": "object",
            "properties": {
                "income": {
                    "type": "number",
                    "description": "Annual income amount"
                },
                "tax_rate": {
                    "type": "number", 
                    "description": "Tax rate as decimal (e.g., 0.25 for 25%)"
                }
            },
            "required": ["income", "tax_rate"]
        }
    }
]

# Make function calling request
response = client.chat.completions.create(
    model=manager.model_info.id,
    messages=[
        {
            "role": "user",
            "content": "Calculate the tax for someone earning \$75,000 with a 22% tax rate"
        }
    ],
    functions=functions,
    function_call="auto"
)

print(response.choices[0].message.content)

ویژگی‌های پیشرفته Foundry Local

مدیریت مدل

# List available models
foundry model list

# Download specific model
foundry model download phi-3.5-mini

# Run model interactively
foundry model run phi-3.5-mini

# Remove model from cache
foundry model remove phi-3.5-mini

# Delete all cached models
foundry model remove "*"

بهینه‌سازی عملکرد

Foundry Local به طور خودکار بهترین نوع مدل را برای سخت‌افزار شما انتخاب می‌کند:

  • GPU CUDA: مدل‌های بهینه‌شده برای GPU را دانلود می‌کند.
  • NPU Qualcomm: از نسخه‌های شتاب‌یافته NPU استفاده می‌کند.
  • فقط CPU: مدل‌های بهینه‌شده برای CPU را انتخاب می‌کند.

بهترین روش‌ها و رفع مشکلات

بهترین روش‌های تعریف توابع

۱. نام‌گذاری واضح و توصیفی

# Good
{
    "name": "get_stock_price",
    "description": "Retrieve current stock price for a given symbol"
}

# Avoid
{
    "name": "get_data", 
    "description": "Gets data"
}

۲. تعریف جامع پارامترها

{
    "name": "send_email",
    "description": "Send an email message to specified recipients",
    "parameters": {
        "to": {
            "type": "array",
            "items": {"type": "string"},
            "description": "List of recipient email addresses",
            "required": True
        },
        "subject": {
            "type": "string",
            "description": "Email subject line",
            "required": True
        },
        "body": {
            "type": "string", 
            "description": "Email message content",
            "required": True
        },
        "priority": {
            "type": "string",
            "enum": ["low", "normal", "high"],
            "description": "Email priority level",
            "default": "normal",
            "required": False
        }
    }
}

۳. اعتبارسنجی ورودی و مدیریت خطا

def execute_function(function_name, parameters):
    try:
        # Validate required parameters
        if function_name == "send_email":
            if not parameters.get("to") or not parameters.get("subject"):
                return {"error": "Missing required parameters: to, subject"}
            
            # Validate email format
            email_pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
            for email in parameters["to"]:
                if not re.match(email_pattern, email):
                    return {"error": f"Invalid email format: {email}"}
        
        # Execute function logic
        result = perform_actual_function(function_name, parameters)
        return {"success": True, "data": result}
        
    except Exception as e:
        return {"error": str(e)}

مشکلات رایج و راه‌حل‌ها

مشکل ۱: تابع فراخوانی نمی‌شود

علائم: مدل به جای فراخوانی تابع با متن پاسخ می‌دهد.

راه‌حل‌ها:

  1. بررسی توضیحات تابع: مطمئن شوید که به وضوح با قصد کاربر مطابقت دارد.
  2. اعتبارسنجی تعریف پارامترها: مطمئن شوید که تمام پارامترهای مورد نیاز به درستی تعریف شده‌اند.
  3. بازبینی پیام سیستم: دستورالعمل‌های واضحی درباره زمان استفاده از توابع اضافه کنید.
  4. آزمایش با درخواست‌های صریح: امتحان کنید "لطفاً از تابع آب‌وهوا برای دریافت داده‌های لندن استفاده کنید."

مشکل ۲: پارامترهای نادرست

علائم: تابع با پارامترهای اشتباه یا ناقص فراخوانی می‌شود.

راه‌حل‌ها:

  1. اضافه کردن مثال‌های پارامتر: نمونه مقادیر را در توضیحات پارامترها قرار دهید.
  2. استفاده از محدودیت‌های enum: مقادیر پارامترها را به گزینه‌های خاص محدود کنید.
  3. پیاده‌سازی مقادیر پیش‌فرض: مقادیر پیش‌فرض منطقی برای پارامترهای اختیاری ارائه دهید.
{
    "name": "book_restaurant",
    "parameters": {
        "cuisine": {
            "type": "string",
            "enum": ["italian", "chinese", "mexican", "american", "french"],
            "description": "Type of cuisine (example: 'italian' for Italian food)"
        },
        "party_size": {
            "type": "integer",
            "minimum": 1,
            "maximum": 20,
            "description": "Number of people (example: 4 for a family of four)"
        }
    }
}

مشکل ۳: شکست فراخوانی توابع موازی

علائم: فقط یک تابع اجرا می‌شود در حالی که باید چندین تابع اجرا شوند.

راه‌حل‌ها:

  1. بررسی پشتیبانی مدل: مطمئن شوید که مدل شما از فراخوانی توابع موازی پشتیبانی می‌کند.
  2. به‌روزرسانی پیام سیستم: عبارت "برخی ابزارها" یا "چندین ابزار" را در پیام سیستم اضافه کنید.
  3. استفاده از نسخه‌های مناسب مدل: Phi-4-mini:3.8b-fp16 برای Ollama توصیه می‌شود.

مشکل ۴: مشکلات قالب با Ollama

علائم: فراخوانی توابع با تنظیمات پیش‌فرض Ollama کار نمی‌کند.

راه‌حل‌ها:

  1. استفاده از ModelFile سفارشی: از قالب اصلاح‌شده ارائه شده در این آموزش استفاده کنید.
  2. به‌روزرسانی Ollama: مطمئن شوید که از نسخه 0.5.13 یا بالاتر استفاده می‌کنید.
  3. بررسی کمیت مدل: سطوح کمیت بالاتر (Q8_0، fp16) بهتر از نسخه‌های با کمیت سنگین عمل می‌کنند.

بهینه‌سازی عملکرد

۱. طراحی کارآمد توابع

  • توابع را متمرکز نگه دارید: هر تابع باید یک هدف واضح و واحد داشته باشد.
  • کاهش وابستگی‌های خارجی: تعداد درخواست‌های API و شبکه را کاهش دهید.
  • ذخیره نتایج: داده‌های پر درخواست را ذخیره کنید تا زمان پاسخ‌دهی بهبود یابد.

۲. عملیات دسته‌ای و غیرهمزمان

import asyncio
import aiohttp

async def batch_function_calls(function_calls):
    """Execute multiple function calls concurrently"""
    async with aiohttp.ClientSession() as session:
        tasks = []
        for call in function_calls:
            if call["name"] == "fetch_url":
                task = fetch_url_async(session, call["parameters"]["url"])
                tasks.append(task)
        
        results = await asyncio.gather(*tasks)
        return results

async def fetch_url_async(session, url):
    async with session.get(url) as response:
        return await response.text()

۳. مدیریت منابع

  • استخر اتصال: از اتصالات پایگاه داده و API مجدد استفاده کنید.
  • محدودیت نرخ: محدودیت نرخ مناسب برای APIهای خارجی پیاده‌سازی کنید.
  • مدیریت زمان انتظار: زمان‌های انتظار معقول برای تمام فراخوانی‌های خارجی تنظیم کنید.

مثال‌های پیشرفته

سیستم همکاری چندعاملی

import json
from typing import List, Dict
from qwen_agent.agents import Assistant

class MultiAgentSystem:
    def __init__(self):
        # Research Agent
        self.research_agent = Assistant(
            llm={'model': 'Qwen3-8B', 'model_server': 'http://localhost:8000/v1'},
            function_list=[
                {'mcpServers': {'search': {'command': 'uvx', 'args': ['mcp-server-search']}}},
                {'mcpServers': {'fetch': {'command': 'uvx', 'args': ['mcp-server-fetch']}}}
            ]
        )
        
        # Analysis Agent
        self.analysis_agent = Assistant(
            llm={'model': 'Qwen3-8B', 'model_server': 'http://localhost:8000/v1'},
            function_list=['code_interpreter']
        )
        
        # Communication Agent
        self.comm_agent = Assistant(
            llm={'model': 'Qwen3-8B', 'model_server': 'http://localhost:8000/v1'},
            function_list=[self.create_email_tool(), self.create_slack_tool()]
        )
    
    def create_email_tool(self):
        """Custom email sending tool"""
        class EmailTool:
            name = "send_email"
            description = "Send email to specified recipients"
            parameters = {
                "to": {"type": "string", "description": "Recipient email"},
                "subject": {"type": "string", "description": "Email subject"},
                "body": {"type": "string", "description": "Email content"}
            }
            
            def call(self, params):
                # Implement actual email sending logic
                return f"Email sent successfully to {params['to']}"
        
        return EmailTool()
    
    def create_slack_tool(self):
        """Custom Slack messaging tool"""  
        class SlackTool:
            name = "send_slack"
            description = "Send message to Slack channel"
            parameters = {
                "channel": {"type": "string", "description": "Slack channel"},
                "message": {"type": "string", "description": "Message content"}
            }
            
            def call(self, params):
                # Implement actual Slack API call
                return f"Message sent to {params['channel']}"
        
        return SlackTool()
    
    async def process_complex_request(self, user_request: str):
        """Process complex multi-step requests using multiple agents"""
        
        # Step 1: Research phase
        research_prompt = f"Research the following topic and gather relevant information: {user_request}"
        research_results = []
        for response in self.research_agent.run([{'role': 'user', 'content': research_prompt}]):
            research_results.append(response)
        
        # Step 2: Analysis phase
        analysis_prompt = f"Analyze the following research data and provide insights: {research_results[-1]}"
        analysis_results = []
        for response in self.analysis_agent.run([{'role': 'user', 'content': analysis_prompt}]):
            analysis_results.append(response)
        
        # Step 3: Communication phase
        comm_prompt = f"Create a summary report and send it via email: {analysis_results[-1]}"
        comm_results = []
        for response in self.comm_agent.run([{'role': 'user', 'content': comm_prompt}]):
            comm_results.append(response)
        
        return {
            'research': research_results[-1],
            'analysis': analysis_results[-1], 
            'communication': comm_results[-1]
        }

# Usage example
async def main():
    system = MultiAgentSystem()
    
    request = """
    Analyze the impact of remote work on productivity in tech companies. 
    Research recent studies, analyze the data, and send a summary to our team.
    """
    
    results = await system.process_complex_request(request)
    print("Multi-agent processing complete:", results)

# Run the example
# asyncio.run(main())

سیستم انتخاب ابزار پویا

class DynamicToolSelector:
    def __init__(self):
        self.available_tools = {
            'weather': {
                'description': 'Get weather information',
                'domains': ['weather', 'temperature', 'forecast', 'climate'],
                'function': self.get_weather
            },
            'calculator': {
                'description': 'Perform mathematical calculations',
                'domains': ['math', 'calculate', 'compute', 'arithmetic'],
                'function': self.calculate
            },
            'web_search': {
                'description': 'Search the internet for information',
                'domains': ['search', 'find', 'lookup', 'research'],
                'function': self.web_search
            },
            'file_manager': {
                'description': 'Manage files and directories',
                'domains': ['file', 'directory', 'save', 'load', 'delete'],
                'function': self.manage_files
            }
        }
    
    def analyze_intent(self, user_input: str) -> List[str]:
        """Analyze user input to determine which tools might be needed"""
        user_words = user_input.lower().split()
        relevant_tools = []
        
        for tool_name, tool_info in self.available_tools.items():
            for domain in tool_info['domains']:
                if domain in user_words:
                    relevant_tools.append(tool_name)
                    break
        
        return relevant_tools
    
    def get_tool_definitions(self, tool_names: List[str]) -> List[Dict]:
        """Generate function definitions for selected tools"""
        definitions = []
        
        for tool_name in tool_names:
            if tool_name == 'weather':
                definitions.append({
                    'name': 'get_weather',
                    'description': 'Get current weather information',
                    'parameters': {
                        'location': {'type': 'string', 'description': 'City or location name'},
                        'units': {'type': 'string', 'enum': ['celsius', 'fahrenheit'], 'default': 'celsius'}
                    }
                })
            elif tool_name == 'calculator':
                definitions.append({
                    'name': 'calculate',
                    'description': 'Perform mathematical calculations',
                    'parameters': {
                        'expression': {'type': 'string', 'description': 'Mathematical expression to evaluate'},
                        'precision': {'type': 'integer', 'default': 2, 'description': 'Decimal places for result'}
                    }
                })
            # Add more tool definitions as needed
        
        return definitions
    
    def get_weather(self, location: str, units: str = 'celsius') -> Dict:
        """Mock weather function"""
        return {
            'location': location,
            'temperature': '22°C' if units == 'celsius' else '72°F',
            'condition': 'Sunny',
            'humidity': '60%'
        }
    
    def calculate(self, expression: str, precision: int = 2) -> Dict:
        """Safe mathematical calculation"""
        try:
            # Simple evaluation for demo - in production, use a proper math parser
            import math
            allowed_names = {
                k: v for k, v in math.__dict__.items() if not k.startswith("__")
            }
            allowed_names.update({"abs": abs, "round": round})
            
            result = eval(expression, {"__builtins__": {}}, allowed_names)
            return {
                'expression': expression,
                'result': round(float(result), precision),
                'success': True
            }
        except Exception as e:
            return {
                'expression': expression,
                'error': str(e),
                'success': False
            }
    
    def web_search(self, query: str, max_results: int = 5) -> Dict:
        """Mock web search function"""
        return {
            'query': query,
            'results': [
                {'title': f'Result {i+1} for {query}', 'url': f'https://example{i+1}.com'}
                for i in range(max_results)
            ]
        }
    
    def manage_files(self, action: str, file_path: str, content: str = None) -> Dict:
        """Mock file management function"""
        return {
            'action': action,
            'file_path': file_path,
            'success': True,
            'message': f'Successfully {action}ed file: {file_path}'
        }

# Usage example
def smart_assistant_with_dynamic_tools():
    selector = DynamicToolSelector()
    
    user_requests = [
        "What's the weather like in New York and calculate 15% tip on \$50?",
        "Search for recent AI developments and save the results to a file",
        "Calculate the area of a circle with radius 10 and check weather in Tokyo"
    ]
    
    for request in user_requests:
        print(f"\nUser Request: {request}")
        
        # Analyze which tools might be needed
        relevant_tools = selector.analyze_intent(request)
        print(f"Relevant Tools: {relevant_tools}")
        
        # Get function definitions for the LLM
        tool_definitions = selector.get_tool_definitions(relevant_tools)
        print(f"Tool Definitions: {len(tool_definitions)} functions available")
        
        # In a real implementation, you would pass these to your LLM
        # The LLM would then decide which functions to call and with what parameters

### Enterprise Integration Example

نتیجه عملکرد:

قوانین مهم:

  1. اجرای یک تابع با مدیریت جامع خطا و ثبت گزارش زمان شروع = datetime.now()

    try:
        # بررسی وجود تابع
        اگر `function_name` در `self.functions` نباشد:
            بازگرداندن `FunctionResult`:
                موفقیت = `False`
                خطا = f"تابع '{function_name}' یافت نشد"
                زمان‌سنجی = `start_time`
        
        # بررسی محدودیت‌های نرخ
        اگر `self._check_rate_limit(function_name)` موفق نباشد:
            بازگرداندن `FunctionResult`:
                موفقیت = `False`
                خطا = f"محدودیت نرخ برای تابع '{function_name}' تجاوز شده است"
                زمان‌سنجی = `start_time`
        
        # اعتبارسنجی پارامترها
        نتیجه_اعتبارسنجی = `self._validate_parameters(function_name, parameters)`
        اگر نتیجه_اعتبارسنجی موفق نباشد:
            بازگرداندن نتیجه_اعتبارسنجی
        
        # اجرای تابع
        اطلاعات_تابع = `self.functions[function_name]`
        مدیریت‌کننده = اطلاعات_تابع['handler']
        
        اگر `asyncio.iscoroutinefunction(handler)`:
            داده_نتیجه = `await handler(**parameters)`
        دیگر:
            داده_نتیجه = `handler(**parameters)`
        
        زمان_اجرا = `(datetime.now() - start_time).total_seconds()`
        
        نتیجه = `FunctionResult`:
            موفقیت = `True`
            داده = داده_نتیجه
            زمان_اجرا = زمان_اجرا
            زمان‌سنجی = `start_time`
        
        # ثبت اجرای موفق
        `self._log_function_call(function_name, parameters, result)`
        
        بازگرداندن نتیجه
        
    except Exception as e:
        زمان_اجرا = `(datetime.now() - start_time).total_seconds()`
        نتیجه = `FunctionResult`:
            موفقیت = `False`
            خطا = `str(e)`
            زمان_اجرا = زمان_اجرا
            زمان‌سنجی = `start_time`
        
        # ثبت اجرای ناموفق
        `self._log_function_call(function_name, parameters, result)`
        
        بازگرداندن نتیجه
    
  2. بررسی محدودیت نرخ برای فراخوانی تابع

    def _check_rate_limit(self, function_name: str) -> bool:
        اطلاعات_تابع = `self.functions[function_name]`
        اکنون = `datetime.now()`
        
        # بازنشانی شمارنده اگر یک دقیقه گذشته باشد
        اگر `(اکنون - اطلاعات_تابع['last_reset']).seconds >= 60`:
            اطلاعات_تابع['call_count'] = 0
            اطلاعات_تابع['last_reset'] = اکنون
        
        # بررسی اگر زیر محدودیت باشد
        اگر اطلاعات_تابع['call_count'] >= اطلاعات_تابع['rate_limit']:
            بازگرداندن `False`
        
        اطلاعات_تابع['call_count'] += 1
        بازگرداندن `True`
    
  3. اعتبارسنجی پارامترهای تابع

    def _validate_parameters(self, function_name: str, parameters: Dict) -> FunctionResult:
        پارامترهای_تابع = `self.functions[function_name]['parameters']`
        
        # بررسی پارامترهای ضروری
        برای `param_name, param_info` در `پارامترهای_تابع.items()`:
            اگر `param_info.get('required', False)` و `param_name` در `parameters` نباشد:
                بازگرداندن `FunctionResult`:
                    موفقیت = `False`
                    خطا = f"پارامتر ضروری '{param_name}' وجود ندارد"
        
        # اعتبارسنجی نوع و محدودیت‌های پارامترها
        برای `param_name, value` در `parameters.items()`:
            اگر `param_name` در `پارامترهای_تابع`:
                اطلاعات_پارامتر = `پارامترهای_تابع[param_name]`
                
                # اعتبارسنجی نوع
                نوع_مورد_انتظار = اطلاعات_پارامتر.get('type')
                اگر نوع_مورد_انتظار == 'string' و `not isinstance(value, str)`:
                    بازگرداندن `FunctionResult`:
                        موفقیت = `False`
                        خطا = f"پارامتر '{param_name}' باید از نوع رشته باشد"
                elif نوع_مورد_انتظار == 'number' و `not isinstance(value, (int, float))`:
                    بازگرداندن `FunctionResult`:
                        موفقیت = `False`
                        خطا = f"پارامتر '{param_name}' باید از نوع عدد باشد"
                elif نوع_مورد_انتظار == 'boolean' و `not isinstance(value, bool)`:
                    بازگرداندن `FunctionResult`:
                        موفقیت = `False`
                        خطا = f"پارامتر '{param_name}' باید از نوع بولین باشد"
                
                # اعتبارسنجی مقادیر مجاز
                اگر 'enum' در اطلاعات_پارامتر و `value` در اطلاعات_پارامتر['enum'] نباشد:
                    بازگرداندن `FunctionResult`:
                        موفقیت = `False`
                        خطا = f"پارامتر '{param_name}' باید یکی از این مقادیر باشد: {اطلاعات_پارامتر['enum']}"
        
        بازگرداندن `FunctionResult(success=True)`
    
  4. ثبت فراخوانی تابع برای اهداف حسابرسی

    def _log_function_call(self, function_name: str, parameters: Dict, result: FunctionResult):
        ورودی_ثبت = {
            'زمان‌سنجی': `result.timestamp.isoformat()`,
            'نام_تابع': `function_name`,
            'پارامترها': `parameters`,
            'موفقیت': `result.success`,
            'زمان_اجرا': `result.execution_time`,
            'خطا': `result.error` اگر `not result.success` دیگر `None`
        }
        
        `self.audit_log.append(ورودی_ثبت)`
        
        # اختیاری: نوشتن در سیستم ثبت خارجی
        اگر `self.config.get('enable_external_logging', False)`:
            `self._write_to_external_log(ورودی_ثبت)`
    
  5. اجرای مثال‌های کاربردی

    async def enterprise_demo():
        """نمایش قابلیت‌های عامل هوش مصنوعی سازمانی"""
        
        پیکربندی = {
            'enable_external_logging': `True`,
            'max_concurrent_functions': 10,
            'default_timeout': 30
        }
        
        عامل = `EnterpriseAIAgent(pیکربندی)`
        
        # مثال ۱: پردازش استعلام مشتری
        print("=== پردازش استعلام مشتری ===")
        
        نتیجه = `await agent.execute_function`(
            'get_customer_info',
            {'customer_id': 'CUST-12345', 'include_history': `True`}
        )
        
        اگر نتیجه موفق باشد:
            print(f"اطلاعات مشتری بازیابی شد: {نتیجه.data['name']}")
            print(f"زمان اجرا: {نتیجه.execution_time:.3f}s")
    

به یاد داشته باشید که فراخوانی توابع یک حوزه در حال پیشرفت است و به‌روز نگه داشتن اطلاعات خود در مورد آخرین تحولات در چارچوب‌ها و مدل‌های انتخابی‌تان به شما کمک می‌کند عوامل هوش مصنوعی مؤثرتری بسازید.

➡️ گام بعدی


سلب مسئولیت:
این سند با استفاده از سرویس ترجمه هوش مصنوعی Co-op Translator ترجمه شده است. در حالی که ما برای دقت تلاش می‌کنیم، لطفاً توجه داشته باشید که ترجمه‌های خودکار ممکن است شامل خطاها یا نادقتی‌ها باشند. سند اصلی به زبان اصلی آن باید به عنوان منبع معتبر در نظر گرفته شود. برای اطلاعات حساس، ترجمه حرفه‌ای انسانی توصیه می‌شود. ما هیچ مسئولیتی در قبال سوءتفاهم‌ها یا تفسیرهای نادرست ناشی از استفاده از این ترجمه نداریم.