use modelbridge::{Client, Message, Request, ToolCall, ToolResult, ToolSchema};
use serde_json::json;
fn schemas() -> Vec<ToolSchema> {
vec![ToolSchema::new(
"distance_km",
"Straight-line distance between two cities, in kilometres.",
json!({
"type": "object",
"properties": {
"from": { "type": "string" },
"to": { "type": "string" },
},
"required": ["from", "to"],
}),
)]
}
fn run(call: &ToolCall) -> Result<String, String> {
match call.name.as_str() {
"distance_km" => {
let from = call.arg("from").ok_or("`from` is required")?;
let to = call.arg("to").ok_or("`to` is required")?;
Ok(format!("{from} to {to}: 1,213 km"))
}
other => Err(format!("no tool named `{other}`")),
}
}
fn main() -> Result<(), String> {
let provider = std::env::args().nth(1).unwrap_or_else(|| "openai".into());
let client = Client::default_for(&provider)?;
let question = "How far is Lisbon from Paris, and how long would that take at 90 km/h?";
let mut conversation = vec![Message::user(question)];
let first = client.complete(
&Request::new("Use the tools for anything factual. Answer in one sentence.")
.messages(conversation.clone())
.tools(schemas())
.max_output_tokens(400),
)?;
if first.tool_calls.is_empty() {
println!("{}", first.text);
return Ok(());
}
conversation.push(first.as_message());
let mut results = Vec::new();
for (index, call) in first.tool_calls.iter().enumerate() {
eprintln!("[calling {}({})]", call.name, call.args);
results.push(match run(call) {
Ok(output) => ToolResult::new(call, index, output),
Err(message) => ToolResult::failure(call, index, message),
});
}
conversation.push(Message::tool_results(results));
let second = client.complete(
&Request::new("Use the tools for anything factual. Answer in one sentence.")
.messages(conversation)
.max_output_tokens(400),
)?;
println!("{}", second.text);
let usage = first.usage + second.usage;
eprintln!(
"2 turns, {} tokens, about ${:.4}",
usage.total(),
usage.dollars()
);
Ok(())
}