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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
//! Provider: the interface for communicating with an LLM.
//!
//! This module defines the `Provider` trait and its companion data types:
//! requests ([`ChatRequest`]), responses ([`ChatResponse`] / [`StreamEvent`]),
//! errors ([`ProviderError`]), and usage ([`Usage`]). The trait itself is
//! vendor-agnostic; the implementations ([`OpenAiProvider`] / [`FakeProvider`]
//! / [`RetryProvider`]) all implement the same trait, and any implementation
//! can be wrapped by [`RetryProvider`] to gain retry capability.
pub use ;
pub use ;
pub use ;
use crateMessage;
use crateToolSchema;
use BoxStream;
use ;
use BTreeMap;
use Duration;
/// The interface for chatting with an LLM.
///
/// Implementations are responsible for communicating with a specific LLM
/// service and mapping vendor responses back to this framework's [`Message`];
/// [`chat`](Provider::chat) returns the full reply at once, while
/// [`stream_chat`](Provider::stream_chat) returns the same reply incrementally
/// as a stream of events. Both share the same semantics and differ only in
/// delivery.
///
/// `Send + Sync` guarantees that `Box<dyn Provider>` can be held across
/// awaits in Agent implementations (for the same reason as
/// [`Tool`](crate::tool::Tool)).
///
/// # Examples
///
/// The calling convention is identical for every implementation; the example
/// below uses [`FakeProvider`]:
///
/// ```rust
/// # #[tokio::main]
/// # async fn main() -> Result<(), molo::ProviderError> {
/// use molo::provider::{ChatRequest, FakeProvider, FakeReply, Provider};
///
/// let fake = FakeProvider::new([FakeReply::Text("hi".into())]);
/// let response = fake.chat(ChatRequest::default()).await?;
/// assert_eq!(response.message, molo::message::Message::assistant("hi"));
/// # Ok(())
/// # }
/// ```
/// `Box<dyn Provider>` is itself a Provider: re-exposes the trait object as a
/// value, for assembly patterns that need to "hold an instance and create a
/// new loop per call" (e.g., a sub-agent factory that captures a provider and
/// constructs a fresh loop for each invocation).
/// A single conversation request.
///
/// # Examples
///
/// ```rust
/// use molo::message::Message;
/// use molo::provider::ChatRequest;
///
/// let request = ChatRequest {
/// messages: vec![Message::user("hi")],
/// ..Default::default()
/// };
/// # let _ = request;
/// ```
/// Model options for one conversation.
///
/// Common parameters are provided as typed fields (temperature / max tokens,
/// where `None` means vendor default); **vendor-specific or framework-unknown
/// parameters go into [`extra`](ModelOptions::extra)** and are passed through
/// to the vendor verbatim under their wire field names — so users can use new
/// parameters without waiting for a framework update:
///
/// ```rust
/// use molo::ModelOptions;
///
/// let mut options = ModelOptions::default();
/// options.extra.insert("top_p".into(), serde_json::json!(0.9));
/// ```
///
/// Extra keys that collide with framework-managed fields are ignored in favor
/// of the typed fields.
/// Token usage for one conversation.
///
/// Field names match the OpenAI wire format; `total_tokens` follows the
/// vendor's convention (not necessarily the sum of the other two). `Default`
/// = all zeros (endpoints that omit usage count as zero).
///
/// Usage serves two consumers: the Agent layer accumulates it per turn into
/// the end-of-loop summary, while external observability (logs / metrics)
/// reads it directly — consumers do not need to distinguish the source.
/// Usage accumulates per turn (the Agent layer sums tokens across turns).
/// The reply to one conversation.
/// Why the model ended its reply.
///
/// Common reasons are typed (Stop / Length); vendor-specific or
/// framework-unknown reasons are surfaced via [`Other`](FinishReason::Other)
/// carrying the vendor's raw string — users can recognize new reasons without
/// waiting for a framework update. `#[non_exhaustive]` guarantees that adding
/// new common categories in the future is not a breaking change.
/// An event in a streamed conversation reply.
///
/// One streamed reply = several [`StreamEvent::Delta`] /
/// [`StreamEvent::ToolCall`] increments + one closing [`StreamEvent::Done`];
/// the caller concatenates the Deltas in order to get the full reply.
///
/// Stream termination semantics: on normal termination `Done` is always the
/// last success event on the stream; errors terminate the stream with an
/// `Err` item, and no events are produced after the error item.
///
/// The enum is `#[non_exhaustive]` (reserved for extension): matches must
/// include a wildcard arm.
/// Why a Provider call failed.
///
/// The enum categories cover the cases that need distinguishing, with details
/// carried by fields; vendor-specific errors are mapped into this type at the
/// implementation boundary. `#[non_exhaustive]` guarantees that adding new
/// categories in the future is not a breaking change.
///
/// Error classification is the basis for retry decisions (see the `Default`
/// judgment of [`Retryable`]): Network / Timeout / RateLimited are worth
/// retrying, while `Api` is judged by status (5xx retried, 4xx not — retrying
/// would not change the outcome).
/// The stage at which a timeout occurred: one-to-one with
/// [`OpenAiProvider`]'s four timeouts (connect / non-streaming total /
/// streaming event interval / streaming total), plus the error-response-body
/// read timeout and a generic transport timeout.
///
/// The enum is `#[non_exhaustive]` (reserved for extension): matches must
/// include a wildcard arm.