Skip to content

Commit bb35f04

Browse files
author
Alex Andreba
committed
more preps
1 parent 7bd35b0 commit bb35f04

File tree

13 files changed

+173
-160
lines changed

13 files changed

+173
-160
lines changed

.github/workflows/rust.yml

+12-1
Original file line numberDiff line numberDiff line change
@@ -16,4 +16,15 @@ jobs:
1616
steps:
1717
- uses: actions/checkout@v3
1818
- name: Build
19-
run: cargo build --verbose
19+
run:
20+
- cargo build --verbose
21+
- cargo build --verbose --all-features
22+
- cargo build --verbose --tests
23+
- cargo build --verbose --tests --all-features
24+
25+
- name: Check
26+
run:
27+
- cargo check --verbose
28+
- cargo check --verbose --all-features
29+
- cargo check --verbose --tests
30+
- cargo check --verbose --tests --all-features

Cargo.toml

+1-1
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ categories = [
1414
]
1515
repository = "https://github.com/Aandreba/libopenai"
1616
license-file = "LICENSE.md"
17-
exclude = [".github", "media", "Makefile"]
17+
exclude = [".github", "examples", "media", "Makefile"]
1818

1919
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
2020

Makefile

+6
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
1+
check:
2+
cargo check
3+
cargo check --all-features
4+
cargo check --tests
5+
cargo check --tests --all-features
6+
17
doc:
28
cargo +nightly rustdoc --all-features --open -- --cfg docsrs

README.md

+9-2
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,8 @@ use libopenai::prelude::*;
2222

2323
#[tokio::main]
2424
async fn main() -> Result<()> {
25-
# dotenv::dotenv().unwrap();
25+
// OPTIONAL: Load variables in a `.env` file into the enviroment
26+
dotenv::dotenv().unwrap();
2627

2728
let client = Client::new(
2829
None, // Gets api key from `OPENAI_API_KEY` enviroment variable
@@ -41,9 +42,15 @@ async fn main() -> Result<()> {
4142
println!("{:#?}", basic);
4243
return Ok(());
4344
}
44-
4545
```
4646

4747
## Features
4848

49+
- Support for completions (regular & chat)
50+
- [Image generation](https://docs.rs/libopenai/latest/libopenai/image) with automatic conversion to desired formats
51+
- [Audio-to-text](https://docs.rs/libopenai/latest/libopenai/audio) conversions
52+
- Support for streaming
53+
54+
## Cargo features
55+
4956
Currently, the only feature available is **tracing**, which enables some minor logging

examples/audio.rs

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
use libopenai::prelude::*;
2+
3+
#[tokio::main]
4+
async fn main() -> Result<()> {
5+
dotenv::dotenv().unwrap();
6+
tracing_subscriber::fmt::init();
7+
8+
let client = Client::new(None, None)?;
9+
10+
let srt = TranscriptionBuilder::new()
11+
.response_format(libopenai::audio::AudioResponseFormat::Srt)
12+
.temperature(0.0)?
13+
.with_file("./media/audio.mp3", &client)
14+
.await?;
15+
16+
println!("{:#?}", srt.text());
17+
println!("{:#?}", srt.duration());
18+
println!("{:#?}", srt.segments().map(Iterator::collect::<Vec<_>>));
19+
20+
let verbose = TranscriptionBuilder::new()
21+
.response_format(libopenai::audio::AudioResponseFormat::VerboseJson)
22+
.temperature(0.0)?
23+
.with_file("./media/audio.mp3", &client)
24+
.await?;
25+
26+
println!("{:#?}", verbose.text());
27+
println!("{:#?}", verbose.duration());
28+
println!("{:#?}", verbose.segments().map(Iterator::collect::<Vec<_>>));
29+
30+
return Ok(());
31+
}

examples/main.rs examples/basic.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ use libopenai::prelude::*;
33
#[tokio::main]
44
async fn main() -> Result<()> {
55
dotenv::dotenv().unwrap();
6+
tracing_subscriber::fmt::init();
67

78
let client = Client::new(
89
None, // Gets api key from `OPENAI_API_KEY` enviroment variable

examples/finetune.rs

+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
use futures::TryStreamExt;
2+
use libopenai::{file::TemporaryFile, prelude::*};
3+
4+
#[tokio::main]
5+
async fn main() -> Result<()> {
6+
const MODEL: &str = "text-davinci-003";
7+
8+
dotenv::dotenv().unwrap();
9+
tracing_subscriber::fmt::init();
10+
let client = Client::new(None, None)?;
11+
12+
let ft = match FineTune::retreive("ft-8KUqxC0IcvgVe707j93Xoa6D", &client).await {
13+
Ok(x) => x,
14+
Err(_) => {
15+
let questions = Completion::builder(MODEL, "Give me a math question")
16+
.n(10)
17+
.max_tokens(100)
18+
.build(&client)
19+
.await?
20+
.choices;
21+
22+
let answers = Completion::raw_builder(MODEL)
23+
.echo(true)
24+
.prompt(questions.iter().map(|x| x.text.as_str()))
25+
.max_tokens(256)
26+
.build(&client)
27+
.await?
28+
.choices
29+
.into_iter()
30+
.filter_map(|x| {
31+
if let Some((prompt, completion)) = x.text.split_once("\n\n") {
32+
return Some(TrainingData::new(prompt, completion));
33+
}
34+
return None;
35+
});
36+
37+
let training_file = TemporaryFile::from_file(
38+
TrainingData::save_iter(answers, &client).await?,
39+
client.clone(),
40+
);
41+
42+
FineTune::new(&training_file.id, &client).await?
43+
}
44+
};
45+
46+
let mut events = ft.event_stream(&client).await.unwrap();
47+
48+
let handle = tokio::spawn(async move {
49+
while let Some(event) = events.try_next().await.unwrap() {
50+
println!("{event:#?}");
51+
}
52+
return Result::<()>::Ok(());
53+
});
54+
55+
let example = Completion::new(ft.fine_tuned_model()?, "square root of two", client)
56+
.await
57+
.unwrap();
58+
println!("{example:#?}");
59+
60+
handle.await.unwrap()?;
61+
return Ok(());
62+
}

examples/image.rs

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
use libopenai::prelude::*;
2+
3+
#[tokio::main]
4+
async fn main() -> Result<()> {
5+
dotenv::dotenv().unwrap();
6+
tracing_subscriber::fmt::init();
7+
8+
let client = Client::new(None, None)?;
9+
10+
Images::create("Nintendo Switch playing The Last of Us")?
11+
.n(2)?
12+
.build(&client)
13+
.await?
14+
.save_at("./media/out")
15+
.await?;
16+
17+
return Ok(());
18+
}

examples/streamed.rs

+24
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
use futures::TryStreamExt;
2+
use libopenai::prelude::*;
3+
4+
#[tokio::main]
5+
async fn main() -> Result<()> {
6+
dotenv::dotenv().unwrap();
7+
tracing_subscriber::fmt::init();
8+
9+
let client = Client::new(None, None)?;
10+
11+
let mut stream = Completion::builder(
12+
"text-davinci-003",
13+
"What's the best way to calculate a factorial?",
14+
)
15+
.max_tokens(256)
16+
.build_stream(&client)
17+
.await?;
18+
19+
while let Some(completion) = stream.try_next().await? {
20+
println!("{completion:#?}");
21+
}
22+
23+
return Ok(());
24+
}

src/file.rs

+6-1
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@ use std::{
2525
};
2626
use tokio_util::io::ReaderStream;
2727

28+
// File that is deleted when dropped
2829
#[derive(Debug)]
2930
pub struct TemporaryFile {
3031
inner: File,
@@ -234,15 +235,19 @@ impl<S: Stream<Item = reqwest::Result<Bytes>>, T: DeserializeOwned> Stream for C
234235
}
235236

236237
impl TemporaryFile {
238+
/// Creates a new [`TemporaryFile`] from an existing [`File`] instance.
237239
#[inline]
238-
pub fn new(inner: File, client: Client) -> Self {
240+
pub fn from_file(inner: File, client: Client) -> Self {
239241
return Self {
240242
inner,
241243
client,
242244
deleting: false,
243245
};
244246
}
245247

248+
/// Returns the inner [`File`]
249+
///
250+
/// Note that after this function is invoked, the file will no longer be automatically deleted when dropped.
246251
#[inline]
247252
pub fn into_inner(self) -> File {
248253
let mut this = ManuallyDrop::new(self);

src/image/variation.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,8 @@ impl VariationBuilder {
8080
}
8181

8282
/// Sends the request with the specified file
83+
///
84+
/// If the images do not conform to OpenAI's requirements, they will be adapted before they are sent
8385
pub async fn with_file(
8486
self,
8587
image: impl Into<PathBuf>,
@@ -102,8 +104,6 @@ impl VariationBuilder {
102104
}
103105

104106
/// Sends the request with the specified file.
105-
///
106-
/// If the images do not conform to OpenAI's requirements, they will be adapted before they are sent
107107
pub async fn with_tokio_reader<I>(self, image: I, client: impl AsRef<Client>) -> Result<Images>
108108
where
109109
I: 'static + Send + Sync + tokio::io::AsyncRead,

src/lib.rs

+1
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ pub mod prelude {
6767

6868
pub use file::File;
6969

70+
pub use finetune::data::TrainingData;
7071
pub use finetune::{FineTune, FineTuneEvent};
7172

7273
pub use super::image::ImageData;

0 commit comments

Comments
 (0)