الخطوة 5 في الوكلاء: تحسين تطبيق الدردشة بأدوات وكيلية

اجمع كل ما بنيته معًا — أضف أدوات إلى الواجهة الخلفية لتطبيق الدردشة ليتمكن الذكاء الاصطناعي من استخدام آلة حاسبة والبحث في ويكيبيديا أثناء المحادثات.

ما ستتعلمه

  • دمج أدوات وكيلية في الواجهة الخلفية القائمة على Flask
  • إضافة سجل المحادثة لتوفير السياق
  • تصحيح أخطاء سلوك الوكيل

الخطوة 1: إضافة دوال الأدوات إلى الواجهة الخلفية

عدّل الملف backend/app/routes.py، وأضف دوال الأدوات في أعلى الملف:

import json
import requests


def calculate(expression: str) -> str:
    """Evaluate a math expression safely."""
    try:
        allowed = set("0123456789+-*/.() ")
        if not all(c in allowed for c in expression):
            return "Error: Invalid characters in expression"
        result = eval(expression)
        return str(result)
    except Exception as e:
        return f"Error: {str(e)}"


def search_wikipedia(query: str) -> str:
    """Search Wikipedia and return a summary."""
    try:
        url = "https://en.wikipedia.org/api/rest_v1/page/summary/" + requests.utils.quote(query)
        response = requests.get(url, timeout=10)
        if response.status_code == 200:
            data = response.json()
            return f"Title: {data['title']}\nSummary: {data['extract'][:500]}"
        elif response.status_code == 404:
            return f"No Wikipedia page found for '{query}'"
        else:
            return f"Wikipedia error: {response.status_code}"
    except Exception as e:
        return f"Error: {str(e)}"

الخطوة 2: تعريف الأدوات لـ OpenAI

tools = [
    {
        "type": "function",
        "function": {
            "name": "calculate",
            "description": "Evaluate a mathematical expression",
            "parameters": {
                "type": "object",
                "properties": {
                    "expression": {
                        "type": "string",
                        "description": "Math expression like '2 + 2'"
                    }
                },
                "required": ["expression"]
            }
        }
    },
    {
        "type": "function",
        "function": {
            "name": "search_wikipedia",
            "description": "Search Wikipedia for a topic and get a summary",
            "parameters": {
                "type": "object",
                "properties": {
                    "query": {
                        "type": "string",
                        "description": "The topic to search for"
                    }
                },
                "required": ["query"]
            }
        }
    }
]

الخطوة 3: تحديث نقطة نهاية الدردشة

استبدل دالة chat() الموجودة:

@api.route("/chat", methods=["POST"])
def chat():
    data = request.get_json()
    user_message = data.get("message", "")

    if not user_message:
        return jsonify({"error": "Message is required"}), 400

    user_msg = Message(content=user_message, sender="user")
    db.session.add(user_msg)
    db.session.commit()

    try:
        # اجلب الرسائل الأخيرة لتوفير السياق
        recent = Message.query.order_by(Message.timestamp.desc()).limit(10).all()
        recent.reverse()

        messages = [
            {"role": "system", "content": "You are a helpful assistant with a calculator and Wikipedia search. Use these tools when needed."}
        ]
        for msg in recent:
            role = "user" if msg.sender == "user" else "assistant"
            messages.append({"role": role, "content": msg.content})

        # حلقة الوكيل
        max_turns = 5
        for _ in range(max_turns):
            response = client.chat.completions.create(
                model="gpt-4o-mini",
                messages=messages,
                tools=tools,
                tool_choice="auto",
            )

            message = response.choices[0].message

            if not message.tool_calls:
                ai_reply = message.content
                break

            messages.append(message)

            for tool_call in message.tool_calls:
                args = json.loads(tool_call.function.arguments)
                if tool_call.function.name == "calculate":
                    result = calculate(args["expression"])
                elif tool_call.function.name == "search_wikipedia":
                    result = search_wikipedia(args["query"])
                else:
                    result = "Unknown tool"

                messages.append({
                    "role": "tool",
                    "tool_call_id": tool_call.id,
                    "content": result,
                })
        else:
            ai_reply = "I couldn't complete that request."

        ai_msg = Message(content=ai_reply, sender="ai")
        db.session.add(ai_msg)
        db.session.commit()

        return jsonify({
            "user_message": user_msg.to_dict(),
            "ai_message": ai_msg.to_dict(),
        })

    except Exception as e:
        return jsonify({"error": str(e)}), 500

الخطوة 4: تثبيت requests

pip install requests

الخطوة 5: اختبار الدردشة الوكيلية

شغّل الواجهة الخلفية:

cd aiproject/backend
source venv/bin/activate
python app/__init__.py

اختبرها باستخدام curl:

# رياضيات — يجب أن يستخدم الآلة الحاسبة
curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "What is 12345 * 6789?"}'

# بحث — يجب أن يبحث في ويكيبيديا
curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Tell me about the Eiffel Tower"}'

# دردشة بسيطة — لا حاجة إلى أدوات
curl -X POST http://localhost:5000/api/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Hello!"}'

كيف يعمل الآن

المستخدم: "What is 12345 * 6789?"

1. تحفظ الواجهة الخلفية رسالة المستخدم في قاعدة البيانات
2. تجلب الواجهة الخلفية الرسائل الأخيرة لتوفير السياق
3. تستدعي الواجهة الخلفية OpenAI مع الأدوات المعرّفة
4. يقرر OpenAI: "I need the calculator tool"
5. تنفّذ الواجهة الخلفية calculate("12345 * 6789")
6. تعيد الواجهة الخلفية نتيجة الأداة إلى OpenAI
7. يرد OpenAI بما يلي: "12345 × 6789 = 83,810,205"
8. تحفظ الواجهة الخلفية استجابة الذكاء الاصطناعي في قاعدة البيانات
9. تعيد الواجهة الخلفية الرسالتين إلى تطبيق الجوال

ما الذي تغيّر

قبل بعد
رد مباشر من الذكاء الاصطناعي يستطيع الذكاء الاصطناعي استخدام الأدوات
لا قدرة على إجراء العمليات الحسابية أداة آلة حاسبة
لا قدرة على البحث أداة ويكيبيديا
استدعاء API واحد استدعاءات متعددة (حلقة الوكيل)
معالجة أخطاء بسيطة حد أقصى للجولات لمنع الحلقات اللانهائية

أصبح تطبيق الدردشة لديك الآن وكيليًا. يستطيع الذكاء الاصطناعي أن يقرر متى يحسب، ومتى يبحث، ومتى يرد مباشرةً.