use oai_sdk::{ChatRequest, Message, ModelClient, Tool, ToolFunction};
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let client = ModelClient::builder()
.base_url("http://localhost:11434")
.build()?;
println!("Ollama Client Tool Calling Example");
println!("This example shows how to use tool calling with the Ollama API.\n");
let tools = vec![Tool {
tool_type: "function".to_string(),
function: ToolFunction {
name: "get_current_weather".to_string(),
description: "Get the current weather for a location".to_string(),
parameters: json!({
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The location to get the weather for, e.g. San Francisco, CA"
},
"format": {
"type": "string",
"description": "The format to return the weather in, e.g. 'celsius' or 'fahrenheit'",
"enum": ["celsius", "fahrenheit"]
}
},
"required": ["location", "format"]
}),
},
}];
let messages = vec![Message::user("What is the weather like in Tokyo?")];
let request = ChatRequest {
model: "llama3.1:8b".to_string(), messages,
stream: false,
format: None,
options: None,
keep_alive: None,
tools: Some(tools),
think: None,
};
println!("User: What is the weather like in Tokyo?");
match client.chat(request).await {
Ok(response) => {
if let Some(tool_calls) = response.message.tool_calls {
println!("Model wants to call tools:");
for tool_call in tool_calls {
println!(" - Function: {}", tool_call.function.name);
println!(
" Arguments: {}",
serde_json::to_string_pretty(&tool_call.function.arguments)?
);
}
println!("\nIn a real application, you would execute these tool calls");
println!("and send the results back to the model for a final response.");
} else {
println!("Assistant: {}", response.message.content);
}
}
Err(e) => {
println!("Error: {}", e);
}
}
Ok(())
}