tool_calling_simple/
tool_calling_simple.rs1#![allow(clippy::uninlined_format_args)]
2use openai_ergonomic::{
7 builders::chat::tool_function,
8 responses::{chat::ToolCallExt, ToolChoiceHelper},
9 Client, Result,
10};
11use serde::{Deserialize, Serialize};
12use serde_json::json;
13
14#[derive(Debug, Serialize, Deserialize)]
15struct WeatherParams {
16 location: String,
17}
18
19fn get_weather_tool() -> openai_ergonomic::responses::Tool {
20 tool_function(
21 "get_weather",
22 "Get the current weather for a location",
23 json!({
24 "type": "object",
25 "properties": {
26 "location": {
27 "type": "string",
28 "description": "The city name"
29 }
30 },
31 "required": ["location"]
32 }),
33 )
34}
35
36fn execute_weather_function(params: &WeatherParams) -> String {
37 format!("The weather in {} is sunny, 24°C", params.location)
39}
40
41#[tokio::main]
42async fn main() -> Result<()> {
43 println!("=== Tool Calling Example ===");
44
45 let client = Client::from_env()?.build();
46
47 let builder = client
49 .chat()
50 .user("What's the weather like in San Francisco?")
51 .tools(vec![get_weather_tool()]);
52 let response = client.send_chat(builder).await?;
53
54 let tool_calls = response.tool_calls();
56 if !tool_calls.is_empty() {
57 for tool_call in tool_calls {
58 println!("Tool called: {}", tool_call.function_name());
59 println!("Arguments: {}", tool_call.function_arguments());
60
61 let params: WeatherParams = serde_json::from_str(tool_call.function_arguments())?;
63 let result = execute_weather_function(¶ms);
64 println!("Function result: {}", result);
65 }
66 } else if let Some(content) = response.content() {
67 println!("Response: {}", content);
68 }
69
70 println!("\n=== Forced Tool Choice ===");
72 let builder = client
73 .chat()
74 .user("Tell me about Paris")
75 .tools(vec![get_weather_tool()])
76 .tool_choice(ToolChoiceHelper::specific("get_weather"));
77 let response = client.send_chat(builder).await?;
78
79 for tool_call in response.tool_calls() {
80 println!("Forced tool: {}", tool_call.function_name());
81 }
82
83 println!("\n=== No Tools Mode ===");
85 let builder = client
86 .chat()
87 .user("What's the weather?")
88 .tools(vec![get_weather_tool()])
89 .tool_choice(ToolChoiceHelper::none());
90 let response = client.send_chat(builder).await?;
91
92 if let Some(content) = response.content() {
93 println!("Response without tools: {}", content);
94 }
95
96 Ok(())
97}