بناء نظام أتمتة سير العمل باستخدام Claude 4.5

Share:
درس تقني
خبير
⏱ ٦٠ دقيقة قراءة
© بوابة الذكاء الاصطناعي ٢٠٢٦-٠٤-٢١

رؤية-لغة-عمل للمؤسسات: تصميم وكيل سطح مكتب مستقل باستخدام Claude 4.5

الانتقال من روبوتات الدردشة النصية إلى مشغلي الأنظمة المستقلة. تعلم كيفية تنظيم سير العمل لرؤية-لغة-عمل (VLA) بشكل آمن لتمكين الذكاء الاصطناعي من التنقل في الواجهات الرسومية، والتفاعل مع البرمجيات القديمة الخاصة، وأداء التفكير المكاني المعقد.

المتطلبات الأساسية

  • Python 3.12+ (يوصى ببيئة المؤسسات)
  • Anthropic Tier 3+ API Access (مطلوب لحدود التردد العالية متعددة الوسائط لـ Claude 4.5)
  • Docker Engine (مطلوب بشدة لتوفير بيئة Xvfb الافتراضية)
  • فهم متقدم لتخطيط إحداثيات واجهة المستخدم، تجريد DOM، وترميز الصور base64

فهم نموذج VLA

تتفاعل نماذج اللغة الكبيرة القياسية (LLMs) بشكل بحت عبر نقاط نهاية API وتيارات نصية. ومع ذلك، فإن ٨٠٪ من برمجيات المؤسسات — مثل أنظمة ERP القديمة، عملاء قاعدة البيانات المحلية GUI، أو بوابات الرعاية الصحية المخصصة — تفتقر إلى واجهات API قوية. هنا تأتي نماذج رؤية-لغة-عمل (VLA) لسد الفجوة.

من خلال الاستفادة من بنية “استخدام الكمبيوتر” في Claude 4.5، يعمل الوكيل تمامًا مثل الموظف البشري: “يرى” الشاشة عبر أخذ عينات بصرية مستمرة، “يفكر” في خطوات سير العمل اللازمة باستخدام التفكير المكاني الكثيف، و”يعمل” من خلال التحكم في الفأرة ولوحة المفاتيح الفعلية.

الخطوة ١: تعزيز البيئة والعزل (مهم)

يحمل التحكم في واجهة المستخدم مخاطر شديدة، بما في ذلك الحذف العرضي للبيانات أو التعديلات غير المقصودة على نظام المضيف. لا تقم أبدًا بتنفيذ وكلاء VLA مباشرة على جهازك المضيف. يجب علينا عزل الوكيل داخل حاوية Ubuntu مزودة بعرض افتراضي (Xvfb).

قم بإنشاء Dockerfile التالي لتوفير بيئة تنفيذ آمنة:


FROM python:3.12-slim

# Install X virtual framebuffer and UI automation dependencies
RUN apt-get update && apt-get install -y 
    xvfb 
    x11-utils 
    scrot 
    python3-tk 
    python3-dev 
    && rm -rf /var/lib/apt/lists/*

WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Start virtual display on port :99 before executing the Python agent
CMD ["sh", "-c", "Xvfb :99 -screen 0 1920x1080x24 & export DISPLAY=:99 && python agent_core.py"]
  

يجب أن يتضمن requirements.txt الخاص بك: anthropic pyautogui mss opencv-python-headless python-dotenv.

الخطوة ٢: وحدة القياس البصري

يتطلب الوكيل تدفقًا بصريًا عالي الدقة. نستخدم mss لالتقاط الشاشة بزمن انتقال منخفض للغاية. في هذا المقتطف الجاهز للإنتاج، نقدم وحدة logging الأصلية في Python للحفاظ على سجل تدقيق لإدراك الوكيل.


import mss
import base64
import logging
from PIL import Image
import io

# Initialize enterprise logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - [AGENT-VISION] - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

def capture_visual_context():
    """Captures the virtual display and encodes it for Claude 4.5 ingestion."""
    try:
        with mss.mss() as sct:
            monitor = sct.monitors[1] # Target the Xvfb primary display
            sct_img = sct.grab(monitor)
            
            # Convert to PIL Image for optimization
            img = Image.frombytes("RGB", sct_img.size, sct_img.bgra, "raw", "BGRX")
            
            # Downscale to 1280x720 to optimize token consumption while preserving UI text legibility
            img.thumbnail((1280, 720)) 
            
            buffered = io.BytesIO()
            img.save(buffered, format="JPEG", quality=85)
            
            logger.info(f"Visual context captured at resolution: {img.size}")
            return base64.b64encode(buffered.getvalue()).decode('utf-8')
    except Exception as e:
        logger.error(f"Visual telemetry failure: {e}")
        raise
  

الخطوة ٣: تعريف مخطط العمل

يجب علينا تسجيل مخطط JSON صارم يحدد بالضبط كيف يُسمح للذكاء الاصطناعي بالتفاعل مع نظام التشغيل. يتم تحسين Claude 4.5 أصلاً لهذا التخطيط الهيكلي المحدد.


import anthropic

client = anthropic.Anthropic()

os_control_tool = {
    "name": "os_gui_interaction",
    "description": "Execute deterministic keyboard and mouse commands on the virtual desktop environment.",
    "input_schema": {
        "type": "object",
        "properties": {
            "action": {"type": "string", "enum": ["left_click", "double_click", "type_text", "scroll", "drag_and_drop"]},
            "coordinates": {"type": "array", "items": {"type": "integer"}, "description": "[x, y] coordinates mapping to the 1920x1080 display"},
            "text_payload": {"type": "string", "description": "String payload to input if action is 'type_text'"}
        },
        "required": ["action"]
    }
}
  

الخطوة ٤: الحلقة الإدراكية المستقلة

المحرك الأساسي هو حلقة تكرارية. يدرك الوكيل الشاشة، يفكر في الهدف، يصدر أمر أداة، ينفذ البرنامج النصي عمل نظام التشغيل، ويتحقق الوكيل من النتيجة في المرور البصري التالي.


import pyautogui
import time
import os

def orchestrate_agent(objective):
    logger.info(f"Initiating Agentic Workflow: {objective}")
    messages = [{"role": "user", "content": [{"type": "text", "text": objective}]}]
    
    # Strict execution ceiling to prevent infinite compute drain
    MAX_STEPS = 15 
    
    for step in range(MAX_STEPS):
        logger.info(f"--- Execution Cycle {step + 1}/{MAX_STEPS} ---")
        
        b64_image = capture_visual_context()
        messages[-1]["content"].append({
            "type": "image",
            "source": {"type": "base64", "media_type": "image/jpeg", "data": b64_image}
        })
        
        response = client.messages.create(
            model="claude-4-5-sonnet-20260215", 
            max_tokens=1500,
            tools=[os_control_tool],
            messages=messages
        )
        
        if response.stop_reason == "tool_use":
            tool_call = response.content[-1]
            action = tool_call.input.get("action")
            
            logger.info(f"Agent Action Triggered: {action}")
            
            try:
                # Physical Execution Layer
                if action in ["left_click", "double_click"]:
                    x, y = tool_call.input["coordinates"]
                    pyautogui.moveTo(x, y, duration=0.2) # Smooth movement prevents anti-bot triggers
                    pyautogui.click(clicks=2 if action == "double_click" else 1)
                elif action == "type_text":
                    pyautogui.write(tool_call.input["text_payload"], interval=0.03)
                    pyautogui.press("enter")
                    
                # Acknowledge success to the agent
                messages.append({"role": "assistant", "content": [tool_call]})
                messages.append({
                    "role": "user", 
                    "content": [{"type": "tool_result", "tool_use_id": tool_call.id, "content": "Action executed successfully. Awaiting visual confirmation."}]
                })
                
                # Allow UI to render before next capture
                time.sleep(1.5) 
                
            except Exception as e:
                logger.error(f"Execution failed: {e}")
                # Self-correction: Inform the agent of the error so it can try a different approach
                messages.append({
                    "role": "user", 
                    "content": [{"type": "tool_result", "tool_use_id": tool_call.id, "content": f"ERROR: {str(e)}"}]
                })
        else:
            logger.info("Workflow successfully completed by Agent.")
            break

# Execute the workflow
if __name__ == "__main__":
    orchestrate_agent("Open the legacy accounting app, locate invoice #8842, and extract the total amount into a new text file.")
  
🚀 حاجز الإنتاج: في بيئة المؤسسات الحقيقية، قم بتنفيذ طبقة تحقق OpenCV Template Matching. قبل تنفيذ `pyautogui.click()`, قم باستخراج جزء صغير من الزر من لقطة الشاشة الأولية. تأكد من أن الجزء البصري لا يزال موجودًا في إحداثيات X/Y المستهدفة لمنع النقرات الكارثية إذا تحولت واجهة المستخدم بشكل غير متوقع أو حجب إشعار الشاشة.

دعم المطور التفاعلي

يتضمن تنفيذ نماذج رؤية-لغة-عمل في بيئات المؤسسات متغيرات معقدة، من تكوينات عرض Docker إلى معالجة الأخطاء غير المتزامنة. لست مضطرًا لحل المشاكل بمفردك.

هل تحتاج إلى تكييف هذا البرنامج النصي لبرمجياتك الخاصة؟ تواجه مشاكل في تخطيط الإحداثيات؟

تفاعل مع مساعد بوابة الذكاء الاصطناعي التقني مباشرة في واجهة الدردشة أدناه. ذكاءنا الاصطناعي التفاعلي مدرك تمامًا لهذا الدرس ويمكنه مساعدتك في تصحيح الأخطاء البرمجية، تحسين ملف Dockerfile الخاص بك، أو تصميم مخططات استخدام الكمبيوتر المخصصة التي تناسب متطلبات سير العمل الخاصة بك.

Share:

هل كان هذا الشرح مفيداً؟

ابحث عن ما تريد