4 releases
new 0.1.3 | Feb 11, 2025 |
---|---|
0.1.2 | Jan 19, 2025 |
0.1.1 | Dec 29, 2024 |
0.1.0 | Dec 16, 2024 |
#1204 in Parser implementations
197 downloads per month
37KB
834 lines
OpenAI Tools
API Wrapper for OpenAI API.

Installation
To start using the openai-tools
, add it to your projects's dependencies in the `Cargo.toml' file:
cargo add openai-tools
API key is necessary to access OpenAI API.
Set it in the .env
file:
OPENAI_API_KEY = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
lib.rs
:
Usage
Chat Completion
Simple Chat
let mut openai = OpenAI::new();
let messages = vec![
Message::new(String::from("user"), String::from("Hi there!"))
];
openai
.model_id(String::from("gpt-4o-mini"))
.messages(messages)
.temperature(1.0);
let response: Response = openai.chat().unwrap();
println!("{}", &response.choices[0].message.content);
// Hello! How can I assist you today?
Chat with Json Schema
#[derive(Debug, Serialize, Deserialize)]
struct Weather {
location: String,
date: String,
weather: String,
error: String,
}
let mut openai = OpenAI::new();
let messages = vec![Message::new(
String::from("user"),
String::from("Hi there! How's the weather tomorrow in Tokyo? If you can't answer, report error."),
)];
// build json schema
let mut json_schema = JsonSchema::new("weather".to_string());
json_schema.add_property(
String::from("location"),
String::from("string"),
Option::from(String::from("The location to check the weather for.")),
);
json_schema.add_property(
String::from("date"),
String::from("string"),
Option::from(String::from("The date to check the weather for.")),
);
json_schema.add_property(
String::from("weather"),
String::from("string"),
Option::from(String::from("The weather for the location and date.")),
);
json_schema.add_property(
String::from("error"),
String::from("string"),
Option::from(String::from("Error message. If there is no error, leave this field empty.")),
);
// configure chat completion model
openai
.model_id(String::from("gpt-4o-mini"))
.messages(messages)
.temperature(1.0)
.response_format(ResponseFormat::new(String::from("json_schema"), json_schema));
// execute chat
let response = openai.chat().unwrap();
let answer: Weather = serde_json::from_str::<Weather>(&response.choices[0].message.content).unwrap();
println!("{:?}", answer)
// Weather {
// location: "Tokyo",
// date: "2023-10-01",
// weather: "Temperatures around 25°C with partly cloudy skies and a slight chance of rain.",
// error: "",
// }
Dependencies
~1–1.9MB
~39K SLoC