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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
//! Provider trait and types for LLM abstraction.
//!
//! This module defines the [`LlmProvider`] trait that all LLM providers implement,
//! along with request/response types, tool definitions, and configuration.
//!
//! # Overview
//!
//! The provider abstraction allows you to:
//! - Switch between LLM providers without changing your application code
//! - Use a consistent interface for all LLM operations
//! - Access provider-specific features (like caching) through unified APIs
//!
//! # Provider Trait
//!
//! All providers implement [`LlmProvider`], which provides:
//! - [`execute_llm()`](LlmProvider::execute_llm): Execute a standard LLM request
//! - [`execute_structured_llm()`](LlmProvider::execute_structured_llm): Execute with JSON schema output
//! - [`provider_name()`](LlmProvider::provider_name): Get the provider identifier
//!
//! # Tool Calling
//!
//! Define tools with [`Tool`] and handle the calling flow:
//!
//! ```rust
//! use multi_llm::{Tool, ToolChoice, ToolCall, ToolResult};
//!
//! // Define a tool
//! let weather_tool = Tool {
//! name: "get_weather".to_string(),
//! description: "Get current weather for a city".to_string(),
//! parameters: serde_json::json!({
//! "type": "object",
//! "properties": {
//! "city": {"type": "string", "description": "City name"}
//! },
//! "required": ["city"]
//! }),
//! };
//!
//! // Handle a tool call from the LLM
//! let tool_call = ToolCall {
//! id: "call_123".to_string(),
//! name: "get_weather".to_string(),
//! arguments: serde_json::json!({"city": "London"}),
//! };
//!
//! // Return the result
//! let result = ToolResult {
//! tool_call_id: "call_123".to_string(),
//! content: "Sunny, 22°C".to_string(),
//! is_error: false,
//! error_category: None,
//! };
//! ```
//!
//! # Response Structure
//!
//! All providers return a [`Response`] containing:
//! - Text content (for standard requests)
//! - Structured JSON (when using `execute_structured_llm`)
//! - Tool calls (when the model wants to call functions)
//! - Token usage statistics
use crateUserErrorCategory;
use crate;
use crate;
use ;
/// Result type alias for provider operations.
///
/// Uses [`LlmError`](crate::LlmError) for structured error handling with
/// rich metadata (categories, retry info, user messages).
///
/// See [`LlmError`](crate::LlmError) for available error variants and helper methods:
/// - [`is_retryable()`](crate::LlmError::is_retryable): Check if retry makes sense
/// - [`category()`](crate::LlmError::category): Get error category for routing
/// - [`user_message()`](crate::LlmError::user_message): Get safe user-facing message
pub type Result<T> = Result;
/// Definition of a tool/function that the LLM can call.
///
/// Tools allow LLMs to perform actions by generating structured calls that your
/// application executes. The LLM sees the tool's name, description, and parameter
/// schema to understand when and how to use it.
///
/// # Example
///
/// ```rust
/// use multi_llm::Tool;
///
/// let search_tool = Tool {
/// name: "web_search".to_string(),
/// description: "Search the web for information".to_string(),
/// parameters: serde_json::json!({
/// "type": "object",
/// "properties": {
/// "query": {
/// "type": "string",
/// "description": "The search query"
/// },
/// "max_results": {
/// "type": "integer",
/// "description": "Maximum results to return",
/// "default": 10
/// }
/// },
/// "required": ["query"]
/// }),
/// };
/// ```
///
/// # Parameter Schema
///
/// The `parameters` field should be a valid JSON Schema object describing the
/// tool's input. Use `type`, `properties`, `required`, and `description` fields
/// to help the LLM understand how to call your tool correctly.
/// A tool call generated by the LLM.
///
/// When the LLM decides to use a tool, it generates a `ToolCall` with:
/// - A unique ID to match with the response
/// - The tool name to invoke
/// - Arguments parsed from the conversation
///
/// Your application should:
/// 1. Execute the tool with the provided arguments
/// 2. Return a [`ToolResult`] with the matching `tool_call_id`
/// 3. Continue the conversation so the LLM can use the result
///
/// # Example
///
/// ```rust
/// use multi_llm::ToolCall;
///
/// // Received from LLM response
/// let call = ToolCall {
/// id: "call_abc123".to_string(),
/// name: "get_weather".to_string(),
/// arguments: serde_json::json!({"city": "Paris", "units": "celsius"}),
/// };
///
/// // Parse and execute
/// let city = call.arguments["city"].as_str().unwrap();
/// // ... execute weather lookup ...
/// ```
/// Result from executing a tool, sent back to the LLM.
///
/// After executing a [`ToolCall`], create a `ToolResult` to send back.
/// The LLM will use this information to continue the conversation.
///
/// # Example
///
/// ```rust
/// use multi_llm::ToolResult;
///
/// // Successful result
/// let success = ToolResult {
/// tool_call_id: "call_abc123".to_string(),
/// content: "Weather in Paris: Sunny, 18°C".to_string(),
/// is_error: false,
/// error_category: None,
/// };
///
/// // Error result
/// use multi_llm::error::UserErrorCategory;
/// let error = ToolResult {
/// tool_call_id: "call_xyz789".to_string(),
/// content: "City not found".to_string(),
/// is_error: true,
/// error_category: Some(UserErrorCategory::NotFound),
/// };
/// ```
/// Strategy for how the LLM should handle tool selection.
///
/// Controls whether the LLM must use tools, can choose to use them, or is
/// restricted from using them.
///
/// # Example
///
/// ```rust
/// use multi_llm::{RequestConfig, ToolChoice};
///
/// // Let the model decide
/// let config = RequestConfig {
/// tool_choice: Some(ToolChoice::Auto),
/// ..Default::default()
/// };
///
/// // Force a specific tool
/// let config = RequestConfig {
/// tool_choice: Some(ToolChoice::Specific("get_weather".to_string())),
/// ..Default::default()
/// };
/// ```
/// Configuration for a single LLM request.
///
/// Override default provider settings on a per-request basis. All fields are
/// optional - unset fields use the provider's defaults.
///
/// # Basic Usage
///
/// ```rust
/// use multi_llm::RequestConfig;
///
/// let config = RequestConfig {
/// temperature: Some(0.7),
/// max_tokens: Some(1000),
/// ..Default::default()
/// };
/// ```
///
/// # With Tools
///
/// ```rust
/// use multi_llm::{RequestConfig, Tool, ToolChoice};
///
/// let weather_tool = Tool {
/// name: "get_weather".to_string(),
/// description: "Get weather for a city".to_string(),
/// parameters: serde_json::json!({"type": "object", "properties": {}}),
/// };
///
/// let config = RequestConfig {
/// tools: vec![weather_tool],
/// tool_choice: Some(ToolChoice::Auto),
/// ..Default::default()
/// };
/// ```
///
/// # Sampling Parameters
///
/// | Parameter | Range | Effect |
/// |-----------|-------|--------|
/// | `temperature` | 0.0-2.0 | Randomness (0=deterministic, 2=very random) |
/// | `top_p` | 0.0-1.0 | Nucleus sampling threshold |
/// | `top_k` | 1+ | Limit vocab to top K tokens |
/// | `presence_penalty` | -2.0-2.0 | Discourage repetition |
/// Schema specification for structured JSON output.
///
/// When you need the LLM to return data in a specific JSON format, define
/// a `ResponseFormat` with a JSON Schema. The model will attempt to conform
/// its output to this schema.
///
/// # Example
///
/// ```rust
/// use multi_llm::ResponseFormat;
///
/// let format = ResponseFormat {
/// name: "person_info".to_string(),
/// schema: serde_json::json!({
/// "type": "object",
/// "properties": {
/// "name": {"type": "string"},
/// "age": {"type": "integer"},
/// "email": {"type": "string", "format": "email"}
/// },
/// "required": ["name", "age"]
/// }),
/// };
/// ```
/// Token usage statistics for an LLM request.
///
/// Tracks how many tokens were consumed by the prompt and completion,
/// useful for cost estimation and monitoring context window usage.
///
/// # Cost Estimation
///
/// Most providers charge per token. Multiply token counts by the provider's
/// per-token rate to estimate costs:
///
/// ```rust
/// use multi_llm::TokenUsage;
///
/// let usage = TokenUsage {
/// prompt_tokens: 1000,
/// completion_tokens: 500,
/// total_tokens: 1500,
/// };
///
/// // Example: OpenAI GPT-4 pricing (illustrative)
/// let prompt_cost = usage.prompt_tokens as f64 * 0.00003;
/// let completion_cost = usage.completion_tokens as f64 * 0.00006;
/// let total_cost = prompt_cost + completion_cost;
/// ```
/// Response from an LLM operation.
///
/// Contains the model's output along with metadata about the request.
/// Check `tool_calls` first - if non-empty, the model wants to call functions
/// rather than provide a final response.
///
/// # Basic Response
///
/// ```rust,no_run
/// use multi_llm::Response;
///
/// # fn example(response: Response) {
/// // Standard text response
/// println!("Response: {}", response.content);
///
/// // Check token usage
/// if let Some(usage) = &response.usage {
/// println!("Used {} tokens", usage.total_tokens);
/// }
/// # }
/// ```
///
/// # Tool Calling Response
///
/// ```rust,no_run
/// use multi_llm::Response;
///
/// # fn example(response: Response) {
/// // Check if model wants to call tools
/// if !response.tool_calls.is_empty() {
/// for call in &response.tool_calls {
/// println!("Tool: {} with args: {}", call.name, call.arguments);
/// // Execute tool and return result...
/// }
/// }
/// # }
/// ```
///
/// # Structured Response
///
/// ```rust,no_run
/// use multi_llm::Response;
///
/// # fn example(response: Response) {
/// // When using execute_structured_llm
/// if let Some(json) = &response.structured_response {
/// let name = json["name"].as_str().unwrap_or("unknown");
/// println!("Extracted name: {}", name);
/// }
/// # }
/// ```
///
/// # Note on Trait Implementations
///
/// This type intentionally omits `Serialize`, `Deserialize`, and `PartialEq`:
/// - `structured_response` contains arbitrary `serde_json::Value` that may not round-trip cleanly
/// - `raw_body` is provider-specific debug data not meant for serialization
/// - Equality comparison on JSON values can be surprising (object key ordering, number precision)
///
/// If you need to serialize responses, extract the specific fields you need.
/// Business event generated during LLM operations.
///
/// Wraps a [`BusinessEvent`] with its scope for routing to the appropriate
/// storage backend. Only available with the `events` feature enabled.
///
/// # Feature Flag
///
/// This type requires the `events` feature:
/// ```toml
/// [dependencies]
/// multi-llm = { version = "...", features = ["events"] }
/// ```
/// State for a tool calling round in multi-turn conversations.
///
/// When using tool calling, conversations often have multiple rounds:
/// 1. User asks a question
/// 2. Assistant requests tool calls
/// 3. Tools execute and return results
/// 4. Assistant uses results to form final response
///
/// `ToolCallingRound` captures the assistant's tool requests and the corresponding
/// results, allowing providers to properly format multi-turn tool conversations.
///
/// # Example Flow
///
/// ```rust,no_run
/// use multi_llm::{ToolCallingRound, ToolResult, UnifiedMessage};
///
/// // After receiving tool calls from the LLM
/// # fn example(assistant_response: UnifiedMessage, tool_results: Vec<ToolResult>) {
/// let round = ToolCallingRound {
/// assistant_message: assistant_response, // The message with tool calls
/// tool_results, // Results from executing those calls
/// };
///
/// // Pass to execute_llm for the next turn
/// // provider.execute_llm(request, Some(round), config).await?;
/// # }
/// ```
/// Trait implemented by all LLM providers.
///
/// This is the core abstraction that makes multi-llm work. All providers
/// (OpenAI, Anthropic, Ollama, LM Studio) implement this trait, allowing
/// you to switch providers without changing your application code.
///
/// # Usage
///
/// You typically don't implement this trait yourself. Instead, use
/// [`UnifiedLLMClient`](crate::UnifiedLLMClient) which wraps all providers:
///
/// ```rust,no_run
/// use multi_llm::{unwrap_response, UnifiedLLMClient, LLMConfig, UnifiedMessage, UnifiedLLMRequest, LlmProvider};
///
/// # async fn example() -> anyhow::Result<()> {
/// let config = LLMConfig::from_env()?;
/// let client = UnifiedLLMClient::from_config(config)?;
///
/// let request = UnifiedLLMRequest::new(vec![
/// UnifiedMessage::user("Hello!")
/// ]);
///
/// let response = unwrap_response!(client.execute_llm(request, None, None).await?);
/// println!("Response: {}", response.content);
/// # Ok(())
/// # }
/// ```
///
/// # Return Types
///
/// Return types depend on the `events` feature:
/// - **Without `events`**: Returns `Result<Response>`
/// - **With `events`**: Returns `Result<(Response, Vec<LLMBusinessEvent>)>`
///
/// # Implementing Custom Providers
///
/// If you need to implement a custom provider:
///
/// ```rust,ignore
/// use multi_llm::{LlmProvider, UnifiedLLMRequest, RequestConfig, Response, ToolCallingRound};
/// use async_trait::async_trait;
///
/// struct MyProvider { /* ... */ }
///
/// #[async_trait]
/// impl LlmProvider for MyProvider {
/// async fn execute_llm(
/// &self,
/// request: UnifiedLLMRequest,
/// current_tool_round: Option<ToolCallingRound>,
/// config: Option<RequestConfig>,
/// ) -> multi_llm::provider::Result<Response> {
/// // Convert request to your API format
/// // Make API call
/// // Convert response to Response
/// todo!()
/// }
///
/// async fn execute_structured_llm(
/// &self,
/// request: UnifiedLLMRequest,
/// current_tool_round: Option<ToolCallingRound>,
/// schema: serde_json::Value,
/// config: Option<RequestConfig>,
/// ) -> multi_llm::provider::Result<Response> {
/// // Similar to execute_llm but with JSON schema enforcement
/// todo!()
/// }
///
/// fn provider_name(&self) -> &'static str {
/// "my_provider"
/// }
/// }
/// ```
/// Type aliases for backward compatibility
pub type LLMRequestConfig = RequestConfig;
pub type LLMResponseFormat = ResponseFormat;
pub type LLMTokenUsage = TokenUsage;