api_huggingface 0.4.1

HuggingFace's API for accessing large language models (LLMs) and embeddings.
Documentation
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
//! Shared components for `HuggingFace` inference API.

use serde::{ Deserialize, Serialize };
use super::input::InferenceParameters;
use super::output::InferenceOutput;

/// Chat message for the new Router API
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct ChatMessage
{
  /// Role of the message sender (user, assistant, system, tool)
  pub role : String,

  /// Content of the message
  pub content : String,

  /// Tool calls made by the assistant (only for role="assistant")
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub tool_calls : Option< Vec< ToolCall > >,

  /// ID of the tool call this message is responding to (only for role="tool")
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub tool_call_id : Option< String >,
}

/// A tool call made by the model
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct ToolCall
{
  /// Unique identifier for this tool call
  pub id : String,

  /// Type of tool (always "function" for now)
  #[ serde( rename = "type" ) ]
  pub tool_type : String,

  /// Function call details
  pub function : FunctionCall,
}

/// Function call details
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct FunctionCall
{
  /// Name of the function to call
  pub name : String,

  /// JSON string of function arguments
  pub arguments : String,
}

/// Chat completions request (new Router API format)
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct ChatCompletionRequest
{
  /// Array of messages in the conversation
  pub messages : Vec< ChatMessage >,

  /// Model identifier
  pub model : String,

  /// Temperature for randomness (0.0 - 2.0)
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub temperature : Option< f32 >,

  /// Maximum tokens to generate
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub max_tokens : Option< u32 >,

  /// Top-p nucleus sampling
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub top_p : Option< f32 >,

  /// Whether to stream the response
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub stream : Option< bool >,

  /// List of tools the model may call
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub tools : Option< Vec< ToolDefinition > >,

  /// Controls which (if any) tool is called by the model
  /// - "auto": model decides whether to call tools (default)
  /// - "none": model will not call any tools
  /// - "required": model must call one or more tools
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub tool_choice : Option< String >,
}

/// Tool definition for function calling
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct ToolDefinition
{
  /// Type of tool (always "function")
  #[ serde( rename = "type" ) ]
  pub tool_type : String,

  /// Function definition
  pub function : crate::components::tools::Tool,
}

/// Chat completions response (new Router API format)
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct ChatCompletionResponse
{
  /// Unique identifier for the completion
  pub id : String,

  /// Object type (always "chat.completion")
  pub object : String,

  /// Unix timestamp of creation
  pub created : i64,

  /// Model used for completion
  pub model : String,

  /// Array of completion choices
  pub choices : Vec< ChatChoice >,

  /// Token usage information
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub usage : Option< ChatUsage >,

  /// System fingerprint (optional, ignored)
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub system_fingerprint : Option< String >,

  /// Service tier (optional, ignored)
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub service_tier : Option< String >,

  /// Usage breakdown (optional, ignored)
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub usage_breakdown : Option< serde_json::Value >,

  /// Provider-specific data (optional, ignored)
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub x_groq : Option< serde_json::Value >,
}

/// Individual completion choice
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct ChatChoice
{
  /// Index of this choice
  pub index : u32,

  /// The generated message
  pub message : ChatMessage,

  /// Reason for completion finishing
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub finish_reason : Option< String >,

  /// Logprobs (optional, ignored)
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub logprobs : Option< serde_json::Value >,
}

/// Token usage statistics
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct ChatUsage
{
  /// Tokens in the prompt
  pub prompt_tokens : u32,

  /// Tokens in the completion
  pub completion_tokens : u32,

  /// Total tokens used
  pub total_tokens : u32,

  /// Queue time (optional, provider-specific)
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub queue_time : Option< f64 >,

  /// Prompt processing time (optional, provider-specific)
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub prompt_time : Option< f64 >,

  /// Completion generation time (optional, provider-specific)
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub completion_time : Option< f64 >,

  /// Total time (optional, provider-specific)
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub total_time : Option< f64 >,
}

/// Request for text generation inference
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct InferenceRequest
{
  /// Input text or prompt
  pub inputs : String,
  
  /// Inference parameters
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub parameters : Option< InferenceParameters >,
  
  /// Options for the request
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub options : Option< InferenceOptions >,
}

impl InferenceRequest
{
  /// Create a new inference request
  #[ inline ]
  #[ must_use ]
  pub fn new( inputs : impl Into< String > ) -> Self
  {
  Self
  {
      inputs : inputs.into(),
      parameters : None,
      options : None,
  }
  }
  
  /// Set parameters
  #[ inline ]
  #[ must_use ]
  pub fn with_parameters( mut self, parameters : InferenceParameters ) -> Self
  {
  self.parameters = Some( parameters );
  self
  }
  
  /// Set options
  #[ inline ]
  #[ must_use ]
  pub fn with_options( mut self, options : InferenceOptions ) -> Self
  {
  self.options = Some( options );
  self
  }
}

/// Batch inference request for multiple inputs
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct BatchInferenceRequest
{
  /// Input texts or prompts
  pub inputs : Vec< String >,
  
  /// Inference parameters
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub parameters : Option< InferenceParameters >,
  
  /// Options for the request
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub options : Option< InferenceOptions >,
}

impl BatchInferenceRequest
{
  /// Create a new batch inference request
  #[ inline ]
  #[ must_use ]
  pub fn new( inputs : Vec< String > ) -> Self
  {
  Self
  {
      inputs,
      parameters : None,
      options : None,
  }
  }
  
  /// Set parameters
  #[ inline ]
  #[ must_use ]
  pub fn with_parameters( mut self, parameters : InferenceParameters ) -> Self
  {
  self.parameters = Some( parameters );
  self
  }
}

/// Options for inference requests
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct InferenceOptions
{
  /// Use cache
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub use_cache : Option< bool >,
  
  /// Wait for model to load
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub wait_for_model : Option< bool >,
  
  /// Use GPU if available
  #[ serde( skip_serializing_if = "Option::is_none" ) ]
  pub use_gpu : Option< bool >,
}

impl Default for InferenceOptions
{
  #[ inline ]
  fn default() -> Self
  {
  Self::recommended()
  }
}

impl InferenceOptions
{
  /// Create new inference options with HuggingFace-recommended values.
  ///
  /// # Governing Principle Compliance
  ///
  /// This provides HuggingFace-recommended options without making them implicit defaults.
  /// Developers must explicitly choose to use these recommended values.
  #[ inline ]
  #[ must_use ]
  pub fn recommended() -> Self
  {
  Self
  {
      use_cache : Some( true ),      // Enable caching for better performance
      wait_for_model : Some( true ), // Wait for model loading if needed
      use_gpu : Some( true ),        // Use GPU acceleration when available
  }
  }

  /// Create new inference options (convenience wrapper)
  ///
  /// # Compatibility
  ///
  /// This method provides backward compatibility by delegating to `recommended()`.
  /// For explicit control, use `recommended()`, `empty()`, or `conservative()`.
  #[ inline ]
  #[ must_use ]
  pub fn new() -> Self
  {
  Self::recommended()
  }

  /// Create empty inference options requiring explicit configuration
  ///
  /// # Governing Principle Compliance
  ///
  /// This requires explicit configuration for all options, providing full transparency
  /// and control over inference behavior.
  #[ inline ]
  #[ must_use ]
  pub fn empty() -> Self
  {
  Self
  {
      use_cache : None,
      wait_for_model : None,
      use_gpu : None,
  }
  }

  /// Create conservative options for production environments
  #[ inline ]
  #[ must_use ]
  pub fn conservative() -> Self
  {
  Self
  {
      use_cache : Some( false ),     // Disable caching for consistent results
      wait_for_model : Some( false ), // Fail fast if model not available
      use_gpu : Some( false ),       // Use CPU for predictable performance
  }
  }
  
  /// Set `use_cache` option
  #[ inline ]
  #[ must_use ]
  pub fn with_use_cache( mut self, use_cache : bool ) -> Self
  {
  self.use_cache = Some( use_cache );
  self
  }
  
  /// Set `wait_for_model` option
  #[ inline ]
  #[ must_use ]
  pub fn with_wait_for_model( mut self, wait_for_model : bool ) -> Self
  {
  self.wait_for_model = Some( wait_for_model );
  self
  }
  
  /// Set `use_gpu` option
  #[ inline ]
  #[ must_use ]
  pub fn with_use_gpu( mut self, use_gpu : bool ) -> Self
  {
  self.use_gpu = Some( use_gpu );
  self
  }
}

/// Response wrapper for inference operations
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
#[ serde( untagged ) ]
pub enum InferenceResponse
{
  /// Single inference output
  Single( InferenceOutput ),
  /// Multiple inference outputs
  Batch( Vec< InferenceOutput > ),
  /// Summarization response
  Summarization( Vec< SummarizationOutput > ),
}

/// Summarization model response
#[ derive( Debug, Clone, Serialize, Deserialize ) ]
pub struct SummarizationOutput
{
  /// Summarized text
  pub summary_text : String,
}

impl InferenceResponse
{
  /// Extract text content from any inference response type
  /// 
  /// Returns the first available text from the response, regardless of type
  #[ inline ]
  #[ must_use ]
  pub fn extract_text( &self ) -> Option< String >
  {
  match self
  {
      Self::Single( output ) => Some( output.generated_text.clone() ),
      Self::Batch( outputs ) => outputs.first().map( | o | o.generated_text.clone() ),
      Self::Summarization( summaries ) => summaries.first().map( | s | s.summary_text.clone() ),
  }
  }
  
  /// Extract text content with fallback message
  /// 
  /// Returns the text content or a default fallback message if no content is available
  #[ inline ]
  #[ must_use ]
  pub fn extract_text_or_default( &self, default : &str ) -> String
  {
  self.extract_text().unwrap_or_else( || default.to_string() )
  }
}