0Pricing
AI Engineering Academy · درس

تعريف مخططات الدوال لواجهة API

اكتبوا تعريفات JSON Schema لدوالكم، ومرروها في المعامل tools، وافهموا كيف يقرر النموذج متى يستدعي هذه الدوال وكيفية استدعائها.

تعريف مخططات الدوال لواجهة API درس مجاني في AI Engineering Academy على CoddyKit. هذا هو الدرس 1 من أصل 4. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في AI Engineering Academy، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة AI Engineering Academy 4 دروس في المجموع.

بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.

What Is Function Calling?

OpenAI's function calling (now called tool calling) lets you describe Python functions to the model in a structured JSON Schema format. When the model determines a function should be called, instead of producing free-text it returns a structured JSON object with the function name and arguments — which your code then executes reliably.

The tools Parameter Structure

You pass your function definitions to the API in the tools parameter as a list of objects. Each object has a type of 'function' and a function key containing the name, description, and a JSON Schema defining the parameters.

from openai import OpenAI

client = OpenAI()

tools = [
    {
        'type': 'function',
        'function': {
            'name': 'get_current_weather',
            'description': 'Get the current weather in a given location.',
            'parameters': {
                'type': 'object',
                'properties': {
                    'location': {
                        'type': 'string',
                        'description': 'City and country, e.g. London, UK'
                    },
                    'unit': {
                        'type': 'string',
                        'enum': ['celsius', 'fahrenheit'],
                        'description': 'Temperature unit to use.'
                    }
                },
                'required': ['location']
            }
        }
    }
]

JSON Schema for Parameters

The parameters field follows the JSON Schema specification. Use type to specify string, number, integer, boolean, array, or object. Use description for each property to tell the model what the field means. List required fields in the required array — optional fields can be omitted from required.

# A more complex schema with multiple types
create_event_tool = {
    'type': 'function',
    'function': {
        'name': 'create_calendar_event',
        'description': 'Create a new calendar event. Use when the user wants to schedule a meeting or appointment.',
        'parameters': {
            'type': 'object',
            'properties': {
                'title': {'type': 'string', 'description': 'Event title.'},
                'start_time': {'type': 'string', 'description': 'ISO 8601 datetime, e.g. 2024-03-15T14:00:00.'},
                'duration_minutes': {'type': 'integer', 'description': 'Duration in minutes.', 'minimum': 5},
                'attendees': {
                    'type': 'array',
                    'items': {'type': 'string'},
                    'description': 'List of email addresses of attendees.'
                },
                'location': {'type': 'string', 'description': 'Physical or virtual meeting location.'}
            },
            'required': ['title', 'start_time', 'duration_minutes']
        }
    }
}

Making the API Call with Tools

Pass the tools list directly to chat.completions.create. The model may respond with a regular text message (if it can answer without a function), or it may respond with a tool_calls object instructing you to execute a function. Always check finish_reason to know which case you're in.

response = client.chat.completions.create(
    model='gpt-4o',
    messages=[
        {'role': 'user', 'content': 'What is the weather in Tokyo?'}
    ],
    tools=tools
)

print('Finish reason:', response.choices[0].finish_reason)
# 'tool_calls' means the model wants to call a function
# 'stop' means the model gave a regular text response

choice = response.choices[0].message
if response.choices[0].finish_reason == 'tool_calls':
    print('Model wants to call:', choice.tool_calls[0].function.name)

Controlling Tool Selection with tool_choice

The tool_choice parameter controls whether the model must call a function or can choose freely. Setting it to 'auto' lets the model decide. Setting it to 'required' forces a tool call. Setting it to a specific function name forces exactly that function to be called — useful for extraction tasks where you always want structured output.

# Force the model to always call extract_contact
response = client.chat.completions.create(
    model='gpt-4o',
    messages=[{'role': 'user', 'content': 'Hi, I am John Smith, john@example.com, +1-555-0100.'}],
    tools=[extract_contact_tool],
    tool_choice={'type': 'function', 'function': {'name': 'extract_contact'}}
)
# With tool_choice forced, finish_reason will always be 'tool_calls'

Enum Fields for Constrained Choices

Use the enum field in your JSON Schema whenever a parameter should be restricted to a fixed set of values. This dramatically improves reliability — the model is much less likely to invent an invalid option when it can see the exact allowed values listed in the schema.

classify_sentiment_tool = {
    'type': 'function',
    'function': {
        'name': 'classify_sentiment',
        'description': 'Classify the sentiment of a customer review.',
        'parameters': {
            'type': 'object',
            'properties': {
                'sentiment': {
                    'type': 'string',
                    'enum': ['positive', 'negative', 'neutral', 'mixed'],
                    'description': 'The sentiment classification.'
                },
                'confidence': {
                    'type': 'number',
                    'minimum': 0.0,
                    'maximum': 1.0,
                    'description': 'Model confidence from 0 to 1.'
                }
            },
            'required': ['sentiment', 'confidence']
        }
    }
}

Nested Object Schemas

JSON Schema supports nested objects. Use 'type': 'object' with its own properties to define complex hierarchical data structures. This is ideal for extracting structured data from unstructured text like emails or documents.

extract_order_tool = {
    'type': 'function',
    'function': {
        'name': 'extract_order',
        'description': 'Extract order details from a customer email.',
        'parameters': {
            'type': 'object',
            'properties': {
                'customer': {
                    'type': 'object',
                    'properties': {
                        'name': {'type': 'string'},
                        'email': {'type': 'string', 'format': 'email'}
                    },
                    'required': ['name']
                },
                'items': {
                    'type': 'array',
                    'items': {
                        'type': 'object',
                        'properties': {
                            'product_id': {'type': 'string'},
                            'quantity': {'type': 'integer', 'minimum': 1}
                        },
                        'required': ['product_id', 'quantity']
                    }
                }
            },
            'required': ['customer', 'items']
        }
    }
}

Generating Schemas from Pydantic Models

Writing JSON Schemas by hand is tedious and error-prone. Instead, define your data structure as a Pydantic model and use .schema() to generate the JSON Schema automatically. This also gives you Python-level validation when you deserialize the model's response.

from pydantic import BaseModel, Field
from typing import Optional, List

class ContactInfo(BaseModel):
    name: str = Field(description='Full name of the person.')
    email: Optional[str] = Field(None, description='Email address.')
    phone: Optional[str] = Field(None, description='Phone number in E.164 format.')
    company: Optional[str] = Field(None, description='Company or organization.')

# Auto-generate the JSON Schema
schema = ContactInfo.schema()

# Build the tool definition
extract_contact_tool = {
    'type': 'function',
    'function': {
        'name': 'extract_contact',
        'description': 'Extract contact information from text.',
        'parameters': schema
    }
}

Writing Effective Function Descriptions

The function description is the key signal the model uses to decide when to call a tool. A good description is specific about the use case, mentions when the function should and should not be called, and describes what the output will be. Vague descriptions cause the model to call the wrong function or miss opportunities to call the right one.

  • Vague: 'Get weather data.'
  • Good: 'Get the current weather conditions for a specific city. Use when the user explicitly asks about weather in a named location. Returns temperature, conditions, and humidity.'

Strict Mode for Guaranteed Schema Adherence

OpenAI's strict mode for structured outputs guarantees the model will produce JSON that exactly matches your schema — no extra fields, no missing required fields. Enable it by setting 'strict': true in the function definition. Note: strict mode requires additionalProperties: false in all schema objects.

strict_tool = {
    'type': 'function',
    'function': {
        'name': 'classify_ticket',
        'description': 'Classify a support ticket into category and priority.',
        'strict': True,  # Enable strict schema adherence
        'parameters': {
            'type': 'object',
            'additionalProperties': False,  # Required for strict mode
            'properties': {
                'category': {
                    'type': 'string',
                    'enum': ['billing', 'technical', 'account', 'other']
                },
                'priority': {
                    'type': 'string',
                    'enum': ['low', 'medium', 'high', 'urgent']
                }
            },
            'required': ['category', 'priority']
        }
    }
}

Testing Your Function Schemas

Before deploying, test each function schema with diverse inputs: normal cases, edge cases, and adversarial inputs. Verify the model calls the right function, produces valid argument types, handles optional fields correctly, and respects enum constraints. Use the OpenAI Playground to iterate quickly before writing production code.

Quick Check

Test your understanding of defining function schemas for the OpenAI API.

Lesson Recap

In this lesson you learned: function schemas use JSON Schema to define parameter types, descriptions, and constraints, tool_choice controls whether the model must call a function or chooses freely, and Pydantic models can auto-generate JSON Schema to reduce manual schema writing. Next up we learn to process tool calls in your application by detecting, executing, and sending results back.

الأسئلة الشائعة

هل درس «تعريف مخططات الدوال لواجهة API» مجاني؟

نعم — نص درس «تعريف مخططات الدوال لواجهة API» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة AI Engineering Academy، انتقل إلى CoddyKit PRO. تتضمن دورة AI Engineering Academy 4 دروس في المجموع.

ماذا ستتعلم في «تعريف مخططات الدوال لواجهة API»؟

اكتبوا تعريفات JSON Schema لدوالكم، ومرروها في المعامل tools، وافهموا كيف يقرر النموذج متى يستدعي هذه الدوال وكيفية استدعائها. تتمرن على AI Engineering Academy مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.

هل أحتاج إلى خبرة سابقة لأبدأ AI Engineering Academy؟

لا تُشترط خبرة سابقة. AI Engineering Academy على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 1 من أصل 4.

كم من الوقت يستغرق درس «تعريف مخططات الدوال لواجهة API»؟

معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.

هل يمكنني كتابة وتشغيل أكواد في درس AI Engineering Academy هذا؟

نعم. كل درس في AI Engineering Academy يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.

جميع الدروس في هذه الدورة

  1. تعريف مخططات الدوال لواجهة API
  2. معالجة استدعاءات الأدوات في تطبيقكم
  3. استدعاء الدوال بالتوازي
  4. بناء واجهة قاعدة بيانات باللغة الطبيعية
← العودة إلى AI Engineering Academy