Create a custom tool with the `function` macro
masterYou can define custom tools using the #[ollama_rs::function] macro. The function must return a Result<String, Box<dyn std::error::Error + Sync + Send>>. The doc comments above the function are used to describe the tool to the LLM.
/// Retrieve the weather for a specified city.
///
/// * city - The city for which to get the weather.
#[ollama_rs::function]
async fn get_weather(city: String) -> Result<String, Box<dyn std::error::Error + Sync + Send>> {
let url = format!("https://wttr.in/{city}?format=%C+%t");
let response = reqwest::get(&url).await?.text().await?;
Ok(response)
}To use this tool in a streaming chat request, attach it to the ChatMessageRequest:
use ollama_rs::generation::chat::request::ChatMessageRequest;
let request = ChatMessageRequest::new("lfm2.5:8b".to_owned(), Vec::new()).add_tool(get_weather);
let mut stream = ollama.send_chat_messages_stream(request).await.unwrap();When using send_chat_messages_stream, if a chunk contains message.tool_calls, you must run the requested tools and include their results in a follow-up request.