openai_dive/lib.rs
1//! # OpenAI Dive
2//!
3//! OpenAI Dive is an unofficial async Rust library that allows you to interact with the OpenAI API.
4//!
5//! ```ini
6//! [dependencies]
7//! openai_dive = "1.3"
8//! ```
9//!
10//! ## Get started
11//!
12//! ```rust
13//! use openai_dive::v1::api::Client;
14//!
15//! let api_key = std::env::var("OPENAI_API_KEY").expect("$OPENAI_API_KEY is not set");
16//!
17//! let client = Client::new_from_env(); // or Client::new(api_key);
18//!
19//! let result = client
20//! .models()
21//! .list()
22//! .await?;
23//! ```
24//!
25//! - [Set API key](#set-api-key)
26//! - [Using OpenAI-compatible APIs](#using-openai-compatible-apis)
27//! - [Set organization/project id](#set-organizationproject-id)
28//! - [Add proxy](#add-proxy)
29//! - [Available models](#available-models)
30//!
31//! ## Endpoints
32//!
33//! - [Chat](#chat)
34//! - [Completion](#completion)
35//! - [Vision](#vision)
36//! - [Voice](#voice)
37//! - [Function calling](#function-calling)
38//! - [Structured outputs](#structured-outputs)
39//! - [Web search](#web-search)
40//! - [Responses](#responses)
41//! - [Images](#images)
42//! - [Audio](#audio)
43//! - [Videos](#videos)
44//! - [Models](#models)
45//! - [Files](#files)
46//! - [Embeddings](#embeddings)
47//! - [Moderation](#moderation)
48//! - [Uploads](#uploads)
49//! - [Fine-tuning](#fine-tuning)
50//! - [Batches](#batches)
51//! - [Administration](#administration)
52//! - [Usage](#usage)
53//! - [Realtime](#realtime)
54//!
55//! ## Completion
56//!
57//! Given a list of messages comprising a conversation, the model will return a response.
58//!
59//! ### Create chat completion
60//!
61//! Creates a model response for the given chat conversation.
62//!
63//! ```rust
64//! let parameters = ChatCompletionParametersBuilder::default()
65//! .model(Gpt4Model::Gpt4O.to_string())
66//! .messages(vec![
67//! ChatMessage::User {
68//! content: ChatMessageContent::Text("Hello!".to_string()),
69//! name: None,
70//! },
71//! ChatMessage::User {
72//! content: ChatMessageContent::Text("What is the capital of Vietnam?".to_string()),
73//! name: None,
74//! },
75//! ])
76//! .response_format(ChatCompletionResponseFormat::Text)
77//! .build()?;
78//!
79//! let result = client
80//! .chat()
81//! .create(parameters)
82//! .await?;
83//! ```
84//!
85//! More information: [Create chat completion](https://platform.openai.com/docs/api-reference/chat/create)
86//!
87//! ### Vision
88//!
89//! Learn how to use vision capabilities to understand images.
90//!
91//! ```rust
92//! let parameters = ChatCompletionParametersBuilder::default()
93//! .model(Gpt4Model::Gpt4O.to_string())
94//! .messages(vec![
95//! ChatMessage::User {
96//! content: ChatMessageContent::Text("What is in this image?".to_string()),
97//! name: None,
98//! },
99//! ChatMessage::User {
100//! content: ChatMessageContent::ContentPart(vec![ChatMessageContentPart::Image(
101//! ChatMessageImageContentPart {
102//! r#type: "image_url".to_string(),
103//! image_url: ImageUrlType {
104//! url:
105//! "https://images.unsplash.com/photo-1526682847805-721837c3f83b?w=640"
106//! .to_string(),
107//! detail: None,
108//! },
109//! },
110//! )]),
111//! name: None,
112//! },
113//! ])
114//! .build()?;
115//!
116//! let result = client
117//! .chat()
118//! .create(parameters)
119//! .await?;
120//! ```
121//!
122//! More information: [Vision](https://platform.openai.com/docs/guides/vision)
123//!
124//! ### Voice
125//!
126//! Learn how to use audio capabilities to understand audio files.
127//!
128//! ```rust
129//! let recording = std::fs::read("example-audio.txt").unwrap();
130//!
131//! let parameters = ChatCompletionParametersBuilder::default()
132//! .model(Gpt4Model::Gpt4OAudioPreview.to_string())
133//! .messages(vec![
134//! ChatMessage::User {
135//! content: ChatMessageContent::Text(
136//! "What do you hear in this recording?".to_string(),
137//! ),
138//! name: None,
139//! },
140//! ChatMessage::User {
141//! content: ChatMessageContent::AudioContentPart(vec![ChatMessageAudioContentPart {
142//! r#type: "input_audio".to_string(),
143//! input_audio: InputAudioData {
144//! data: String::from_utf8(recording).unwrap(),
145//! format: "mp3".to_string(),
146//! },
147//! }]),
148//! name: None,
149//! },
150//! ])
151//! .build()?;
152//!
153//! let result = client
154//! .chat()
155//! .create(parameters)
156//! .await?;
157//! ```
158//!
159//! More information: [Vision](https://platform.openai.com/docs/guides/audio)
160//!
161//! ### Function calling
162//!
163//! In an API call, you can describe functions and have the model intelligently choose to output a JSON object containing arguments to call one or many functions. The Chat Completions API does not call the function; instead, the model generates JSON that you can use to call the function in your code.
164//!
165//! ```rust
166//! let messages = vec![ChatMessage::User {
167//! content: ChatMessageContent::Text(
168//! "Give me a random number higher than 100 but less than 2*150?".to_string(),
169//! ),
170//! name: None,
171//! }];
172//!
173//! let parameters = ChatCompletionParametersBuilder::default()
174//! .model(Gpt4Model::Gpt4O.to_string())
175//! .messages(messages)
176//! .tools(vec![ChatCompletionTool {
177//! r#type: ChatCompletionToolType::Function,
178//! function: ChatCompletionFunction {
179//! name: "get_random_number".to_string(),
180//! description: Some("Get a random number between two values".to_string()),
181//! parameters: json!({
182//! "type": "object",
183//! "properties": {
184//! "min": {"type": "integer", "description": "Minimum value of the random number."},
185//! "max": {"type": "integer", "description": "Maximum value of the random number."},
186//! },
187//! "required": ["min", "max"],
188//! }),
189//! },
190//! }])
191//! .build()?;
192//!
193//! let result = client
194//! .chat()
195//! .create(parameters)
196//! .await?;
197//!
198//! let message = result.choices[0].message.clone();
199//!
200//! if let ChatMessage::Assistant {
201//! tool_calls: Some(tool_calls),
202//! ..
203//! } = message
204//! {
205//! for tool_call in tool_calls {
206//! let name = tool_call.function.name;
207//! let arguments = tool_call.function.arguments;
208//!
209//! if name == "get_random_number" {
210//! let random_numbers: RandomNumber = serde_json::from_str(&arguments).unwrap();
211//!
212//! println!("Min: {:?}", &random_numbers.min);
213//! println!("Max: {:?}", &random_numbers.max);
214//!
215//! let random_number_result = get_random_number(random_numbers);
216//!
217//! println!(
218//! "Random number between those numbers: {:?}",
219//! random_number_result.clone()
220//! );
221//! }
222//! }
223//! }
224//!
225//! #[derive(Serialize, Deserialize)]
226//! pub struct RandomNumber {
227//! min: u32,
228//! max: u32,
229//! }
230//!
231//! fn get_random_number(params: RandomNumber) -> Value {
232//! let random_number = rand::thread_rng().gen_range(params.min..params.max);
233//!
234//! random_number.into()
235//! }
236//! ```
237//!
238//! More information: [Function calling](https://platform.openai.com/docs/guides/function-calling)
239//!
240//! ### Structured outputs
241//!
242//! Structured Outputs is a feature that guarantees the model will always generate responses that adhere to your supplied JSON Schema, so you don't need to worry about the model omitting a required key, or hallucinating an invalid enum value.
243//!
244//! ```rust
245//! let parameters = ChatCompletionParametersBuilder::default()
246//! .model("gpt-4o-2024-08-06")
247//! .messages(vec![
248//! ChatMessage::System {
249//! content: ChatMessageContent::Text(
250//! "You are a helpful math tutor. Guide the user through the solution step by step."
251//! .to_string(),
252//! ),
253//! name: None,
254//! },
255//! ChatMessage::User {
256//! content: ChatMessageContent::Text(
257//! "How can I solve 8x + 7 = -23"
258//! .to_string(),
259//! ),
260//! name: None,
261//! },
262//! ])
263//! .response_format(ChatCompletionResponseFormat::JsonSchema {
264//! json_schema: JsonSchemaBuilder::default()
265//! .name("math_reasoning")
266//! .schema(serde_json::json!({
267//! "type": "object",
268//! "properties": {
269//! "steps": {
270//! "type": "array",
271//! "items": {
272//! "type": "object",
273//! "properties": {
274//! "explanation": { "type": "string" },
275//! "output": { "type": "string" }
276//! },
277//! "required": ["explanation", "output"],
278//! "additionalProperties": false
279//! }
280//! },
281//! "final_answer": { "type": "string" }
282//! },
283//! "required": ["steps", "final_answer"],
284//! "additionalProperties": false
285//! }))
286//! .strict(true)
287//! .build()?
288//! }
289//! )
290//! .build()?;
291//!
292//! let result = client.chat().create(parameters).await?;
293//! ```
294//!
295//! More information: [Structured outputs](https://platform.openai.com/docs/guides/structured-outputs)
296//!
297//! ### Web search
298//!
299//! Allow models to search the web for the latest information before generating a response.
300//!
301//! ```rust
302//! let parameters = ChatCompletionParametersBuilder::default()
303//! .model(ToolModel::Gpt4OMiniSearchPreview.to_string())
304//! .messages(vec![ChatMessage::User {
305//! content: ChatMessageContent::Text(
306//! "What was a positive news story from today?!".to_string(),
307//! ),
308//! name: None,
309//! }])
310//! .web_search_options(WebSearchOptions {
311//! search_context_size: Some(WebSearchContextSize::Low),
312//! user_location: Some(ApproximateUserLocation {
313//! r#type: UserLocationType::Approximate,
314//! approximate: WebSearchUserLocation {
315//! city: Some("Amsterdam".to_string()),
316//! country: Some("NL".to_string()),
317//! region: None,
318//! timezone: None,
319//! },
320//! }),
321//! })
322//! .response_format(ChatCompletionResponseFormat::Text)
323//! .build()?;
324//!
325//! let result = client.chat().create(parameters).await?;
326//! ```
327//!
328//! More information: [Web search](https://platform.openai.com/docs/guides/web-search)
329//!
330//! ## Responses
331//!
332//! OpenAI's most advanced interface for generating model responses. Supports text and image inputs, and text outputs. Create stateful interactions with the model, using the output of previous responses as input. Extend the model's capabilities with built-in tools for file search, web search, computer use, and more. Allow the model access to external systems and data using function calling.
333//!
334//! For more information see the examples in the [examples/responses](https://github.com/tjardoo/openai-client/tree/master/examples/responses) directory.
335//!
336//! - Text & image inputs
337//! - Text outputs
338//! - Stateful interactions
339//! - File search
340//! - Web search
341//! - Computer use
342//! - Function calling
343//!
344//! ## Images
345//!
346//! Given a prompt and/or an input image, the model will generate a new image.
347//!
348//! - Create image
349//! - Create image edit
350//! - Create image variation
351//!
352//! For more information see the examples in the [examples/images](https://github.com/tjardoo/openai-client/tree/master/examples/images) directory.
353//!
354//! More information [Images](https://platform.openai.com/docs/api-reference/images)
355//!
356//! ## Audio
357//!
358//! Learn how to turn audio into text or text into audio.
359//!
360//! - Create speech
361//! - Create transcription
362//! - Create translation
363//!
364//! For more information see the examples in the [examples/audio](https://github.com/tjardoo/openai-client/tree/master/examples/audio) directory.
365//!
366//! More information [Audio](https://platform.openai.com/docs/api-reference/audio)
367//!
368//! ## Videos
369//!
370//! Create and remix videos.
371//!
372//! - Create video
373//! - Create remix
374//! - List videos
375//! - Retrieve video
376//! - Delete video
377//! - Retrieve video content
378//!
379//! For more information see the examples in the [examples/video](https://github.com/tjardoo/openai-client/tree/master/examples/video) directory.
380//!
381//! More information [Video](https://platform.openai.com/docs/api-reference/videos)
382//!
383//! ## Models
384//!
385//! List and describe the various models available in the API.
386//!
387//! For more information see the examples in the [examples/models](https://github.com/tjardoo/openai-client/tree/master/examples/models) directory.
388//!
389//! - List models
390//! - Retrieve model
391//! - Delete fine-tune model
392//!
393//! More information [Models](https://platform.openai.com/docs/api-reference/models)
394//!
395//! ## Files
396//!
397//! Files are used to upload documents that can be used with features like Assistants, Fine-tuning, and Batch API.
398//!
399//! For more information see the examples in the [examples/files](https://github.com/tjardoo/openai-client/tree/master/examples/files) directory.
400//!
401//! - List files
402//! - Upload file
403//! - Delete file
404//! - Retrieve file
405//! - Retrieve file content
406//!
407//! More information [Files](https://platform.openai.com/docs/api-reference/files)
408//!
409//! ## Embeddings
410//!
411//! Get a vector representation of a given input that can be easily consumed by machine learning models and algorithms.
412//!
413//! For more information see the examples in the [examples/embeddings](https://github.com/tjardoo/openai-client/tree/master/examples/embeddings) directory.
414//!
415//! - Create embeddings
416//!
417//! More information: [Embeddings](https://platform.openai.com/docs/api-reference/embeddings)
418//!
419//! ## Moderation
420//!
421//! Given some input text, outputs if the model classifies it as potentially harmful across several categories.
422//!
423//! For more information see the examples in the [examples/moderations](https://github.com/tjardoo/openai-client/tree/master/examples/moderations) directory.
424//!
425//! - Create moderation
426//!
427//! More information [Moderation](https://platform.openai.com/docs/api-reference/moderations)
428//!
429//! ## Uploads
430//!
431//! Creates an intermediate Upload object that you can add Parts to. Currently, an Upload can accept at most 8 GB in total and expires after an hour after you create it.
432//!
433//! Once you complete the Upload, we will create a File object that contains all the parts you uploaded. This File is usable in the rest of our platform as a regular File object.
434//!
435//! For more information see the examples in the [examples/uploads](https://github.com/tjardoo/openai-client/tree/master/examples/uploads) directory.
436//!
437//! - Create upload
438//! - Add upload part
439//! - Complete upload
440//! - Cancel upload
441//!
442//! More information [Uploads](https://platform.openai.com/docs/api-reference/uploads)
443//!
444//! ## Fine-tuning
445//!
446//! Manage fine-tuning jobs to tailor a model to your specific training data.
447//!
448//! For more information see the examples in the [examples/fine_tuning](https://github.com/tjardoo/openai-client/tree/master/examples/fine_tuning) directory.
449//!
450//! - Create fine-tuning job
451//! - List fine-tuning jobs
452//! - Retrieve fine-tuning job
453//! - Cancel fine-tuning job
454//! - List fine-tuning events
455//! - List fine-tuning checkpoints
456//!
457//! More information [Fine-tuning](https://platform.openai.com/docs/api-reference/fine-tuning)
458//!
459//! ## Batches
460//!
461//! Create large batches of API requests for asynchronous processing. The Batch API returns completions within 24 hours for a 50% discount.
462//!
463//! For more information see the examples in the [examples/batches](https://github.com/tjardoo/openai-client/tree/master/examples/batches) directory.
464//!
465//! - Create batch
466//! - List batches
467//! - Retrieve batch
468//! - Cancel batch
469//!
470//! More information [Batch](https://platform.openai.com/docs/api-reference/batch)
471//!
472//! ## Administration
473//!
474//! Programmatically manage your organization.
475//!
476//! For more information see the examples in the [examples/administration](https://github.com/tjardoo/openai-client/tree/master/examples/administration) directory.
477//!
478//! - Users
479//! - Invites
480//! - Projects
481//! - Project Users
482//! - Project Service Accounts
483//! - Project API Keys
484//! - Rate Limits
485//! - Audit Logs
486//!
487//! More information [Administration](https://platform.openai.com/docs/api-reference/administration)
488//!
489//! ## Usage
490//!
491//! The Usage API provides detailed insights into your activity across the OpenAI API.
492//!
493//! It also includes a separate Costs endpoint, which offers visibility into your spend, breaking down consumption by invoice line items and project IDs.
494//!
495//! For more information see the examples in the [examples/usage](https://github.com/tjardoo/openai-client/tree/master/examples/usage) directory.
496//!
497//! - Completions
498//! - Embeddings
499//! - Moderations
500//! - Images
501//! - Audio speeches
502//! - Audio transcriptions
503//! - Vector stores
504//! - Code interpreter sessions
505//! - Costs
506//!
507//! More information [Usage](https://platform.openai.com/docs/api-reference/usage)
508//!
509//! ## Realtime
510//!
511//! Communicate with a GPT-4o class model live, in real time, over WebSocket. Produces both audio and text transcriptions.
512//!
513//! Enable the feature flag `realtime` to use this feature.
514//!
515//! For more information see the examples in the [examples/realtime](https://github.com/tjardoo/openai-client/tree/master/examples/realtime) directory.
516//!
517//! - All client events
518//! - All server events
519//!
520//! More information [Realtime](https://platform.openai.com/docs/api-reference/realtime)
521//!
522//! ## Configuration
523//!
524//! ### Set API key
525//!
526//! Add the OpenAI API key to your environment variables.
527//!
528//! ```sh
529//! # Windows PowerShell
530//! $Env:OPENAI_API_KEY='sk-...'
531//!
532//! # Windows cmd
533//! set OPENAI_API_KEY=sk-...
534//!
535//! # Linux/macOS
536//! export OPENAI_API_KEY='sk-...'
537//! ```
538//!
539//! ### Using OpenAI-compatible APIs
540//!
541//! By simply changing the base URL, you can use this crate with other OpenAI-compatible APIs.
542//!
543//! ```rust
544//! let deepseek_api_key = std::env::var("DEEPSEEK_API_KEY").expect("DEEPSEEK_API_KEY is not set");
545//!
546//! let mut client = Client::new(deepseek_api_key);
547//! client.set_base_url("https://api.deepseek.com");
548//! ```
549//!
550//! Use `extra_body` in `ChatCompletionParameters` to pass non-standard parameters supported by OpenAI-compatible APIs.
551//!
552//! Use `query_params` in `ChatCompletionParameters` to pass non-standard `query` parameters supported by OpenAI-compatible APIs.
553//!
554//! ### Set organization/project ID
555//!
556//! You can create multiple organizations and projects in the OpenAI platform. This allows you to group files, fine-tuned models and other resources.
557//!
558//! You can set the organization ID and/or project ID on the client via the `set_organization` and `set_project` methods. If you don't set the organization and/or project ID, the client will use the default organization and default project.
559//!
560//! ```rust
561//! let mut client = Client::new_from_env();
562//!
563//! client
564//! .set_organization("org-XXX")
565//! .set_project("proj_XXX");
566//! ```
567//!
568//! ### Add proxy
569//!
570//! This crate uses `reqwest` as HTTP Client. Reqwest has proxies enabled by default. You can set the proxy via the system environment variable or by overriding the default client.
571//!
572//! #### Example: set system environment variable
573//!
574//! You can set the proxy in the system environment variables ([https://docs.rs/reqwest/latest/reqwest/#proxies](https://docs.rs/reqwest/latest/reqwest/#proxies)).
575//!
576//! ```sh
577//! export HTTPS_PROXY=socks5://127.0.0.1:1086
578//! ```
579//!
580//! #### Example: overriding the default client
581//!
582//! ```rust
583//! use openai_dive::v1::api::Client;
584//!
585//! let http_client = reqwest::Client::builder()
586//! .proxy(reqwest::Proxy::https("socks5://127.0.0.1:1086")?)
587//! .build()?;
588//!
589//! let api_key = std::env::var("OPENAI_API_KEY").expect("$OPENAI_API_KEY is not set");
590//!
591//! let client = Client {
592//! http_client,
593//! base_url: "https://api.openai.com/v1".to_string(),
594//! api_key,
595//! headers: None,
596//! organization: None,
597//! project: None,
598//! };
599//! ```
600//!
601//! ### Available Models
602//!
603//! You can use these predefined constants to set the model in the parameters or use any string representation (ie. for your custom models).
604//!
605//! #### GPT-5
606//!
607//! - Gpt51 (`gpt-5.1`)
608//! - Gpt5O (`gpt-5o`)
609//! - Gpt5OAudioPreview (`gpt-5o-audio-preview`)
610//!
611//! #### GPT-4
612//!
613//! - Gpt41 (`gpt-4.1`)
614//! - Gpt4O (`gpt-4o`)
615//! - Gpt4OAudioPreview (`gpt-4o-audio-preview`)
616//!
617//! #### Tool Models
618//!
619//! - Gpt4OSearchPreview (`gpt-4o-search-preview`)
620//! - Gpt4OMiniSearchPreview (`gpt-4o-mini-search-preview`)
621//! - ComputerUsePreview (`computer-use-preview`)
622//!
623//! #### Moderation Models
624//!
625//! - OmniModerationLatest (`omni-moderation-latest`)
626//!
627//! #### Embedding Models
628//!
629//! - TextEmbedding3Small (`text-embedding-3-small`)
630//! - TextEmbedding3Large (`text-embedding-3-large`)
631//!
632//! #### Transcription Models
633//!
634//! - Gpt4OTranscribe (`gpt-4o-transcribe`)
635//! - Whisper1 (`whisper-1`)
636//!
637//! #### TTS Models
638//!
639//! - Gpt4OMiniTts (`gpt-4o-mini-tts`)
640//! - Tts1 (`tts-1`)
641//! - Tts1HD (`tts-1-hd`)
642//!
643//! #### Image Models
644//!
645//! - GptImage1 (`gpt-image-1`)
646//! - DallE3 (`dall-e-3`)
647//! - DallE2 (`dall-e-2`)
648//!
649//! #### Video Models
650//!
651//! - Sora2 (`sora-2`)
652//! - Sora2Pro (`sora-2-pro`)
653//!
654//! More information: [Models](https://platform.openai.com/docs/models)
655
656pub mod v1;