forked from 0xPlaygrounds/rig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
multi_extract.rs
88 lines (77 loc) · 2.63 KB
/
multi_extract.rs
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
80
81
82
83
84
85
86
87
88
use rig::{
pipeline::{self, agent_ops, TryOp},
providers::openai,
try_parallel,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, JsonSchema, Serialize)]
/// A record containing extracted names
pub struct Names {
/// The names extracted from the text
pub names: Vec<String>,
}
#[derive(Debug, Deserialize, JsonSchema, Serialize)]
/// A record containing extracted topics
pub struct Topics {
/// The topics extracted from the text
pub topics: Vec<String>,
}
#[derive(Debug, Deserialize, JsonSchema, Serialize)]
/// A record containing extracted sentiment
pub struct Sentiment {
/// The sentiment of the text (-1 being negative, 1 being positive)
pub sentiment: f64,
/// The confidence of the sentiment
pub confidence: f64,
}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
let openai = openai::Client::from_env();
let names_extractor = openai
.extractor::<Names>("gpt-4")
.preamble("Extract names (e.g.: of people, places) from the given text.")
.build();
let topics_extractor = openai
.extractor::<Topics>("gpt-4")
.preamble("Extract topics from the given text.")
.build();
let sentiment_extractor = openai
.extractor::<Sentiment>("gpt-4")
.preamble(
"Extract sentiment (and how confident you are of the sentiment) from the given text.",
)
.build();
// Create a chain that extracts names, topics, and sentiment from a given text
// using three different GPT-4 based extractors.
// The chain will output a formatted string containing the extracted information.
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: {names}\nExtracted topics: {topics}\nExtracted sentiment: {sentiment}",
names = names.names.join(", "),
topics = topics.topics.join(", "),
sentiment = sentiment.sentiment,
)
});
// Batch call the chain with up to 4 inputs concurrently
let response = chain
.try_batch_call(
4,
vec![
"Screw you Putin!",
"I love my dog, but I hate my cat.",
"I'm going to the store to buy some milk.",
],
)
.await?;
for response in response {
println!("Text analysis:\n{response}");
}
Ok(())
}