حدود الخطوات
جزء من قسم الأدوات والوكلاء في رحلة AI Engineering على Coddy. الدرس 9 من 22.
تنتهي حلقة الوكيل عندما يتوقف النموذج عن طلب الأدوات، ولا يوجد ما يضمن أنه سيفعل ذلك. يمكن لأداة تستمر في الفشل مع try again أن تجعل النموذج يعيد المحاولة إلى الأبد، وكل دورة تكلف استدعاءً ورموزًا. ضع حدًا للحلقة:
steps = 1
while response.stop_reason == "tool_use":
if steps == MAX_STEPS:
break
# تشغيل الأدوات، وإلحاق الجولات، واستدعاء النموذج مرة أخرى
steps += 1
if response.stop_reason == "tool_use":
print("Gave up: the task took too many steps")يقع الفحص في بداية الحلقة، لذا لا يجري البرنامج أبدًا استدعاءً برقم MAX_STEPS + 1. بعد الحلقة، يخبرك سبب التوقف بالطريقة التي انتهى بها: لا يزال tool_use يعني أن الحد قد أوقفه ولا توجد إجابة لعرضها. أخبر المستخدم بذلك بدلاً من عدم طباعة أي شيء. غالباً ما تكون إعادات المحاولة صحيحة: فالخدمة التي تنتهي مهلتها مرة واحدة قد تجيب في المحاولة التالية. يتيح الحد للحلقة إعادة المحاولة ومع ذلك تنتهي. تضع وكلاء الإنتاج أيضاً حداً أقصى للرموز والوقت بالطريقة نفسها.
التحدي
متوسطيعمل وكيل المطعم في كود البداية إلى الأبد عندما يستمر نظام الحجز في الفشل، لأن النموذج يعيد المحاولة في كل مرة. أضف حدًا للخطوات.
- في أعلى الحلقة، استخدم
breakعندما تتساوىstepsمعMAX_STEPS. - بعد الحلقة، إذا كان سبب التوقف لا يزال
"tool_use"، اطبعStopped: no answer after 5 steps(استخدمMAX_STEPS). - استمر في طباعة الإجابة، عند توفرها، والخطوات.
على سبيل المثال، بالنسبة للإدخال Is there a table at Golden Dragon tonight? يطبع البرنامج:
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Tool: check_table {'restaurant': 'Golden Dragon'} -> error: The booking system is temporarily unavailable, try again
Stopped: no answer after 5 steps
Steps: 5جرّب بنفسك
import coddy_ai as anthropic # في بيئة الإنتاج: import anthropic
client = anthropic.Anthropic()
MAX_STEPS = 5
TABLES = {"Bella Vista": "a table for two at 8 pm", "Sunset Grill": "a table by the window at 9 pm"}
attempts = {}
def check_table(restaurant):
attempts[restaurant] = attempts.get(restaurant, 0) + 1
if restaurant == "Golden Dragon":
raise TimeoutError("The booking system is temporarily unavailable, try again")
if restaurant == "Sunset Grill" and attempts[restaurant] < 3:
raise TimeoutError("The booking system timed out, try again")
if restaurant in TABLES:
return f"{restaurant} has {TABLES[restaurant]}"
return f"{restaurant} has no free table tonight"
TOOLS = [
{
"name": "check_table",
"description": "Check if a restaurant has a free table tonight",
"input_schema": {
"type": "object",
"properties": {"restaurant": {"type": "string", "description": "The restaurant name"}},
"required": ["restaurant"],
},
}
]
def run_tool(block):
try:
output = check_table(**block.input)
except TimeoutError as error:
print(f"Tool: {block.name} {block.input} -> error: {error}")
return {"type": "tool_result", "tool_use_id": block.id, "content": str(error), "is_error": True}
print(f"Tool: {block.name} {block.input} -> {output}")
return {"type": "tool_result", "tool_use_id": block.id, "content": output}
request = input()
messages = [{"role": "user", "content": request}]
# أوقف الحلقة عندما يتم استدعاء النموذج MAX_STEPS من المرات
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
steps = 1
while response.stop_reason == "tool_use":
messages.append({"role": "assistant", "content": response.content})
results = [run_tool(block) for block in response.content if block.type == "tool_use"]
messages.append({"role": "user", "content": results})
response = client.messages.create(model="claude-opus-5-5", max_tokens=500, tools=TOOLS, messages=messages)
steps += 1
for block in response.content:
if block.type == "text":
print("Answer: " + block.text)
print(f"Steps: {steps}")
يتضمن هذا الدرس اختبارًا قصيرًا. ابدأ الدرس للإجابة عليه وتتبّع تقدمك.
جميع دروس الأدوات والوكلاء
1أساسيات استخدام الأدوات
تعريف أداةقراءة استدعاء الأداةإرجاع نتائج الأداةالاختيار بين الأدواتمراجعة: مكتب الطقستدرّب بنفسك: مترجم Python عبر الإنترنت