This repository was archived by the owner on Nov 1, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathresponse.rs
More file actions
189 lines (173 loc) Β· 5 KB
/
Copy pathresponse.rs
File metadata and controls
189 lines (173 loc) Β· 5 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
//! Example usage of the OpenAI response API.
// std
use std::{env, error::Error};
// crates.io
use futures::StreamExt;
use tracing_subscriber::EnvFilter;
// self
use openagent::prelude::*;
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
tracing_subscriber::fmt().with_env_filter(EnvFilter::from_default_env()).init();
let _ = dotenvy::dotenv();
let api = Api::new(Auth {
uri: "https://api.openai.com/v1".into(),
key: env::var("OPENAI_API_KEY").expect("OPENAI_API_KEY must be set; qed"),
});
let req = ResponseRequest {
input: Either::A("Hello, how are you?".into()),
model: Model::Gpt4oMini,
// model: Model::Custom {
// id: "".into(),
// name: "".into(),
// embedding: false,
// reasoning: false,
// function_calling: false,
// },
..Default::default()
};
println!("request: {}", serde_json::to_string(&req)?);
// Example 1: Non-streaming response.
println!("=== non-streaming response ===");
println!("{:#?}", api.create_response(req.clone()).await);
// Example 2: Streaming response with typed event handler.
println!("\n=== streaming response with typed events ===");
match api
.create_response_stream(
req.clone(),
SseOptions::new(ApiEventHandler::default()).drop_event(true),
)
.await
{
Ok(mut stream) =>
while let Some(event_res) = stream.next().await {
match event_res {
Ok(event) => match event {
ResponseEvent::Created(e) => {
println!("π response created: {e:?}");
},
ResponseEvent::InProgress(e) => {
println!("β³ response in progress: {e:?}");
},
ResponseEvent::OutputItemAdded(e) => {
println!("π output item added: {e:?}");
},
ResponseEvent::ContentPartAdded(e) => {
println!("π content part added: {e:?}");
},
ResponseEvent::OutputTextDelta(e) => {
print!("{}", e.delta);
},
ResponseEvent::OutputTextDone(e) => {
println!("\nβ
text output done: {e:?}");
},
ResponseEvent::ContentPartDone(e) => {
println!("β
content part done: {e:?}");
},
ResponseEvent::OutputItemDone(e) => {
println!("β
output item done: {e:?}");
},
ResponseEvent::Completed(e) => {
println!("π response completed: {e:?}");
println!(
"π usage: {} input + {} output = {} total tokens",
e.response.usage.as_ref().unwrap().input_tokens,
e.response.usage.as_ref().unwrap().output_tokens,
e.response.usage.as_ref().unwrap().total_tokens
);
},
_ => (),
},
Err(e) => {
println!("β stream error: {e:#?}");
break;
},
}
},
Err(e) => {
println!("β error: {e:#?}");
},
}
// Example 3: Custom event handler for accumulating text.
println!("\n=== custom event handler example ===");
struct TextAccumulator {
content: String,
}
impl TextAccumulator {
fn new() -> Self {
Self { content: String::new() }
}
fn handle_event(&mut self, event: &ResponseEvent) {
match event {
ResponseEvent::Created(e) => {
println!("π starting response: {}", e.response.id);
},
ResponseEvent::OutputTextDelta(e) => {
self.content.push_str(&e.delta);
print!("{}", e.delta);
},
ResponseEvent::Completed(e) => {
println!("\nπ final accumulated text ({} chars):", self.content.len());
println!("\"{}\"", self.content);
println!(
"π total tokens used: {}",
e.response.usage.as_ref().unwrap().total_tokens
);
},
_ => (),
}
}
}
let mut accumulator = TextAccumulator::new();
match api
.create_response_stream(
ResponseRequest {
model: Model::Gpt4oMini,
// model: Model::Custom {
// id: "".into(),
// name: "".into(),
// embedding: false,
// reasoning: false,
// function_calling: false,
// },
input: Either::B(vec![ResponseInput::Message(ResponseMessage {
content: Either::B(vec![
ResponseMessageInputContent::InputText {
text: "Come up with keywords related to the image, and search on the web using the search tool for any news related to the keywords, summarize the findings and cite the sources.".into(),
},
ResponseMessageInputContent::InputImage {
detail: Default::default(),
file_id: Default::default(),
image_url: Some("https://upload.wikimedia.org/wikipedia/commons/thumb/1/15/Cat_August_2010-4.jpg/2880px-Cat_August_2010-4.jpg".into()),
},
]),
role: Role::User,
})]),
tools: Some(vec![Tool::WebSearchPreview {
search_context_size: Default::default(),
user_location: Default::default(),
}]),
..Default::default()
},
SseOptions::new(ApiEventHandler::default()).drop_event(true),
)
.await
{
Ok(mut stream) =>
while let Some(event_result) = stream.next().await {
match event_result {
Ok(event) => {
accumulator.handle_event(&event);
},
Err(e) => {
println!("β stream error: {e:#?}");
break;
},
}
},
Err(e) => {
println!("β error: {e:#?}");
},
}
Ok(())
}