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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
/// A pinned, boxed stream of content blocks from the model.
///
/// This type alias represents an asynchronous stream that yields `ContentBlock` items.
/// Each item is wrapped in a `Result` to handle potential errors during streaming.
///
/// The stream is:
/// - **Pinned** (`Pin<Box<...>>`): Required for safe async operations and self-referential types
/// - **Boxed**: Allows dynamic dispatch and hides the concrete stream implementation
/// - **Send**: Can be safely transferred between threads
///
/// # Content Blocks
///
/// The stream can yield several types of content blocks:
///
/// - **TextBlock**: Incremental text responses from the model
/// - **ToolUseBlock**: Requests to execute a tool with specific parameters
/// - **ToolResultBlock**: Results from tool execution (in manual mode)
///
/// # Error Handling
///
/// Errors in the stream indicate issues like:
/// - Network failures or timeouts
/// - Malformed SSE events
/// - JSON parsing errors
/// - API errors from the model provider
///
/// When an error occurs, the stream typically terminates. It's the caller's responsibility
/// to handle errors appropriately.
///
/// # Examples
///
/// ```rust,no_run
/// use open_agent::{query, AgentOptions, ContentBlock};
/// use futures::StreamExt;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let options = AgentOptions::builder()
/// .model("gpt-4")
/// .api_key("sk-...")
/// .build()?;
///
/// let mut stream = query("Hello!", &options).await?;
///
/// while let Some(result) = stream.next().await {
/// match result {
/// Ok(ContentBlock::Text(text)) => print!("{}", text.text),
/// Ok(_) => {}, // Other block types
/// Err(e) => eprintln!("Stream error: {}", e),
/// }
/// }
/// # Ok(())
/// # }
/// ```
pub type ContentStream = ;
/// Simple query function for single-turn interactions without conversation history.
///
/// This is a stateless convenience function for simple queries that don't require
/// multi-turn conversations. It creates a temporary HTTP client, sends a single
/// prompt, and returns a stream of content blocks.
///
/// For multi-turn conversations or more control over the interaction, use [`Client`] instead.
///
/// # Parameters
///
/// - `prompt`: The user's message to send to the model
/// - `options`: Configuration including model, API key, tools, etc.
///
/// # Returns
///
/// Returns a `ContentStream` that yields content blocks as they arrive from the model.
/// The stream must be polled to completion to receive all blocks.
///
/// # Behavior
///
/// 1. Creates a temporary HTTP client with configured timeout
/// 2. Builds message array (system prompt + user prompt)
/// 3. Converts tools to OpenAI format if provided
/// 4. Makes HTTP POST request to `/chat/completions`
/// 5. Parses Server-Sent Events (SSE) response stream
/// 6. Aggregates chunks into complete content blocks
/// 7. Returns stream that yields blocks as they complete
///
/// # Error Handling
///
/// This function can return errors for:
/// - HTTP client creation failures
/// - Network errors during the request
/// - API errors (authentication, invalid model, rate limits, etc.)
/// - SSE parsing errors
/// - JSON deserialization errors
///
/// # Performance Notes
///
/// - Creates a new HTTP client for each call (consider using `Client` for repeated queries)
/// - Timeout is configurable via `AgentOptions::timeout` (default: 120 seconds)
/// - Streaming begins immediately; no buffering of the full response
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust,no_run
/// use open_agent::{query, AgentOptions};
/// use futures::StreamExt;
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let options = AgentOptions::builder()
/// .system_prompt("You are a helpful assistant")
/// .model("gpt-4")
/// .api_key("sk-...")
/// .build()?;
///
/// let mut stream = query("What's the capital of France?", &options).await?;
///
/// while let Some(block) = stream.next().await {
/// match block? {
/// open_agent::ContentBlock::Text(text) => {
/// print!("{}", text.text);
/// }
/// open_agent::ContentBlock::ToolUse(_)
/// | open_agent::ContentBlock::ToolResult(_)
/// | open_agent::ContentBlock::Image(_) => {}
/// }
/// }
///
/// Ok(())
/// }
/// ```
///
/// ## With Tools
///
/// ```rust,no_run
/// use open_agent::{query, AgentOptions, Tool, ContentBlock};
/// use futures::StreamExt;
/// use serde_json::json;
///
/// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let calculator = Tool::new(
/// "calculator",
/// "Performs calculations",
/// json!({"type": "object"}),
/// |input| Box::pin(async move { Ok(json!({"result": 42})) })
/// );
///
/// let options = AgentOptions::builder()
/// .model("gpt-4")
/// .api_key("sk-...")
/// .tools(vec![calculator])
/// .build()?;
///
/// let mut stream = query("Calculate 2+2", &options).await?;
///
/// while let Some(block) = stream.next().await {
/// match block? {
/// ContentBlock::ToolUse(tool_use) => {
/// println!("Model wants to use: {}", tool_use.name());
/// // Note: You'll need to manually execute tools and continue
/// // the conversation. For automatic execution, use Client.
/// }
/// ContentBlock::Text(text) => print!("{}", text.text),
/// ContentBlock::ToolResult(_) | ContentBlock::Image(_) => {}
/// }
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## Error Handling
///
/// ```rust,no_run
/// use open_agent::{query, AgentOptions};
/// use futures::StreamExt;
///
/// # async fn example() {
/// let options = AgentOptions::builder()
/// .model("gpt-4")
/// .api_key("invalid-key")
/// .build()
/// .unwrap();
///
/// match query("Hello", &options).await {
/// Ok(mut stream) => {
/// while let Some(result) = stream.next().await {
/// match result {
/// Ok(block) => println!("Block: {:?}", block),
/// Err(e) => {
/// eprintln!("Stream error: {}", e);
/// break;
/// }
/// }
/// }
/// }
/// Err(e) => eprintln!("Query failed: {}", e),
/// }
/// # }
/// ```
pub async