LlmAgent
LlmAgent ADK-Rust में मुख्य Agent प्रकार है जो तर्क और निर्णय लेने के लिए एक Large Language Model का उपयोग करता है।
त्वरित शुरुआत
एक नया प्रोजेक्ट बनाएँ:
cargo new llm_agent
cd llm_agent
Cargo.toml में डिपेंडेंसीज़ जोड़ें:
[dependencies]
adk-rust = "0.2.0"
tokio = { version = "1.40", features = ["full"] }
dotenvy = "0.15"
serde_json = "1.0"
अपनी API key के साथ .env बनाएँ:
echo 'GOOGLE_API_KEY=your-api-key' > .env
src/main.rs को बदलें:
use adk_rust::prelude::*;
use adk_rust::Launcher;
use std::sync::Arc;
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
dotenvy::dotenv().ok();
let api_key = std::env::var("GOOGLE_API_KEY")?;
let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;
let agent = LlmAgentBuilder::new("my_agent")
.instruction("You are a helpful assistant.")
.model(Arc::new(model))
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
इसे चलाएँ:
cargo run
अपने Agent के साथ इंटरैक्ट करना
आपको एक इंटरैक्टिव प्रॉम्प्ट दिखाई देगा:
🤖 Agent ready! Type your questions (or 'exit' to quit).
You: Hello! What can you help me with?
Assistant: Hello! I'm a helpful assistant. I can help you with:
- Answering questions on various topics
- Explaining concepts clearly
- Having a conversation
What would you like to know?
You: exit
👋 Goodbye!
निर्देशों के साथ एजेंट के व्यवहार को आकार देना
instruction() मेथड आपके एजेंट के व्यक्तित्व और व्यवहार को परिभाषित करता है। यह वह सिस्टम प्रॉम्प्ट है जो हर प्रतिक्रिया का मार्गदर्शन करता है:
// A formal business assistant
let formal_agent = LlmAgentBuilder::new("formal_assistant")
.instruction("You are a professional business consultant. \
Use formal language. Be concise and data-driven.")
.model(Arc::new(model))
.build()?;
// A friendly coding tutor
let tutor_agent = LlmAgentBuilder::new("code_tutor")
.instruction("You are a friendly coding tutor for beginners. \
Explain concepts simply. Use examples. \
Encourage questions. Never make the user feel bad for not knowing.")
.model(Arc::new(model))
.build()?;
// A creative storyteller
let story_agent = LlmAgentBuilder::new("storyteller")
.instruction("You are a creative storyteller. \
Craft engaging narratives with vivid descriptions. \
Use plot twists and memorable characters.")
.model(Arc::new(model))
.build()?;
उदाहरण आउटपुट
User prompt: "Rust क्या है?"
औपचारिक व्यावसायिक सहायक:
Rust is a systems programming language focused on performance, memory safety,
and concurrency. Key metrics: 0 runtime overhead, 0 garbage collection.
Adoption growing 30% YoY in enterprise. Recommended for performance-critical
applications where reliability is paramount.
मैत्रीपूर्ण कोडिंग ट्यूटर:
Great question! 🎉 Rust is a programming language that helps you write fast
and safe code. Think of it like a helpful friend who stops you from making
mistakes before they happen!
Here's a simple example:
let name = "Alice"; // This creates a variable
What makes Rust special is that it catches bugs at compile time, not when
your program is running. Pretty cool, right? Want me to explain more?
रचनात्मक कहानीकार:
In the twilight of 2010, in a secret Mozilla laboratory, a lone developer
named Graydon Hoare breathed life into something extraordinary—a language
that would challenge the old gods of C and C++.
They called it Rust, named for a fungus that survives against all odds.
Like a phoenix rising from the ashes of segmentation faults and memory
leaks, Rust promised a new era: speed without sacrifice, power without peril.
And so, the revolution began...
इंस्ट्रक्शन टेम्पलेटिंग
निर्देश {var} सिंटैक्स का उपयोग करके वेरिएबल इंजेक्शन का समर्थन करते हैं। रनटाइम पर सेशन की स्थिति से वेरिएबल हल किए जाते हैं:
let agent = LlmAgentBuilder::new("personalized")
.instruction("You are helping {user_name}. Their role is {user_role}. \
Tailor your responses to their expertise level.")
.model(Arc::new(model))
.build()?;
टेम्पलेटिंग का उपयोग करने के लिए चरण-दर-चरण मार्गदर्शिका:
- एजेंट बनाएं जिसमें निर्देश में टेम्पलेट वेरिएबल हों
- स्थिति प्रबंधित करने के लिए Runner और SessionService सेट करें
- सेशन बनाएं जिसमें आपके टेम्पलेट से मेल खाने वाले स्थिति वेरिएबल हों
- एजेंट चलाएं - टेम्पलेट स्वचालित रूप से प्रतिस्थापित हो जाते हैं
यहाँ एक पूरा कार्यशील उदाहरण दिया गया है:
use adk_rust::prelude::*;
use adk_rust::runner::{Runner, RunnerConfig};
use adk_rust::session::{CreateRequest, InMemorySessionService, SessionService};
use adk_rust::futures::StreamExt;
use serde_json::json;
use std::collections::HashMap;
use std::sync::Arc;
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
dotenvy::dotenv().ok();
let api_key = std::env::var("GOOGLE_API_KEY")?;
let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;
// 1. Agent with templated instruction
let agent = LlmAgentBuilder::new("personalized")
.instruction("You are helping {user_name}. Their role is {user_role}. \
Tailor your responses to their expertise level.")
.model(Arc::new(model))
.build()?;
// 2. Create session service and runner
let session_service = Arc::new(InMemorySessionService::new());
let runner = Runner::new(RunnerConfig {
app_name: "templating_demo".to_string(),
agent: Arc::new(agent),
session_service: session_service.clone(),
artifact_service: None,
memory_service: None,
run_config: None,
})?;
// 3. Create session with state variables
let mut state = HashMap::new();
state.insert("user_name".to_string(), json!("Alice"));
state.insert("user_role".to_string(), json!("Senior Developer"));
let session = session_service.create(CreateRequest {
app_name: "templating_demo".to_string(),
user_id: "user123".to_string(),
session_id: None,
state,
}).await?;
// 4. Run the agent - instruction becomes:
// "You are helping Alice. Their role is Senior Developer..."
let mut response_stream = runner.run(
"user123".to_string(),
session.id().to_string(),
Content::new("user").with_text("Explain async/await in Rust"),
).await?;
// Print the response
while let Some(event) = response_stream.next().await {
let event = event?;
if let Some(content) = event.content() {
for part in &content.parts {
if let Part::Text { text } = part {
print!("{}", text);
}
}
}
}
Ok(())
}
टेम्पलेट वेरिएबल प्रकार:
| Pattern | Example | Source |
|---|---|---|
{var} | {user_name} | सेशन स्थिति |
{prefix:var} | {user:name}, {app:config} | प्रीफ़िक्स्ड स्थिति |
{var?} | {user_name?} | वैकल्पिक (यदि अनुपस्थित हो तो खाली) |
{artifact.file} | {artifact.resume.pdf} | आर्टिफैक्ट सामग्री |
आउटपुट उदाहरण:
टेम्पलेट: "आप {user_name} की मदद कर रहे हैं। उनकी भूमिका {user_role} है।"
बन जाता है: "आप एलिस की मदद कर रहे हैं। उनकी भूमिका सीनियर डेवलपर है।"
एजेंट तब उपयोगकर्ता के नाम और विशेषज्ञता के स्तर के आधार पर व्यक्तिगत सामग्री के साथ प्रतिक्रिया देगा!
टूल जोड़ना
टूल आपके Agent को बातचीत से परे क्षमताएँ प्रदान करते हैं—वे डेटा ला सकते हैं, गणना कर सकते हैं, वेब खोज सकते हैं, या बाहरी APIs को कॉल कर सकते हैं। LLM उपयोगकर्ता के अनुरोध के आधार पर यह तय करता है कि टूल का उपयोग कब करना है।
टूल कैसे काम करते हैं
- Agent उपयोगकर्ता संदेश प्राप्त करता है → "टोक्यो में मौसम कैसा है?"
- LLM टूल को कॉल करने का निर्णय लेता है →
{"city": "Tokyo"}के साथget_weatherका चयन करता है - टूल निष्पादित होता है →
{"temperature": "22°C", "condition": "sunny"}लौटाता है - LLM प्रतिक्रिया प्रारूपित करता है → "टोक्यो में मौसम 22°C पर धूप वाला है।"
FunctionTool के साथ एक टूल बनाना
FunctionTool एक टूल बनाने का सबसे सरल तरीका है—किसी भी async Rust फ़ंक्शन को रैप करें और LLM उसे कॉल कर सकता है। आप एक नाम, विवरण और हैंडलर फ़ंक्शन प्रदान करते हैं जो JSON तर्क प्राप्त करता है और एक JSON परिणाम लौटाता है।
let weather_tool = FunctionTool::new(
"get_weather", // टूल का नाम (LLM द्वारा उपयोग किया जाता है)
"Get the current weather for a city", // विवरण (LLM को यह तय करने में मदद करता है कि इसका उपयोग कब करना है)
|_ctx, args| async move { // हैंडलर फ़ंक्शन
let city = args.get("city") // JSON से तर्क निकालें
.and_then(|v| v.as_str())
.unwrap_or("unknown");
Ok(json!({ "city": city, "temperature": "22°C" })) // JSON परिणाम लौटाएँ
},
);
⚠️ ध्यान दें: वर्तमान सीमा:
GoogleSearchToolजैसे बिल्ट-इन टूल वर्तमान में एक ही Agent मेंFunctionToolके साथ असंगत हैं। या तो बिल्ट-इन टूल या कस्टमFunctionToolका उपयोग करें, लेकिन दोनों एक साथ नहीं। 💡 समाधान: अलग-अलग सबएजेंट बनाएँ, प्रत्येक अपने स्वयं के टूल प्रकार के साथ, और उन्हें एक मास्टर LLMAgent, वर्कफ़्लो एजेंटों या मल्टी-एजेंट पैटर्न का उपयोग करके समन्वित करें।
एक मल्टी-टूल एजेंट बनाएँ
एक नया प्रोजेक्ट बनाएँ:
cargo new tool_agent
cd tool_agent
Cargo.toml में डिपेंडेंसी जोड़ें:
[dependencies]
adk-rust = { version = "0.2.0", features = ["tools"] }
tokio = { version = "1.40", features = ["full"] }
dotenvy = "0.15"
serde_json = "1.0"
.env बनाएँ:
echo 'GOOGLE_API_KEY=your-api-key' > .env
src/main.rs को तीन टूल वाले एक एजेंट से बदलें:
use adk_rust::prelude::*;
use adk_rust::Launcher;
use serde_json::json;
use std::sync::Arc;
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
dotenvy::dotenv().ok();
let api_key = std::env::var("GOOGLE_API_KEY")?;
let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;
// टूल 1: मौसम की जानकारी
let weather_tool = FunctionTool::new(
"get_weather",
"किसी शहर के लिए वर्तमान मौसम प्राप्त करें। पैरामीटर: city (string)",
|_ctx, args| async move {
let city = args.get("city").and_then(|v| v.as_str()).unwrap_or("unknown");
Ok(json!({ "city": city, "temperature": "22°C", "condition": "sunny" }))
},
);
// टूल 2: कैलकुलेटर
let calculator = FunctionTool::new(
"calculate",
"अंकगणित करें। पैरामीटर: a (number), b (number), operation (add/subtract/multiply/divide)",
|_ctx, args| async move {
let a = args.get("a").and_then(|v| v.as_f64()).unwrap_or(0.0);
let b = args.get("b").and_then(|v| v.as_f64()).unwrap_or(0.0);
let op = args.get("operation").and_then(|v| v.as_str()).unwrap_or("add");
let result = match op {
"add" => a + b,
"subtract" => a - b,
"multiply" => a * b,
"divide" => if b != 0.0 { a / b } else { 0.0 },
_ => 0.0,
};
Ok(json!({ "result": result }))
},
);
// टूल 3: बिल्ट-इन Google खोज (ध्यान दें: ADK-Rust में वर्तमान में असमर्थित)
// let search_tool = GoogleSearchTool::new();
// मौसम और कैलकुलेटर टूल के साथ एजेंट बनाएँ
let agent = LlmAgentBuilder::new("multi_tool_agent")
.instruction("आप एक सहायक सहायक हैं। आवश्यकता पड़ने पर टूल का उपयोग करें: \
- मौसम के प्रश्नों के लिए get_weather \
- गणित के लिए calculate")
.model(Arc::new(model))
.tool(Arc::new(weather_tool))
.tool(Arc::new(calculator))
// .tool(Arc::new(search_tool)) // वर्तमान में असमर्थित
.build()?;
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
अपना एजेंट चलाएँ:
cargo run
उदाहरण बातचीत
आप: 250 का 15% कितना है?
Assistant: [a=250, b=0.15, operation=multiply के साथ calculate टूल का उपयोग कर रहा है]
250 का 15% 37.5 है।
आप: टोक्यो में मौसम कैसा है?
Assistant: [city=Tokyo के साथ get_weather टूल का उपयोग कर रहा है]
टोक्यो में मौसम 22°C तापमान के साथ धूप वाला है।
आप: नवीनतम Rust सुविधाओं की खोज करें
Assistant: मेरे पास इस समय खोज कार्यक्षमता तक पहुँच नहीं है, लेकिन मैं Rust के बारे में अन्य प्रश्नों में मदद कर सकता हूँ या गणनाएँ कर सकता हूँ!
JSON Schema के साथ संरचित आउटपुट
उन एप्लिकेशनों के लिए जिन्हें संरचित डेटा की आवश्यकता होती है, output_schema() का उपयोग करें:
use adk_rust::prelude::*;
use serde_json::json;
use std::sync::Arc;
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
dotenvy::dotenv().ok();
let api_key = std::env::var("GOOGLE_API_KEY")?;
let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;
let extractor = LlmAgentBuilder::new("entity_extractor")
.instruction("Extract entities from the given text.")
.model(Arc::new(model))
.output_schema(json!({
"type": "object",
"properties": {
"people": {
"type": "array",
"items": { "type": "string" }
},
"locations": {
"type": "array",
"items": { "type": "string" }
},
"dates": {
"type": "array",
"items": { "type": "string" }
}
},
"required": ["people", "locations", "dates"]
}))
.build()?;
println!("Entity extractor ready!");
Ok(())
}
JSON आउटपुट उदाहरण
इनपुट: "जॉन पेरिस में सारा से 25 दिसंबर को मिला"
आउटपुट:
{
"people": ["John", "Sarah"],
"locations": ["Paris"],
"dates": ["December 25th"]
}
उन्नत सुविधाएँ
सामग्री शामिल करें
बातचीत के इतिहास की दृश्यता को नियंत्रित करें:
// पूरा इतिहास (डिफ़ॉल्ट)
.include_contents(IncludeContents::Default)
// स्टेटलेस - केवल वर्तमान इनपुट देखता है
.include_contents(IncludeContents::None)
आउटपुट कुंजी
एजेंट के प्रतिक्रियाओं को सेशन स्टेट में सहेजें:
.output_key("summary") // प्रतिक्रिया state["summary"] में सहेजी गई
गतिशील निर्देश
रनटाइम पर निर्देशों की गणना करें:
.instruction_provider(|ctx| {
Box::pin(async move {
let user_id = ctx.user_id();
Ok(format!("You are assisting user {}.", user_id))
})
})
कॉलबैक
एजेंट के व्यवहार को रोकें:
.before_model_callback(|ctx, request| {
Box::pin(async move {
println!("About to call LLM with {} messages", request.contents.len());
Ok(BeforeModelResult::Continue)
})
})
बिल्डर संदर्भ
| Method | Description |
|---|---|
new(name) | एजेंट नाम के साथ बिल्डर बनाता है |
model(Arc<dyn Llm>) | LLM सेट करता है (आवश्यक) |
description(text) | एजेंट का विवरण |
instruction(text) | सिस्टम प्रॉम्प्ट |
tool(Arc<dyn Tool>) | एक टूल जोड़ता है |
output_schema(json) | संरचित आउटपुट के लिए JSON स्कीमा |
output_key(key) | प्रतिक्रिया को स्टेट में सहेजता है |
include_contents(mode) | इतिहास की दृश्यता |
build() | एजेंट बनाता है |
पूर्ण उदाहरण
कई उपकरणों (मौसम, कैलकुलेटर, खोज) के साथ एक उत्पादन-तैयार एजेंट और आउटपुट को सेशन स्टेट में सहेजा गया है:
use adk_rust::prelude::*;
use adk_rust::Launcher;
use serde_json::json;
use std::sync::Arc;
#[tokio::main]
async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
dotenvy::dotenv().ok();
let api_key = std::env::var("GOOGLE_API_KEY")?;
let model = GeminiModel::new(&api_key, "gemini-2.5-flash")?;
// Weather tool
let weather = FunctionTool::new(
"get_weather",
"Get weather for a city. Parameters: city (string)",
|_ctx, args| async move {
let city = args.get("city").and_then(|v| v.as_str()).unwrap_or("unknown");
Ok(json!({
"city": city,
"temperature": "22°C",
"humidity": "65%",
"condition": "partly cloudy"
}))
},
);
// Calculator tool
let calc = FunctionTool::new(
"calculate",
"Math operations. Parameters: expression (string like '2 + 2')",
|_ctx, args| async move {
let expr = args.get("expression").and_then(|v| v.as_str()).unwrap_or("0");
Ok(json!({ "expression": expr, "result": "computed" }))
},
);
// Build the full agent
let agent = LlmAgentBuilder::new("assistant")
.description("A helpful assistant with weather and calculation abilities")
.instruction("You are a helpful assistant. \
Use the weather tool for weather questions. \
Use the calculator for math. \
Be concise and friendly.")
.model(Arc::new(model))
.tool(Arc::new(weather))
.tool(Arc::new(calc))
// .tool(Arc::new(GoogleSearchTool::new())) // Currently unsupported with FunctionTool
.output_key("last_response")
.build()?;
println!("✅ Agent '{}' ready!", agent.name());
Launcher::new(Arc::new(agent)).run().await?;
Ok(())
}
इन प्रॉम्प्ट्स को आज़माएँ:
You: What's 25 times 4?
Assistant: It's 100.
You: How's the weather in New York?
Assistant: The weather in New York is partly cloudy with a temperature of 22°C and 65% humidity.
You: Calculate 15% tip on $85
Assistant: A 15% tip on $85 is $12.75, making the total $97.75.
संबंधित
- Workflow Agents - Sequential, Parallel, और Loop agents
- Multi-Agent Systems - Agent पदानुक्रम का निर्माण
- Function Tools - कस्टम tools बनाना
- Callbacks - Agent के व्यवहार को रोकना
पिछला: त्वरित शुरुआत | अगला: Workflow Agents →