إشعار
يتطلب الوصول إلى هذه الصفحة تخويلاً. يمكنك محاولة تسجيل الدخول أو تغيير الدلائل.
يتطلب الوصول إلى هذه الصفحة تخويلاً. يمكنك محاولة تغيير الدلائل.
إذا تم تضمين دالة واحدة أو أكثر في طلبك، يحدد النموذج ما إذا كان يجب استدعاء أي من الدالات استنادا إلى سياق المطالبة. عندما يحدد النموذج أنه يجب استدعاء دالة، يرد بكائن JSON يتضمن الوسائط الخاصة بالدالة.
تصوغ النماذج استدعاءات واجهة برمجة التطبيقات وبنية مخرجات البيانات، كل ذلك استنادا إلى الوظائف التي تحددها. من المهم ملاحظة أنه بينما يمكن للنماذج إنشاء هذه الاستدعاءات، فإن الأمر متروك لك لتنفيذها، ما يضمن بقائك في وضع التحكم.
على مستوى عال، يمكنك تقسيم العمل مع الدوال إلى ثلاث خطوات:
- استدعاء واجهة برمجة تطبيقات إكمال الدردشة باستخدام وظائفك وإدخال المستخدم
- استخدم استجابة النموذج لاستدعاء واجهة برمجة التطبيقات أو الوظيفة
- استدعاء واجهة برمجة تطبيقات إكمال الدردشة مرة أخرى، بما في ذلك الاستجابة من وظيفتك للحصول على استجابة نهائية
المتطلبات المسبقه
- نموذج Azure OpenAI تم نشره
- بالنسبة للمصادقة على Microsoft Entra ID:
- تم تكوين نطاق فرعي مخصص. لمزيد من المعلومات، راجع أسماء النطاقات الفرعية المخصصة.
- الطرود:
pip install openai azure-identity.
مثال استدعاء أداة/دالة واحدة
قم أولا بإظهار استدعاء وظيفة لعبة يمكنه التحقق من الوقت في ثلاثة مواقع مشفرة باستخدام أداة / وظيفة واحدة محددة. لقد أضفنا عبارات الطباعة للمساعدة في تسهيل متابعة تنفيذ التعليمات البرمجية:
import os
import json
from openai import OpenAI
from datetime import datetime
from zoneinfo import ZoneInfo
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://ai.azure.com/.default"
)
client = OpenAI(
base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=token_provider,
)
# Define the deployment you want to use for your chat completions API calls
deployment_name = "<YOUR_DEPLOYMENT_NAME_HERE>"
# Simplified timezone data
TIMEZONE_DATA = {
"tokyo": "Asia/Tokyo",
"san francisco": "America/Los_Angeles",
"paris": "Europe/Paris"
}
def get_current_time(location):
"""Get the current time for a given location"""
print(f"get_current_time called with location: {location}")
location_lower = location.lower()
for key, timezone in TIMEZONE_DATA.items():
if key in location_lower:
print(f"Timezone found for {key}")
current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p")
return json.dumps({
"location": location,
"current_time": current_time
})
print(f"No timezone data found for {location_lower}")
return json.dumps({"location": location, "current_time": "unknown"})
def run_conversation():
# Initial user message
messages = [{"role": "user", "content": "What's the current time in San Francisco"}] # Single function call
#messages = [{"role": "user", "content": "What's the current time in San Francisco, Tokyo, and Paris?"}] # Parallel function call with a single tool/function defined
# Define the function for the model
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Get the current time in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
}
]
# First API call: Ask the model to use the function
response = client.chat.completions.create(
model=deployment_name,
messages=messages,
tools=tools,
tool_choice="auto",
)
# Process the model's response
response_message = response.choices[0].message
messages.append(response_message)
print("Model's response:")
print(response_message)
# Handle function calls
if response_message.tool_calls:
for tool_call in response_message.tool_calls:
if tool_call.function.name == "get_current_time":
function_args = json.loads(tool_call.function.arguments)
print(f"Function arguments: {function_args}")
time_response = get_current_time(
location=function_args.get("location")
)
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": "get_current_time",
"content": time_response,
})
else:
print("No tool calls were made by the model.")
# Second API call: Get the final response from the model
final_response = client.chat.completions.create(
model=deployment_name,
messages=messages,
)
return final_response.choices[0].message.content
# Run the conversation and print the result
print(run_conversation())
إخراج:
Model's response:
ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_pOsKdUlqvdyttYB67MOj434b', function=Function(arguments='{"location":"San Francisco"}', name='get_current_time'), type='function')])
Function arguments: {'location': 'San Francisco'}
get_current_time called with location: San Francisco
Timezone found for san francisco
The current time in San Francisco is 09:24 AM.
إذا كنا نستخدم نشر نموذج يدعم استدعاءات الدالة المتوازية ، فيمكننا تحويل هذا إلى مثال استدعاء دالة متوازية عن طريق تغيير مصفوفة الرسائل لطلب الوقت في مواقع متعددة بدلا من موقع واحد.
لإنجاز هذا التبديل بين التعليقات في هذين الخطين:
messages = [{"role": "user", "content": "What's the current time in San Francisco"}] # Single function call
#messages = [{"role": "user", "content": "What's the current time in San Francisco, Tokyo, and Paris?"}] # Parallel function call with a single tool/function defined
لتبدو هكذا، ثم قم بتشغيل التعليمات البرمجية مرة أخرى:
#messages = [{"role": "user", "content": "What's the current time in San Francisco"}] # Single function call
messages = [{"role": "user", "content": "What's the current time in San Francisco, Tokyo, and Paris?"}] # Parallel function call with a single tool/function defined
يؤدي هذا إلى إنشاء الإخراج التالي:
إخراج:
Model's response:
ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_IjcAVz9JOv5BXwUx1jd076C1', function=Function(arguments='{"location": "San Francisco"}', name='get_current_time'), type='function'), ChatCompletionMessageToolCall(id='call_XIPQYTCtKIaNCCPTdvwjkaSN', function=Function(arguments='{"location": "Tokyo"}', name='get_current_time'), type='function'), ChatCompletionMessageToolCall(id='call_OHIB5aJzO8HGqanmsdzfytvp', function=Function(arguments='{"location": "Paris"}', name='get_current_time'), type='function')])
Function arguments: {'location': 'San Francisco'}
get_current_time called with location: San Francisco
Timezone found for san francisco
Function arguments: {'location': 'Tokyo'}
get_current_time called with location: Tokyo
Timezone found for tokyo
Function arguments: {'location': 'Paris'}
get_current_time called with location: Paris
Timezone found for paris
As of now, the current times are:
- **San Francisco:** 11:15 AM
- **Tokyo:** 03:15 AM (next day)
- **Paris:** 08:15 PM
تسمح لك استدعاءات الدالة المتوازية بإجراء استدعاءات دالة متعددة معا، ما يسمح بتنفيذ النتائج المتوازي واستردادها. وهذا يقلل من عدد الاستدعاءات إلى واجهة برمجة التطبيقات التي تحتاج إلى إجراء ويمكن أن تحسن الأداء العام.
على سبيل المثال في تطبيق الوقت البسيط الذي استردناه عدة مرات في نفس الوقت. أدى هذا إلى رسالة إكمال دردشة مع ثلاثة استدعاءات دالة tool_calls في الصفيف، كل منها مع فريدة من نوعها id. إذا أردت الرد على استدعاءات الدالة هذه، يمكنك إضافة ثلاث رسائل جديدة إلى المحادثة، تحتوي كل منها على نتيجة استدعاء دالة واحدة، مع tool_call_id الإشارة إلى id من tool_calls.
لإجبار النموذج على استدعاء دالة معينة، قم بتعيين tool_choice كائن أداة مسماة، على سبيل المثال: tool_choice={"type": "function", "function": {"name": "get_current_time"}}. لإجبار رسالة موجهة للمستخدم، قم بتعيين tool_choice="none".
ملاحظة
السلوك الافتراضي (tool_choice: "auto") هو أن يقرر النموذج من تلقاء نفسه ما إذا كان يجب أن يستدعي دالة وإذا كان الأمر كذلك، فأي دالة يجب استدعاؤها.
استدعاء الدالة المتوازية مع دوال متعددة
الآن نوضح دالة لعبة أخرى تستدعي مثالا هذه المرة مع تحديد أداتين / وظيفتين مختلفتين.
import os
import json
from openai import OpenAI
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
from azure.identity import DefaultAzureCredential, get_bearer_token_provider
token_provider = get_bearer_token_provider(
DefaultAzureCredential(), "https://ai.azure.com/.default"
)
client = OpenAI(
base_url = "https://YOUR-RESOURCE-NAME.openai.azure.com/openai/v1/",
api_key=token_provider,
)
# Provide the model deployment name you want to use for this example
deployment_name = "YOUR_DEPLOYMENT_NAME_HERE"
# Simplified weather data
WEATHER_DATA = {
"tokyo": {"temperature": "10", "unit": "celsius"},
"san francisco": {"temperature": "72", "unit": "fahrenheit"},
"paris": {"temperature": "22", "unit": "celsius"}
}
# Simplified timezone data
TIMEZONE_DATA = {
"tokyo": "Asia/Tokyo",
"san francisco": "America/Los_Angeles",
"paris": "Europe/Paris"
}
def get_current_weather(location, unit=None):
"""Get the current weather for a given location"""
location_lower = location.lower()
print(f"get_current_weather called with location: {location}, unit: {unit}")
for key in WEATHER_DATA:
if key in location_lower:
print(f"Weather data found for {key}")
weather = WEATHER_DATA[key]
return json.dumps({
"location": location,
"temperature": weather["temperature"],
"unit": unit if unit else weather["unit"]
})
print(f"No weather data found for {location_lower}")
return json.dumps({"location": location, "temperature": "unknown"})
def get_current_time(location):
"""Get the current time for a given location"""
print(f"get_current_time called with location: {location}")
location_lower = location.lower()
for key, timezone in TIMEZONE_DATA.items():
if key in location_lower:
print(f"Timezone found for {key}")
current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p")
return json.dumps({
"location": location,
"current_time": current_time
})
print(f"No timezone data found for {location_lower}")
return json.dumps({"location": location, "current_time": "unknown"})
def run_conversation():
# Initial user message
messages = [{"role": "user", "content": "What's the weather and current time in San Francisco, Tokyo, and Paris?"}]
# Define the functions for the model
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": "The city name, e.g. San Francisco",
},
"unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
},
"required": ["location"],
},
}
},
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Get the current time in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
}
]
# First API call: Ask the model to use the functions
response = client.chat.completions.create(
model=deployment_name,
messages=messages,
tools=tools,
tool_choice="auto",
)
# Process the model's response
response_message = response.choices[0].message
messages.append(response_message)
print("Model's response:")
print(response_message)
# Handle function calls
if response_message.tool_calls:
for tool_call in response_message.tool_calls:
function_name = tool_call.function.name
function_args = json.loads(tool_call.function.arguments)
print(f"Function call: {function_name}")
print(f"Function arguments: {function_args}")
if function_name == "get_current_weather":
function_response = get_current_weather(
location=function_args.get("location"),
unit=function_args.get("unit")
)
elif function_name == "get_current_time":
function_response = get_current_time(
location=function_args.get("location")
)
else:
function_response = json.dumps({"error": "Unknown function"})
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": function_name,
"content": function_response,
})
else:
print("No tool calls were made by the model.")
# Second API call: Get the final response from the model
final_response = client.chat.completions.create(
model=deployment_name,
messages=messages,
)
return final_response.choices[0].message.content
# Run the conversation and print the result
print(run_conversation())
الناتج
Model's response:
ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_djHAeQP0DFEVZ2qptrO0CYC4', function=Function(arguments='{"location": "San Francisco", "unit": "celsius"}', name='get_current_weather'), type='function'), ChatCompletionMessageToolCall(id='call_q2f1HPKKUUj81yUa3ITLOZFs', function=Function(arguments='{"location": "Tokyo", "unit": "celsius"}', name='get_current_weather'), type='function'), ChatCompletionMessageToolCall(id='call_6TEY5Imtr17PaB4UhWDaPxiX', function=Function(arguments='{"location": "Paris", "unit": "celsius"}', name='get_current_weather'), type='function'), ChatCompletionMessageToolCall(id='call_vpzJ3jElpKZXA9abdbVMoauu', function=Function(arguments='{"location": "San Francisco"}', name='get_current_time'), type='function'), ChatCompletionMessageToolCall(id='call_1ag0MCIsEjlwbpAqIXJbZcQj', function=Function(arguments='{"location": "Tokyo"}', name='get_current_time'), type='function'), ChatCompletionMessageToolCall(id='call_ukOu3kfYOZR8lpxGRpdkhhdD', function=Function(arguments='{"location": "Paris"}', name='get_current_time'), type='function')])
Function call: get_current_weather
Function arguments: {'location': 'San Francisco', 'unit': 'celsius'}
get_current_weather called with location: San Francisco, unit: celsius
Weather data found for san francisco
Function call: get_current_weather
Function arguments: {'location': 'Tokyo', 'unit': 'celsius'}
get_current_weather called with location: Tokyo, unit: celsius
Weather data found for tokyo
Function call: get_current_weather
Function arguments: {'location': 'Paris', 'unit': 'celsius'}
get_current_weather called with location: Paris, unit: celsius
Weather data found for paris
Function call: get_current_time
Function arguments: {'location': 'San Francisco'}
get_current_time called with location: San Francisco
Timezone found for san francisco
Function call: get_current_time
Function arguments: {'location': 'Tokyo'}
get_current_time called with location: Tokyo
Timezone found for tokyo
Function call: get_current_time
Function arguments: {'location': 'Paris'}
get_current_time called with location: Paris
Timezone found for paris
Here's the current information for the three cities:
### San Francisco
- **Time:** 09:13 AM
- **Weather:** 72°C (quite warm!)
### Tokyo
- **Time:** 01:13 AM (next day)
- **Weather:** 10°C
### Paris
- **Time:** 06:13 PM
- **Weather:** 22°C
Is there anything else you need?
مهم
قد لا تكون استجابة JSON صالحة دائما لذلك تحتاج إلى إضافة منطق إضافي إلى التعليمات البرمجية الخاصة بك لتكون قادرا على معالجة الأخطاء. بالنسبة لبعض حالات الاستخدام، قد تجد أنك بحاجة إلى استخدام الضبط الدقيق لتحسين أداء استدعاء الدالة.
الهندسة الموجهة مع الوظائف
عند تعريف دالة كجزء من طلبك، يتم إدخال التفاصيل في رسالة النظام باستخدام بناء جملة معين تم تدريب النموذج عليه. وهذا يعني أن الوظائف تستهلك الرموز المميزة في المطالبة الخاصة بك وأنه يمكنك تطبيق تقنيات هندسة المطالبة لتحسين أداء استدعاءات الدالة الخاصة بك. يستخدم النموذج السياق الكامل للمطالبة لتحديد ما إذا كان يجب استدعاء دالة بما في ذلك تعريف الدالة ورسالة النظام ورسائل المستخدم.
تحسين الجودة والموثوقية
إذا كان النموذج لا يستدعي دالتك متى أو كيف تتوقع، فهناك بعض الأشياء التي يمكنك تجربتها لتحسين الجودة.
توفير مزيد من التفاصيل في تعريف الدالة
من المهم أن توفر دالة ذات معنى description وتوفر أوصافا لأي معلمة قد لا تكون واضحة للنموذج. على سبيل المثال، في وصف المعلمة location ، يمكنك تضمين تفاصيل وأمثلة إضافية حول تنسيق الموقع.
"location": {
"type": "string",
"description": "The location of the hotel. The location should include the city and the state's abbreviation (i.e. Seattle, WA or Miami, FL)"
},
توفير المزيد من السياق في رسالة النظام
يمكن أيضا استخدام رسالة النظام لتوفير المزيد من السياق للنموذج. على سبيل المثال، إذا كان لديك دالة تسمى search_hotels يمكنك تضمين رسالة نظام مثل ما يلي لإرشاد النموذج لاستدعاء الدالة عندما يطلب المستخدم المساعدة في العثور على فندق.
{"role": "system", "content": "You're an AI assistant designed to help users search for hotels. When a user asks for help finding a hotel, you should call the search_hotels function."}
إرشاد النموذج لطرح أسئلة توضيحية
في بعض الحالات، تريد إرشاد النموذج لطرح أسئلة توضيحية لمنع وضع افتراضات حول القيم التي يجب استخدامها مع الدالات. على سبيل المثال، قد ترغب في search_hotels أن يطلب النموذج توضيحا إذا لم يتضمن طلب المستخدم تفاصيل حول location. لإرشاد النموذج لطرح سؤال توضيحي، يمكنك تضمين محتوى مثل المثال التالي في رسالة النظام.
{"role": "system", "content": "Don't make assumptions about what values to use with functions. Ask for clarification if a user request is ambiguous."}
تقليل الأخطاء
مجال آخر حيث يمكن أن تكون الهندسة الفورية ذات قيمة في تقليل الأخطاء في استدعاءات الدالة. يتم تدريب النماذج على إنشاء استدعاءات دالة مطابقة للمخطط الذي تحدده، ولكن النماذج تنتج استدعاء دالة لا يتطابق مع المخطط الذي حددته أو تحاول استدعاء دالة لم تقم بتضمينها.
إذا وجدت أن النموذج يقوم بإنشاء استدعاءات دالة لم يتم توفيرها، فحاول تضمين جملة في رسالة النظام التي تقول "Only use the functions you have been provided with.".
استخدام استدعاء الدالة بمسؤولية
مثل أي نظام الذكاء الاصطناعي، فإن استخدام استدعاء الوظائف لدمج نماذج اللغة مع الأدوات والأنظمة الأخرى يمثل مخاطر محتملة. من المهم فهم المخاطر التي يمكن أن يقدمها استدعاء الوظيفة واتخاذ تدابير لضمان استخدام القدرات بشكل مسؤول.
فيما يلي بعض التلميحات لمساعدتك على استخدام الوظائف بأمان وأمان:
- التحقق من صحة استدعاءات الدالة: تحقق دائما من استدعاءات الدالة التي تم إنشاؤها بواسطة النموذج. يتضمن ذلك التحقق من المعلمات، والدالة التي يتم استدعاؤها، والتأكد من محاذاة الاستدعاء مع الإجراء المقصود.
- استخدام البيانات والأدوات الموثوق بها: استخدم البيانات من مصادر موثوق بها ومتحقق منها فقط. يمكن استخدام البيانات غير الموثوق بها في إخراج الدالة لإرشاد النموذج لكتابة استدعاءات الدالة بطريقة أخرى غير المقصودة.
- اتبع مبدأ الامتياز الأقل: امنح فقط الحد الأدنى access اللازم لأداء الوظيفة لوظيفتها. وهذا يقلل من التأثير المحتمل إذا تم إساءة استخدام دالة أو استغلالها. على سبيل المثال، إذا كنت تستخدم استدعاءات الدوال للاستعلام عن قاعدة بيانات، يجب أن تعطي تطبيقك فقط access للقراءة فقط. يجب أيضا ألا تعتمد فقط على استبعاد القدرات في تعريف الدالة كعنصر تحكم أمان.
- ضع في اعتبارك تأثير العالم الحقيقي: كن على دراية بتأثير استدعاءات الوظائف في العالم الحقيقي التي تخطط لتنفيذها، خاصة تلك التي تؤدي إلى إجراءات مثل تنفيذ التعليمات البرمجية أو تحديث قواعد البيانات أو إرسال الإعلامات.
- تنفيذ خطوات تأكيد المستخدم: خاصة بالنسبة للوظائف التي تتخذ إجراءات، نوصي بتضمين خطوة يؤكد فيها المستخدم الإجراء قبل التنفيذ.
للتعرف أكثر على توصياتنا حول كيفية استخدام نماذج OpenAI Azure بمسؤولية، راجع نظرة عامة على ممارسات الذكاء الاصطناعي المسؤول لنماذج OpenAI Azure.
مهم
تم إلغاء معايير functions و function_call مع إصدار نسخة 2023-12-01-preview من واجهة برمجة التطبيقات. الاستبدال هو functions المعلمة tools . الاستبدال هو function_call المعلمة tool_choice .
دعم استدعاء الدالة
استدعاء الدالة المتوازية
-
gpt-4(2024-04-09) -
gpt-4o(2024-05-13) -
gpt-4o(2024-08-06) -
gpt-4o(2024-11-20) -
gpt-4o-mini(2024-07-18) -
gpt-4.1(2025-04-14) -
gpt-4.1-mini(2025-04-14) -
gpt-5(2025-08-07) -
gpt-5-mini(2025-08-07) -
gpt-5-nano(2025-08-07) -
gpt-5-codex(2025-09-11) -
gpt-5.1(2025-11-13) -
gpt-5.1-chat(2025-11-13) -
gpt-5.1-codex(2025-11-13) -
gpt-5.1-codex-mini(2025-11-13) -
gpt-5.1-codex-max(2025-12-04) -
gpt-5.2(2025-12-11) -
gpt-5.2-chat(2025-12-11) -
gpt-5.2-codex(2026-01-14) -
gpt-5.2-chat(2026-02-10) -
gpt-5.3-codex(2026-02-24) -
gpt-5.3-chat(2026-03-03) -
gpt-5.4(2026-03-05) -
gpt-5.4(2026-03-05) -
gpt-5.4-mini(2026-03-17) -
gpt-5.4-nano(2026-03-17)
تمت إضافة دعم الدالة المتوازية لأول مرة في إصدار API 2023-12-01-preview
استدعاء الدالة الأساسية باستخدام الأدوات
- جميع النماذج التي تدعم استدعاء الدالة المتوازية
-
gpt-5.4-pro(2026-03-05) -
gpt-5-pro(2025-10-06) -
codex-mini(2025-05-16) -
o3-pro(2025-06-10) -
o4-mini(2025-04-16) -
o3(2025-04-16) -
gpt-4.1-nano(2025-04-14) -
o3-mini(2025-01-31) -
o1(2024-12-17)
ملاحظة
المعلمة tool_choice مدعومة الآن مع o3-mini و o1. لمزيد من المعلومات ، راجع دليل نماذج التفكير.
مهم
أوصاف الأداة/الوظائف محدودة حاليا ب 1,024 حرفا مع Azure OpenAI. سنعدل هذه المقالة إذا تم تغيير هذا الحد.
الخطوات التالية
- تعرف أكثر على Azure OpenAI.
- لمزيد من الأمثلة حول العمل مع الدوال، اطلع على مستودع عينات GitHub Azure OpenAI