أدوات مدمجة

يوفر adk-rust العديد من الأدوات المدمجة التي توسع قدرات Agent دون الحاجة إلى تطبيق مخصص. هذه الأدوات جاهزة للاستخدام فورًا وتتكامل بسلاسة مع إطار عمل Agent.

نظرة عامة

أداةالغرضحالة الاستخدام
GoogleSearchToolبحث الويب عبر Geminiاسترجاع المعلومات في الوقت الفعلي
ExitLoopToolإنهاء Loopالتحكم في تكرارات LoopAgent
LoadArtifactsToolتحميل Artifactالوصول إلى البيانات الثنائية المخزنة

GoogleSearchTool

GoogleSearchTool تمكّن Agent من البحث في الويب باستخدام Google Search. يتم التعامل مع هذه الأداة داخليًا بواسطة نماذج Gemini من خلال ميزة "grounding"، مما يعني أن البحث يتم تنفيذه من جانب الخادم بواسطة النموذج نفسه.

الاستخدام الأساسي

use adk_rust::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;

    // Create the GoogleSearchTool
    let search_tool = GoogleSearchTool;

    // Add to agent
    let agent = LlmAgentBuilder::new("research_assistant")
        .description("An assistant that can search the web for information")
        .instruction(
            "You are a research assistant. When asked about current events, \
             recent news, or factual information, use the google_search tool \
             to find accurate, up-to-date information."
        )
        .model(Arc::new(model))
        .tool(Arc::new(search_tool))
        .build()?;

    println!("Agent created with Google Search capability!");
    Ok(())
}

كيف تعمل

على عكس أدوات FunctionTool العادية، تعمل GoogleSearchTool بشكل مختلف:

  1. التنفيذ من جانب الخادم: يتم إجراء البحث بواسطة ميزة "grounding" في Gemini، وليس محليًا
  2. الاستدعاء التلقائي: يقرر النموذج متى يبحث بناءً على الاستعلام
  3. النتائج المتكاملة: يتم دمج نتائج البحث مباشرة في استجابة النموذج

يعيد تطبيق الأداة خطأً إذا تم استدعاؤها مباشرة لأن البحث الفعلي يحدث ضمن Gemini API:

// This is handled internally - you don't call it directly
async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
    Err(AdkError::Tool("GoogleSearch is handled internally by Gemini".to_string()))
}

تفاصيل الأداة

خاصيةقيمة
الاسمgoogle_search
الوصف"تقوم بإجراء بحث Google لاسترداد المعلومات من الويب."
المعلماتيحددها نموذج Gemini
التنفيذمن جانب الخادم (Gemini grounding)

حالات الاستخدام

  • الأحداث الجارية: "ماذا حدث في الأخبار اليوم؟"
  • الاستعلامات الواقعية: "ما هو عدد سكان طوكيو؟"
  • المعلومات الحديثة: "ما هي أحدث التطورات في الذكاء الاصطناعي؟"
  • مهام البحث: "ابحث عن معلومات حول اتجاهات الطاقة المتجددة"

أمثلة الاستعلامات

// The agent will automatically use Google Search for queries like:
// - "What's the weather forecast for New York this week?"
// - "Who won the latest championship game?"
// - "What are the current stock prices for tech companies?"

ExitLoopTool

ExitLoopTool هي أداة تحكم تُستخدم مع LoopAgent للإشارة إلى متى يجب إنهاء عملية تكرارية. عند استدعائها، تقوم بتعيين العلامة escalate، مما يتسبب في خروج الحلقة.

الاستخدام الأساسي

use adk_rust::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;

    // Create an agent with ExitLoopTool for iterative refinement
    let refiner = LlmAgentBuilder::new("content_refiner")
        .description("Iteratively improves content quality")
        .instruction(
            "Review the content and improve it. Check for:\n\
             1. Clarity and readability\n\
             2. Grammar and spelling\n\
             3. Logical flow\n\n\
             If the content meets all quality standards, call the exit_loop tool.\n\
             Otherwise, provide an improved version."
        )
        .model(Arc::new(model))
        .tool(Arc::new(ExitLoopTool::new()))
        .build()?;

    // Use in a LoopAgent
    let loop_agent = LoopAgent::new(
        "iterative_refiner",
        vec![Arc::new(refiner)],
    ).with_max_iterations(5);

    println!("Loop agent created with exit capability!");
    Ok(())
}

كيف يعمل

  1. يقوم العميل بتقييم ما إذا كان سيستمر أم سيخرج
  2. عندما يكون جاهزًا للخروج، يستدعي العميل exit_loop
  3. تقوم الأداة بتعيين actions.escalate = true وactions.skip_summarization = true
  4. يكتشف LoopAgent علامة escalate ويتوقف عن التكرار

تفاصيل الأداة

الخاصيةالقيمة
الاسمexit_loop
الوصف"يخرج من الحلقة. استدعِ هذه الدالة فقط عندما يُطلب منك ذلك."
المعلماتلا شيء
الإرجاعكائن فارغ {}

أفضل الممارسات

  1. معايير خروج واضحة: حدد شروطًا محددة في تعليمات العميل
  2. تعيين max_iterations دائمًا: لمنع الحلقات اللانهائية كإجراء أمان
  3. تعليمات ذات معنى: ساعد العميل على فهم متى يجب الخروج
// Good: Clear exit criteria
.instruction(
    "Improve the text until it:\n\
     - Has no grammatical errors\n\
     - Is under 100 words\n\
     - Uses active voice\n\
     When all criteria are met, call exit_loop."
)

// Avoid: Vague criteria
.instruction("Improve the text. Exit when done.")

أداة LoadArtifactsTool

تتيح LoadArtifactsTool للوكلاء استرداد البيانات المخزنة (artifacts) بالاسم. هذا مفيد عندما يحتاج الوكلاء إلى الوصول إلى الملفات أو الصور أو غيرها من البيانات الثنائية التي تم حفظها مسبقًا.

الاستخدام الأساسي

use adk_rust::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;

    // Create agent with artifact loading capability
    let agent = LlmAgentBuilder::new("document_analyzer")
        .description("Analyzes stored documents")
        .instruction(
            "You can load and analyze stored artifacts. \
             Use the load_artifacts tool to retrieve documents by name. \
             The tool accepts an array of artifact names."
        )
        .model(Arc::new(model))
        .tool(Arc::new(LoadArtifactsTool::new()))
        .build()?;

    println!("Agent created with artifact loading capability!");
    Ok(())
}

تفاصيل الأداة

الخاصيةالقيمة
Nameload_artifacts
Description"تحمل الـ artifacts بالاسم وتُرجع محتواها. تقبل مصفوفة من أسماء الـ artifacts."
Parametersartifact_names: مصفوفة من السلاسل النصية
Returnsكائن يحتوي على مصفوفة artifacts

المعلمات

تتوقع الأداة كائن JSON يحتوي على مصفوفة artifact_names:

{
  "artifact_names": ["document.txt", "image.png", "data.json"]
}

تنسيق الاستجابة

تُرجع الأداة كائنًا يحتوي على الـ artifacts المحملة:

{
  "artifacts": [
    {
      "name": "document.txt",
      "content": "The text content of the document..."
    },
    {
      "name": "image.png",
      "content": {
        "mime_type": "image/png",
        "data": "base64-encoded-data..."
      }
    },
    {
      "name": "missing.txt",
      "error": "Artifact not found"
    }
  ]
}

المتطلبات

لكي تعمل LoadArtifactsTool، تحتاج إلى:

  1. ArtifactService مهيأة في الـ runner
  2. Artifacts تم حفظها مسبقًا في الـ service
  3. الأداة مضافة إلى الـ agent
use adk_rust::prelude::*;
use std::sync::Arc;

// Set up artifact service
let artifact_service = Arc::new(InMemoryArtifactService::new());

// Configure runner with artifact service
let runner = Runner::new(agent)
    .with_artifact_service(artifact_service);

دمج الأدوات المدمجة

يمكنك استخدام أدوات مدمجة متعددة معًا:

use adk_rust::prelude::*;
use std::sync::Arc;

#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let api_key = std::env::var("GOOGLE_API_KEY")?;
    let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;

    // Create agent with multiple built-in tools
    let agent = LlmAgentBuilder::new("research_agent")
        .description("Research agent with search and artifact capabilities")
        .instruction(
            "You are a research agent. You can:\n\
             - Search the web using google_search for current information\n\
             - Load stored documents using load_artifacts\n\
             Use these tools to help answer questions comprehensively."
        )
        .model(Arc::new(model))
        .tool(Arc::new(GoogleSearchTool))
        .tool(Arc::new(LoadArtifactsTool::new()))
        .build()?;

    println!("Multi-tool agent created!");
    Ok(())
}

إنشاء أدوات مدمجة مخصصة

يمكنك إنشاء أدواتك الخاصة باتباع نفس النمط المتبع في الأدوات المضمنة (built-in tools) عن طريق تطبيق الـ Tool trait:

use adk_rust::prelude::*;
use async_trait::async_trait;
use serde_json::{json, Value};
use std::sync::Arc;

pub struct MyCustomTool;

impl MyCustomTool {
    pub fn new() -> Self {
        Self
    }
}

#[async_trait]
impl Tool for MyCustomTool {
    fn name(&self) -> &str {
        "my_custom_tool"
    }

    fn description(&self) -> &str {
        "وصف لما تفعله هذه الأداة"
    }

    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
        // منطق أداتك هنا
        Ok(json!({ "result": "success" }))
    }
}

مرجع الـ API

GoogleSearchTool

impl GoogleSearchTool {
    /// إنشاء مثيل GoogleSearchTool جديد
    pub fn new() -> Self;
}

ExitLoopTool

impl ExitLoopTool {
    /// إنشاء مثيل ExitLoopTool جديد
    pub fn new() -> Self;
}

LoadArtifactsTool

impl LoadArtifactsTool {
    /// إنشاء مثيل LoadArtifactsTool جديد
    pub fn new() -> Self;
}

impl Default for LoadArtifactsTool {
    fn default() -> Self;
}

ذات صلة

  • Function Tools - إنشاء Function Tools مخصصة
  • MCP Tools - استخدام خوادم MCP كمزودي أدوات
  • Workflow Agents - استخدام ExitLoopTool مع LoopAgent
  • Artifacts - إدارة البيانات الثنائية باستخدام Artifacts

السابق: ← Function Tools | التالي: Browser Tools →