forked from 0xPlaygrounds/rig
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmulti_extract.rs
More file actions
79 lines (69 loc) 路 2.27 KB
/
Copy pathmulti_extract.rs
File metadata and controls
79 lines (69 loc) 路 2.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
//! Demonstrates fan-out structured extraction with `try_parallel!`.
//! Requires `OPENAI_API_KEY`.
//! Run it to see one batch of text split into names, topics, and sentiment in parallel.
use anyhow::Result;
use rig::client::ProviderClient;
use rig::pipeline::{self, TryOp, agent_ops};
use rig::providers::openai;
use rig::try_parallel;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, JsonSchema, Serialize)]
struct Names {
names: Vec<String>,
}
#[derive(Debug, Deserialize, JsonSchema, Serialize)]
struct Topics {
topics: Vec<String>,
}
#[derive(Debug, Deserialize, JsonSchema, Serialize)]
struct Sentiment {
sentiment: f64,
confidence: f64,
}
fn sample_inputs() -> Vec<&'static str> {
vec![
"Screw you Putin!",
"I love my dog, but I hate my cat.",
"I'm going to the store to buy some milk.",
]
}
#[tokio::main]
async fn main() -> Result<()> {
let client = openai::Client::from_env()?;
let names_extractor = client
.extractor::<Names>(openai::GPT_4O_MINI)
.preamble("Extract names from the given text.")
.retries(2)
.build();
let topics_extractor = client
.extractor::<Topics>(openai::GPT_4O_MINI)
.preamble("Extract topics from the given text.")
.retries(2)
.build();
let sentiment_extractor = client
.extractor::<Sentiment>(openai::GPT_4O_MINI)
.preamble("Extract sentiment and confidence from the given text.")
.retries(2)
.build();
let chain = pipeline::new()
.chain(try_parallel!(
agent_ops::extract(names_extractor),
agent_ops::extract(topics_extractor),
agent_ops::extract(sentiment_extractor),
))
.map_ok(|(names, topics, sentiment)| {
format!(
"Extracted names: {}\nExtracted topics: {}\nExtracted sentiment: {} ({})",
names.names.join(", "),
topics.topics.join(", "),
sentiment.sentiment,
sentiment.confidence,
)
});
let responses = chain.try_batch_call(4, sample_inputs()).await?;
for (idx, response) in responses.iter().enumerate() {
println!("batch item {}:\n{response}\n", idx + 1);
}
Ok(())
}