फ़ंक्शन टूल्स
कस्टम Rust फ़ंक्शनों के साथ एजेंट क्षमताओं का विस्तार करें।
फ़ंक्शन टूल्स क्या हैं?
फ़ंक्शन टूल्स आपको एजेंटों को बातचीत से आगे की क्षमताएँ देने देते हैं - APIs को कॉल करना, गणनाएँ करना, डेटाबेस तक पहुँचना, या कोई भी कस्टम लॉजिक। LLM उपयोगकर्ता के अनुरोध के आधार पर तय करता है कि कब किसी टूल का उपयोग करना है।
मुख्य बातें:
- 🚀
#[tool]macro - शून्य-बॉयलरप्लेट टूल रजिस्ट्रेशन (अनुशंसित)- 🔧
FunctionTool::new()- किसी भी async फ़ंक्शन को मैन्युअल रूप से रैप करें- 📝 JSON parameters - लचीला इनपुट/आउटपुट
- 🎯 Type-safe schemas - types से schemars के माध्यम से स्वचालित JSON Schema
- 🔗 Context access - session state, artifacts, memory
टूल निष्पादन पाइपलाइन
अनुशंसित: #[tool] Macro
टूल्स बनाने का सबसे तेज़ तरीका। यह macro आपकी doc comment को विवरण के रूप में पढ़ता है और आपके args type से JSON schema निकालता है:
use adk_tool::tool;
use adk_core::AdkError;
use schemars::JsonSchema;
use serde::Deserialize;
use serde_json::{json, Value};
#[derive(Deserialize, JsonSchema)]
struct WeatherArgs {
/// The city to look up
city: String,
/// Temperature unit (celsius or fahrenheit)
unit: Option<String>,
}
/// Get the current weather for a city.
#[tool]
async fn get_weather(args: WeatherArgs) -> Result<Value, AdkError> {
Ok(json!({ "temp": 22, "city": args.city }))
}
// Generated: pub struct GetWeather; — implements adk_core::Tool
// Use it: agent_builder.tool(Arc::new(GetWeather))
यदि आपके टूल को session context की आवश्यकता है, तो Arc<dyn ToolContext> को पहले parameter के रूप में जोड़ें:
use adk_core::ToolContext;
use std::sync::Arc;
/// Search the user's saved documents.
#[tool]
async fn search_docs(
ctx: Arc<dyn ToolContext>,
args: SearchArgs,
) -> Result<Value, AdkError> {
let user_id = ctx.user_id();
// ... use context for scoped access
}
Tool Metadata Attributes
टूल्स को macro में सीधे read-only, concurrency-safe, या long-running के रूप में चिह्नित करें:
/// Look up cached data — no side effects, safe for parallel dispatch.
#[tool(read_only, concurrency_safe)]
async fn cache_lookup(args: LookupArgs) -> Result<Value, AdkError> {
Ok(json!({"result": "cached"}))
}
/// Start a long-running background report.
#[tool(long_running)]
async fn generate_report(args: ReportArgs) -> Result<Value, AdkError> {
Ok(json!({"task_id": "abc123", "status": "processing"}))
}
उपलब्ध attributes (सभी वैकल्पिक हैं, इन्हें स्वतंत्र रूप से combine किया जा सकता है):
| विशेषता | प्रभाव |
|---|---|
read_only | is_read_only() → true — समवर्ती Auto प्रेषण के लिए आवश्यक दो संकेतों में से एक |
concurrency_safe | is_concurrency_safe() → true — समवर्ती Auto प्रेषण के लिए आवश्यक दो संकेतों में से एक |
long_running | is_long_running() → true — लंबित टूल को पुनः कॉल करने से LLM को रोकता है |
Plain #[tool] बिना attributes के defaults बनाए रखता है (सभी false), इसलिए मौजूदा code अप्रभावित रहता है।
विकल्प: FunctionTool::new()
Dynamic tools के लिए या जब आप explicit registration पसंद करते हों:
FunctionTool::new() के साथ एक tool बनाएं और हमेशा एक schema जोड़ें ताकि LLM को पता हो कि कौन-से parameters पास करने हैं:
use adk_rust::prelude::*;
use adk_rust::Launcher;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::sync::Arc;
#[derive(JsonSchema, Serialize, Deserialize)]
struct WeatherParams {
/// The city or location to get weather for
location: String,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
let api_key = std::env::var("GOOGLE_API_KEY")?;
let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;
// Weather tool with proper schema
let weather_tool = FunctionTool::new(
"get_weather",
"Get current weather for a location",
|_ctx, args| async move {
let location = args.get("location")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
Ok(json!({
"location": location,
"temperature": "22°C",
"conditions": "sunny"
}))
},
)
.with_parameters_schema::<WeatherParams>(); // Required for LLM to call correctly!
let agent = LlmAgentBuilder::new("weather_agent")
.instruction("You help users check the weather. Always use the get_weather tool.")
.model(Arc::new(model))
.tool(Arc::new(weather_tool))
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
⚠️ महत्वपूर्ण: हमेशा
.with_parameters_schema<T>()का उपयोग करें - इसके बिना, LLM को पता नहीं होगा कि कौन-से parameters पास करने हैं और हो सकता है tool call न करे।
यह कैसे काम करता है:
- User पूछता है: "What's the weather in Tokyo?"
- LLM
get_weatherको{"location": "Tokyo"}के साथ call करने का निर्णय लेता है - Tool
{"location": "Tokyo", "temperature": "22°C", "conditions": "sunny"}लौटाता है - LLM response को format करता है: "The weather in Tokyo is sunny at 22°C."
चरण 2: Parameter Handling
JSON args से parameters निकालें:
let order_tool = FunctionTool::new(
"process_order",
"Process an order. Parameters: product_id (required), quantity (required), priority (optional)",
|_ctx, args| async move {
// Required parameters - return error if missing
let product_id = args.get("product_id")
.and_then(|v| v.as_str())
.ok_or_else(|| adk_core::AdkError::tool("product_id is required"))?;
let quantity = args.get("quantity")
.and_then(|v| v.as_i64())
.ok_or_else(|| adk_core::AdkError::tool("quantity is required"))?;
// Optional parameter with default
let priority = args.get("priority")
.and_then(|v| v.as_str())
.unwrap_or("normal");
Ok(json!({
"order_id": "ORD-12345",
"product_id": product_id,
"quantity": quantity,
"priority": priority,
"status": "confirmed"
}))
},
);
चरण 3: Schema के साथ Typed Parameters
Complex tools के लिए, JSON Schema के साथ typed structs का उपयोग करें:
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(JsonSchema, Serialize, Deserialize)]
struct CalculatorParams {
/// The arithmetic operation to perform
operation: Operation,
/// First operand
a: f64,
/// Second operand
b: f64,
}
#[derive(JsonSchema, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum Operation {
Add,
Subtract,
Multiply,
Divide,
}
let calculator = FunctionTool::new(
"calculator",
"Perform arithmetic operations",
|_ctx, args| async move {
let params: CalculatorParams = serde_json::from_value(args)?;
let result = match params.operation {
Operation::Add => params.a + params.b,
Operation::Subtract => params.a - params.b,
Operation::Multiply => params.a * params.b,
Operation::Divide if params.b != 0.0 => params.a / params.b,
Operation::Divide => return Err(adk_core::AdkError::tool("Cannot divide by zero")),
};
Ok(json!({ "result": result }))
},
)
.with_parameters_schema::<CalculatorParams>();
Schema, schemars का उपयोग करके Rust types से auto-generated होता है।
चरण 4: बहु-टूल एजेंट
एक एजेंट में कई टूल जोड़ें:
let agent = LlmAgentBuilder::new("assistant")
.instruction("Help with calculations, conversions, and weather.")
.model(Arc::new(model))
.tool(Arc::new(calc_tool))
.tool(Arc::new(convert_tool))
.tool(Arc::new(weather_tool))
.build()?;
LLM उपयोगकर्ता के अनुरोध के आधार पर स्वतः सही टूल चुनता है।
त्रुटि प्रबंधन
टूल-विशिष्ट विफलताओं के लिए Tool घटक के साथ त्रुटियाँ लौटाएँ:
use adk_core::{AdkError, ErrorComponent, ErrorCategory};
let divide_tool = FunctionTool::new(
"divide",
"Divide two numbers",
|_ctx, args| async move {
let a = args.get("a").and_then(|v| v.as_f64())
.ok_or_else(|| AdkError::new(
ErrorComponent::Tool,
ErrorCategory::InvalidInput,
"tool.divide.missing_param",
"Parameter 'a' is required",
))?;
let b = args.get("b").and_then(|v| v.as_f64())
.ok_or_else(|| AdkError::new(
ErrorComponent::Tool,
ErrorCategory::InvalidInput,
"tool.divide.missing_param",
"Parameter 'b' is required",
))?;
if b == 0.0 {
return Err(AdkError::new(
ErrorComponent::Tool,
ErrorCategory::InvalidInput,
"tool.divide.division_by_zero",
"Cannot divide by zero",
));
}
Ok(json!({ "result": a / b }))
},
);
त्वरित माइग्रेशन के लिए, backward-compatible शॉर्टहैंड भी काम करता है:
Err(AdkError::tool("Parameter 'a' is required"))
त्रुटि संदेश LLM को पास किए जाते हैं, जो पुनः प्रयास कर सकता है या अलग इनपुट मांग सकता है।
टूल संदर्भ
ToolContext के माध्यम से सत्र जानकारी तक पहुँचें:
#[derive(JsonSchema, Serialize, Deserialize)]
struct GreetParams {
#[serde(default)]
message: Option<String>,
}
let greet_tool = FunctionTool::new(
"greet",
"Greet the user with session info",
|ctx, _args| async move {
let user_id = ctx.user_id();
let session_id = ctx.session_id();
let agent_name = ctx.agent_name();
Ok(json!({
"greeting": format!("Hello, user {}!", user_id),
"session": session_id,
"served_by": agent_name
}))
},
)
.with_parameters_schema::<GreetParams>();
उपलब्ध संदर्भ:
ctx.user_id()- वर्तमान उपयोगकर्ता IDctx.session_id()- वर्तमान सत्र IDctx.agent_name()- एजेंट का नामctx.artifacts()- आर्टिफ़ैक्ट स्टोरेज तक पहुँचctx.search_memory(query)- मेमोरी सेवा खोजें
लंबे समय तक चलने वाले टूल
उन कार्यों के लिए जो पर्याप्त समय लेते हैं (डेटा प्रोसेसिंग, बाहरी APIs), non-blocking पैटर्न का उपयोग करें:
- स्टार्ट टूल तुरंत एक task_id लौटाता है
- पृष्ठभूमि कार्य असिंक्रोनस रूप से चलता है
- स्थिति टूल उपयोगकर्ताओं को प्रगति जांचने देता है
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::RwLock;
#[derive(JsonSchema, Serialize, Deserialize)]
struct ReportParams {
topic: String,
}
#[derive(JsonSchema, Serialize, Deserialize)]
struct StatusParams {
task_id: String,
}
// Shared task store
let tasks: Arc<RwLock<HashMap<String, TaskState>>> = Arc::new(RwLock::new(HashMap::new()));
let tasks1 = tasks.clone();
let tasks2 = tasks.clone();
// Tool 1: Start (returns immediately)
let start_tool = FunctionTool::new(
"generate_report",
"Start generating a report. Returns task_id immediately.",
move |_ctx, args| {
let tasks = tasks1.clone();
async move {
let topic = args.get("topic").and_then(|v| v.as_str()).unwrap_or("general").to_string();
let task_id = format!("task_{}", rand::random::<u32>());
// Store initial state
tasks.write().await.insert(task_id.clone(), TaskState {
status: "processing".to_string(),
progress: 0,
result: None,
});
// Spawn background work (non-blocking!)
let tasks_bg = tasks.clone();
let tid = task_id.clone();
tokio::spawn(async move {
// Simulate work...
tokio::time::sleep(tokio::time::Duration::from_secs(10)).await;
if let Some(t) = tasks_bg.write().await.get_mut(&tid) {
t.status = "completed".to_string();
t.result = Some("Report complete".to_string());
}
});
// Return immediately with task_id
Ok(json!({"task_id": task_id, "status": "processing"}))
}
},
)
.with_parameters_schema::<ReportParams>()
.with_long_running(true); // Mark as long-running
// Tool 2: Check status
let status_tool = FunctionTool::new(
"check_report_status",
"Check report generation status",
move |_ctx, args| {
let tasks = tasks2.clone();
async move {
let task_id = args.get("task_id").and_then(|v| v.as_str()).unwrap_or("");
if let Some(t) = tasks.read().await.get(task_id) {
Ok(json!({"status": t.status, "result": t.result}))
} else {
Ok(json!({"error": "Task not found"}))
}
}
},
)
.with_parameters_schema::<StatusParams>();
मुख्य बिंदु:
.with_long_running(true)एजेंट को बताता है कि यह टूल एक लंबित स्थिति लौटाता है- टूल
tokio::spawn()के साथ कार्य शुरू करता है और तुरंत लौट आता है - एक स्थिति-जांच टूल प्रदान करें ताकि उपयोगकर्ता प्रगति को पोल कर सकें
यह LLM को टूल को बार-बार कॉल करने से रोकने के लिए एक नोट जोड़ता है।
किसी टूल से स्ट्रीमिंग प्रगति
लंबे समय तक चलने वाले टूल अभी भी
चल रहे होते हुए UI पर मध्यवर्ती आउटपुट पुश कर सकते हैं, ताकि उपयोगकर्ता शेल कमांड के stdout, बिल्ड के लॉग, या
डाउनलोड के बाइट्स को अंतिम परिणाम की प्रतीक्षा किए बिना लाइव देख सके। आउटपुट आते ही ToolContext::emit_progress को कॉल करें:
use adk_core::{Result, Tool, ToolContext};
use std::sync::Arc;
#[async_trait::async_trait]
impl Tool for BuildTool {
// ... name(), description(), parameters_schema() ...
async fn execute(&self, ctx: Arc<dyn ToolContext>, args: serde_json::Value) -> Result<serde_json::Value> {
// Emit chunks as they arrive — each becomes a partial Event on the
// agent's EventStream, the SAME stream the model's reply travels on.
ctx.emit_progress("stdout", "Compiling project...\n").await;
ctx.emit_progress("stdout", "Build finished in 4.2s\n").await;
ctx.emit_progress("stderr", "warning: unused variable `x`\n").await;
// The final return value is still the complete result the model consumes.
Ok(serde_json::json!({ "status": "ok", "warnings": 1 }))
}
}
सिग्नेचर:
async fn emit_progress(&self, stream: &str, chunk: &str)
stream— चंक के लिए एक लेबल:"stdout","stderr", या कोई भी कस्टम चैनल।chunk— उत्सर्जित करने के लिए टेक्स्ट (टर्मिनल-शैली के आउटपुट के लिए प्रति पंक्ति उत्सर्जित करें)।
यह UI तक कैसे पहुँचता है। फ्रेमवर्क हर chunk को एजेंट के EventStream पर एक आंशिक Event के रूप में आगे भेजता है। एक consumer इसे event.tool_progress_stream() के साथ पहचानता है और इसे live render करता है। कोई दूसरा channel नहीं है और न ही log scraping — progress, model text, और अंतिम tool result, सब एक ही ordered stream पर आते हैं।
Backward compatible. डिफ़ॉल्ट emit_progress एक no-op है, इसलिए existing tools और runners जो stream नहीं करते, वे प्रभावित नहीं होते। केवल opt in करने वाले tools progress emit करते हैं, और केवल वे consumers जो tool_progress_stream() check करते हैं, इसे observe करते हैं।
Progress bounded और lossy है। एक tool client के consume करने की गति से तेज़ output produce कर सकता है — एक compiler log, एक shell command, एक runaway loop — इसलिए framework बिना सीमा के बढ़ने देने के बजाय, वह जो hold और forward करेगा उसे cap करता है:
| सीमा | मान | इसे पार करने पर |
|---|---|---|
| प्रति टूल बैच कतार गहराई | 256 घटनाएँ | टूल स्थान के लिए 100 ms तक प्रतीक्षा करता है, फिर चंक को छोड़ दिया जाता है |
| प्रति चंक बाइट्स | 8 KiB | चंक को एक वर्ण सीमा पर काट दिया जाता है |
| प्रति टूल कॉल बाइट्स | 1 MiB | शेष प्रगति अग्रेषित नहीं की जाती |
जब आउटपुट इन कारणों में से किसी के लिए छोड़ दिया जाता है, तो उस कॉल के लिए ठीक एक प्रगति इवेंट उत्सर्जित किया जाता है जिसमें पाठ [adk: tool progress truncated] होता है, इसलिए एक अंतर हमेशा दिखाई देता है, न कि मौन रूप से। इसलिए एक धीमा consumer tool को थोड़ी देर के लिए धीमा कर देता है, लेकिन यह उसे अनिश्चितकाल तक रोक नहीं सकता या मेमोरी समाप्त नहीं कर सकता।
ये सीमाएँ केवल progress पर लागू होती हैं। tool के अंतिम परिणाम पर कोई प्रभाव नहीं पड़ता, इसलिए यदि वह आपके लिए महत्वपूर्ण है, तो बड़े परिणाम tool के अंदर ही truncate करें।
पूर्ण web UI के लिए
streaming_bashउदाहरण देखें जो livebashoutput और one-shot tool results (read_file,grep,glob) को एक ही event feed से render करता है। streamingbashtool स्वयंadk-devtoolsमें स्थित है।
उदाहरण चलाना
cargo adk new tool_agent --template tools
cd tool_agent
cargo run
सर्वोत्तम प्रथाएँ
- स्पष्ट विवरण - LLM को यह समझने में मदद करें कि टूल का उपयोग कब करना है
- इनपुट मान्य करें - गायब पैरामीटरों के लिए सहायक त्रुटि संदेश लौटाएँ
- संरचित JSON लौटाएँ - स्पष्ट फ़ील्ड नामों का उपयोग करें
- टूल्स को केंद्रित रखें - प्रत्येक टूल को एक काम अच्छी तरह करना चाहिए
- स्कीमाओं का उपयोग करें - जटिल टूल्स के लिए, पैरामीटर स्कीमाएँ परिभाषित करें
- सुरक्षित केवल-पठन टूल्स को चिह्नित करें -
.with_read_only(true)और.with_concurrency_safe(true)दोनों सेट करें ताकिAutodispatch उन्हें अपने समवर्ती उपसमूह में शामिल कर सके
Tool Metadata: केवल-पठन और समवर्तिता
स्मार्ट dispatch सक्षम करने के लिए टूल्स को केवल-पठन या समवर्ती-सुरक्षित के रूप में चिह्नित करें:
// A lookup tool that performs no side effects
let lookup = FunctionTool::new("lookup", "Look up data", |_ctx, args| async move {
Ok(json!({"result": "cached data"}))
})
.with_read_only(true)
.with_concurrency_safe(true); // Auto mode requires both signals
// A mutation tool (defaults: read_only=false, concurrency_safe=false)
let update = FunctionTool::new("update", "Update record", |_ctx, args| async move {
Ok(json!({"updated": true}))
});
जब ToolExecutionStrategy::Auto सक्रिय होता है, तो dispatch loop पहले calls को समवर्ती रूप से चलाता है जब उनके चयनित tools true को is_read_only() और is_concurrency_safe() दोनों से लौटाते हैं। फिर यह सभी शेष calls को क्रमिक रूप से निष्पादित करता है। ToolExecutionStrategy::Parallel एक स्पष्ट override है जो इन संकेतों को बायपास करता है, इसलिए उसका caller concurrency safety का स्वामी होता है।
SimpleToolContext: Agent Loop के बाहर Tools का उपयोग
जब आपको एजेंट लूप के बाहर किसी टूल को कॉल करने की आवश्यकता हो (testing, MCP server mode, sub-agent delegation), तो पूर्ण ToolContext trait hierarchy को लागू करने के बजाय SimpleToolContext का उपयोग करें:
use adk_tool::SimpleToolContext;
use adk_core::ToolContext;
use std::sync::Arc;
// Construct with just a caller name — all other fields get sensible defaults
let ctx = SimpleToolContext::new("my-test-harness");
// Optionally override the function call ID
let ctx = SimpleToolContext::new("my-mcp-server")
.with_function_call_id("custom-call-id");
// Bind a session ID so session-aware tools (and MCP servers that key state by
// session) see a stable identifier instead of the empty default.
let ctx = SimpleToolContext::new("my-mcp-server")
.with_session_id("session-42");
// Use it to execute any tool
let tool_ctx: Arc<dyn ToolContext> = Arc::new(ctx);
let result = my_tool.execute(tool_ctx, json!({"key": "value"})).await?;
डिफ़ॉल्ट: user_id() → "anonymous", session_id() / branch() → "", artifacts() → None, search_memory() → खाली vec. दोनों invocation_id और function_call_id स्वतः-जनित UUIDs हैं। जब कोई टूल प्रति session रूट करता है या state को बनाए रखता है, तो with_session_id(...) के साथ एक वास्तविक session सेट करें।
StatefulTool: Invocations के बीच साझा state
उन टूल्स के लिए जिन्हें calls के बीच state बनाए रखने की आवश्यकता होती है (counters, caches, connection pools), StatefulTool<S> का उपयोग करें:
use adk_tool::StatefulTool;
use adk_core::ToolContext;
use std::sync::Arc;
use tokio::sync::RwLock;
struct AppCache {
entries: RwLock<HashMap<String, String>>,
}
let cache = Arc::new(AppCache {
entries: RwLock::new(HashMap::new()),
});
let cache_tool = StatefulTool::new(
"cache_lookup",
"Look up a value in the application cache",
cache.clone(),
|state, _ctx, args| async move {
let key = args["key"].as_str().unwrap_or("");
let entries = state.entries.read().await;
let value = entries.get(key).cloned().unwrap_or_default();
Ok(json!({"key": key, "value": value}))
},
)
.with_read_only(true)
.with_concurrency_safe(true);
StatefulTool प्रत्येक invocation पर Arc<S> को clone करता है (reference count में एक सस्ता bump), इसलिए सभी executions एक ही underlying state साझा करते हैं। यह FunctionTool के समान builder methods का समर्थन करता है: with_long_running, with_parameters_schema, with_response_schema, with_scopes, with_read_only, और with_concurrency_safe।
संबंधित
- अंतर्निर्मित टूल्स - पूर्व-निर्मित टूल्स (GoogleSearch, ExitLoop)
- MCP टूल्स - मॉडल कॉन्टेक्स्ट प्रोटोकॉल एकीकरण
- LlmAgent - एजेंट्स में टूल्स जोड़ना
बहु-मोडल फ़ंक्शन प्रतिक्रियाएँ
Gemini 3 मॉडल फ़ंक्शन प्रतिक्रियाओं में छवियाँ, ऑडियो, PDFs, और फ़ाइल संदर्भ प्राप्त करने का समर्थन करते हैं — केवल JSON नहीं। टूल्स अपनी JSON रिटर्न वैल्यू में inline_data और/या file_data ऐरे शामिल करके बहु-मोडल डेटा लौटा सकते हैं:
/// Tool that returns a chart image alongside JSON metadata.
async fn generate_chart(
_ctx: Arc<dyn ToolContext>,
args: serde_json::Value,
) -> Result<serde_json::Value> {
let png_bytes: Vec<u8> = render_chart(&args);
// Include inline_data in the return value — the framework extracts it automatically
Ok(json!({
"response": {
"title": "Q4 Sales",
"chart_type": "bar"
},
"inline_data": [{
"mime_type": "image/png",
"data": png_bytes
}]
}))
}
फ़्रेमवर्क स्वचालित रूप से:
inline_data/file_dataकोFunctionResponseData::from_tool_result()के माध्यम से पहचानता है- इनलाइन बाइनरी डेटा को Base64 में एन्कोड करता है
- भागों को
functionResponseवायर ऑब्जेक्ट के अंदर नेस्ट करता है (Gemini 3 API प्रारूप से मेल खाता हुआ)
फ़ाइल संदर्भ
बाहरी रूप से संग्रहीत बड़ी फ़ाइलों के लिए, बाइट्स एम्बेड करने के बजाय URI के साथ file_data का उपयोग करें:
Ok(json!({
"response": { "document_id": "report-2024", "pages": 12 },
"file_data": [{
"mime_type": "application/pdf",
"file_uri": "gs://my-bucket/reports/report-2024.pdf"
}]
}))
प्रत्यक्ष निर्माण
फ़्रेमवर्क-स्तरीय कोड (कस्टम एजेंट्स, रूपांतरण परतों) के लिए, FunctionResponseData को सीधे निर्मित करें:
use adk_core::{FunctionResponseData, InlineDataPart, FileDataPart};
// JSON + inline image
let frd = FunctionResponseData::with_inline_data(
"chart_tool",
json!({"title": "Q4 Chart"}),
vec![InlineDataPart { mime_type: "image/png".into(), data: png_bytes }],
);
// JSON + file reference
let frd = FunctionResponseData::with_file_data(
"doc_tool",
json!({"status": "ok"}),
vec![FileDataPart { mime_type: "application/pdf".into(), file_uri: "gs://bucket/file.pdf".into() }],
);
// JSON + both
let frd = FunctionResponseData::with_multimodal("tool", json, inline_parts, file_parts);
नोट: मल्टीमोडल फ़ंक्शन प्रतिक्रियाओं के लिए Gemini 3 श्रृंखला मॉडल (
gemini-3-flash-preview,gemini-3-pro-preview) आवश्यक हैं। पहले के मॉडल 400 त्रुटि लौटाते हैं।
एक पूर्ण कार्यशील उदाहरण के लिए examples/multimodal_function_response/ देखें।
पिछला: ← mistral.rs | अगला: अंतर्निर्मित टूल्स →