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
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
//! Diagnostics module for debugging and development tools
//!
//! This module provides diagnostic utilities to help developers debug API requests
//! and responses. It defines the `AsCurl` trait to enable generating executable
//! curl commands from request objects.
//!
//! # Features
//!
//! - **curl Command Generation**: Convert API requests to executable curl commands
//! - **Pretty-formatted Output**: Readable curl commands with proper JSON formatting
//! - **Authorization Header Support**: Uses Bearer token authentication for `HuggingFace` Router API
//! - **Error Resilience**: Robust handling of serialization failures
//!
//! # Usage Examples
//!
//! ## Basic Usage
//!
//! ```no_run
//! use api_huggingface::
//! {
//!   components::inference_shared::{ ChatCompletionRequest, ChatMessage },
//!   diagnostics::AsCurl,
//! };
//!
//! let request = ChatCompletionRequest
//! {
//!   messages : vec![
//!     ChatMessage
//!     {
//!       role : "user".to_string(),
//!       content : "What is 2+2?".to_string(),
//!       tool_calls : None,
//!       tool_call_id : None,
//!     }
//!   ],
//!   model : "moonshotai/Kimi-K2-Instruct-0905:groq".to_string(),
//!   temperature : Some( 0.7 ),
//!   max_tokens : Some( 100 ),
//!   top_p : Some( 0.9 ),
//!   stream : Some( false ),
//!   tools : None,
//!   tool_choice : None,
//! };
//!
//! let curl_command = request.as_curl();
//! println!( "Debug curl command:\n{}", curl_command );
//! ```
//!
//! ## Pretty-formatted Output
//!
//! ```no_run
//! use api_huggingface::
//! {
//!   components::inference_shared::{ ChatCompletionRequest, ChatMessage },
//!   diagnostics::{ AsCurl, CurlOptions },
//! };
//!
//! let request = ChatCompletionRequest
//! {
//!   messages : vec![ ChatMessage
//!   {
//!     role : "user".to_string(),
//!     content : "Hello".to_string(),
//!     tool_calls : None,
//!     tool_call_id : None,
//!   } ],
//!   model : "moonshotai/Kimi-K2-Instruct-0905:groq".to_string(),
//!   temperature : Some( 0.7 ),
//!   max_tokens : Some( 100 ),
//!   top_p : Some( 0.9 ),
//!   stream : Some( false ),
//!   tools : None,
//!   tool_choice : None,
//! };
//!
//! let curl_command = request.as_curl_with_options( &CurlOptions::pretty() );
//! println!( "Readable curl command:\n{}", curl_command );
//! ```
//!
//! ## Adding API Key
//!
//! The generated curl commands include a placeholder for the API key:
//!
//! ```bash
//! curl -X POST "https://router.huggingface.co/v1/chat/completions" \
//!   -H "Authorization : Bearer YOUR_API_KEY_HERE" \
//!   -H "Content-Type : application/json" \
//!   -d '{...}'
//! ```

mod private
{

/// Trait for converting API request objects into executable curl commands
///
/// This trait allows you to convert API request objects into executable curl
/// commands for debugging purposes.
pub trait AsCurl
{
  /// Convert the request object to an executable curl command string
  ///
  /// This method generates a basic curl command with compact JSON formatting.
  /// For more control over the output format, use `as_curl_with_options`.
  fn as_curl( &self ) -> String;

  /// Convert the request object to a curl command with custom formatting options
  ///
  /// # Arguments
  ///
  /// * `options` - Configuration for curl command generation
  ///
  /// # Examples
  ///
  /// ```no_run
  /// use api_huggingface::
  /// {
  ///   components::inference_shared::{ ChatCompletionRequest, ChatMessage },
  ///   diagnostics::{ AsCurl, CurlOptions },
  /// };
  ///
  /// let request = ChatCompletionRequest
  /// {
  ///   messages : vec![ ChatMessage
  ///   {
  ///     role : "user".to_string(),
  ///     content : "Hello".to_string(),
  ///     tool_calls : None,
  ///     tool_call_id : None,
  ///   } ],
  ///   model : "moonshotai/Kimi-K2-Instruct-0905:groq".to_string(),
  ///   temperature : Some( 0.7 ),
  ///   max_tokens : Some( 100 ),
  ///   top_p : Some( 0.9 ),
  ///   stream : Some( false ),
  ///   tools : None,
  ///   tool_choice : None,
  /// };
  ///
  /// let curl_command = request.as_curl_with_options( &CurlOptions::pretty() );
  /// ```
  fn as_curl_with_options( &self, options : &CurlOptions ) -> String;
}

use crate::components::inference_shared::ChatCompletionRequest;

/// Configuration options for curl command generation
///
/// This struct provides fine-grained control over how curl commands are formatted
/// and what additional information is included.
#[ derive( Debug, Clone ) ]
pub struct CurlOptions
{
  /// Whether to format JSON with pretty printing (indentation and line breaks)
  pub pretty_json : bool,
  /// Whether to include the auth header placeholder
  pub include_auth_header : bool,
  /// Whether to use multi-line formatting for better readability
  pub multiline_format : bool,
  /// Custom API key to include (if provided, overrides placeholder)
  pub api_key : Option< String >,
}

impl CurlOptions
{
  /// Create default curl options (compact format)
  #[ inline ]
  #[ must_use ]
  pub fn new() -> Self
  {
  Self
  {
      pretty_json : false,
      include_auth_header : true,
      multiline_format : false,
      api_key : None,
  }
  }

  /// Create options for pretty-formatted output
  ///
  /// This generates curl commands that are more readable, with:
  /// - Pretty-formatted JSON with indentation
  /// - Multi-line formatting with line continuations
  /// - Authorization header placeholder included
  #[ inline ]
  #[ must_use ]
  pub fn pretty() -> Self
  {
  Self
  {
      pretty_json : true,
      include_auth_header : true,
      multiline_format : true,
      api_key : None,
  }
  }

  /// Create options with a specific API key
  ///
  /// # Arguments
  ///
  /// * `api_key` - The API key to include in the curl command
  ///
  /// # Security Note
  ///
  /// Be careful when using this method in production code, as it will
  /// include your actual API key in the curl command string.
  #[ inline ]
  pub fn with_api_key< S : Into< String > >( api_key : S ) -> Self
  {
  Self
  {
      pretty_json : false,
      include_auth_header : true,
      multiline_format : false,
      api_key : Some( api_key.into() ),
  }
  }

  /// Enable pretty JSON formatting
  #[ inline ]
  #[ must_use ]
  pub fn pretty_json( mut self ) -> Self
  {
  self.pretty_json = true;
  self
  }

  /// Enable multi-line formatting
  #[ inline ]
  #[ must_use ]
  pub fn multiline( mut self ) -> Self
  {
  self.multiline_format = true;
  self
  }
}

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

/// Helper functions for generating curl commands
mod curl_helpers
{
  use super::*;

  /// Generate a curl command for a given URL and JSON body
  pub fn generate_curl_command(
  url : &str,
  json_body : &str,
  options : &CurlOptions,
  ) -> String
  {
  let formatted_json = if options.pretty_json
  {
      // Pretty-format the JSON if requested
      match serde_json::from_str::< serde_json::Value >( json_body )
      {
  Ok( value ) => serde_json::to_string_pretty( &value )
          .unwrap_or_else( |_| json_body.to_string() ),
  Err( _ ) => json_body.to_string(),
      }
  }
  else
  {
      json_body.to_string()
  };

  // Generate authorization header
  let auth_header = if let Some( ref api_key ) = options.api_key
  {
      format!( "Authorization : Bearer {api_key}" )
  }
  else if options.include_auth_header
  {
      "Authorization : Bearer YOUR_API_KEY_HERE".to_string()
  }
  else
  {
      String::new()
  };

  if options.multiline_format
  {
      // Multi-line format for better readability
      let json_escaped = formatted_json.replace( '"', "\\\"" );

      if options.include_auth_header || options.api_key.is_some()
      {
  format!(
          "curl -X POST \\\n  \"{url}\" \\\n  -H \"{auth_header}\" \\\n  -H \"Content-Type : application/json\" \\\n  -d \"{json_escaped}\""
  )
      }
      else
      {
  format!(
          "curl -X POST \\\n  \"{url}\" \\\n  -H \"Content-Type : application/json\" \\\n  -d \"{json_escaped}\""
  )
      }
  }
  else
  {
      // Single-line format
      let json_escaped = formatted_json.replace( '\'', "'\"'\"'" );

      if options.include_auth_header || options.api_key.is_some()
      {
  format!(
          "curl -X POST \"{url}\" -H \"{auth_header}\" -H \"Content-Type : application/json\" -d '{json_escaped}'"
  )
      }
      else
      {
  format!(
          "curl -X POST \"{url}\" -H \"Content-Type : application/json\" -d '{json_escaped}'"
  )
      }
  }
  }

  /// Handle JSON serialization with error recovery
  pub fn safe_json_serialize< T : serde::Serialize >( value : &T ) -> String
  {
  serde_json::to_string( value ).unwrap_or_else( |err| {
      format!( "{{\"error\": \"Failed to serialize request : {err}\"}}" )
  })
  }
}

impl AsCurl for ChatCompletionRequest
{
  #[ inline ]
  fn as_curl( &self ) -> String
  {
  self.as_curl_with_options( &CurlOptions::default() )
  }

  #[ inline ]
  fn as_curl_with_options( &self, options : &CurlOptions ) -> String
  {
  let url = "https://router.huggingface.co/v1/chat/completions";
  let json_body = curl_helpers::safe_json_serialize( self );
  curl_helpers::generate_curl_command( url, &json_body, options )
  }
}

/// Convenience functions for common debugging scenarios
///
/// These functions provide quick access to common curl generation patterns
/// without needing to construct request objects manually.
pub mod debug_helpers
{
  use super::*;
  use crate::components::inference_shared::ChatMessage;

  /// Generate a curl command for a simple chat completion request
  ///
  /// # Arguments
  ///
  /// * `message` - The message text to send
  /// * `options` - Optional curl formatting options
  ///
  /// # Examples
  ///
  /// ```no_run
  /// use api_huggingface::diagnostics::debug_helpers;
  ///
  /// let curl_cmd = debug_helpers::simple_chat_curl(
  ///   "What is the capital of France?",
  ///   None
  /// );
  /// println!( "{}", curl_cmd );
  /// ```
  #[ inline ]
  #[ must_use ]
  pub fn simple_chat_curl( message : &str, options : Option< &CurlOptions > ) -> String
  {
  let request = ChatCompletionRequest
  {
      messages : vec![ ChatMessage
      {
  role : "user".to_string(),
  content : message.to_string(),
  tool_calls : None,
  tool_call_id : None,
      } ],
      model : "moonshotai/Kimi-K2-Instruct-0905:groq".to_string(),
      temperature : Some( 0.7 ),
      max_tokens : Some( 150 ),
      top_p : Some( 0.9 ),
      stream : Some( false ),
      tools : None,
      tool_choice : None,
  };

  match options
  {
      Some( opts ) => request.as_curl_with_options( opts ),
      None => request.as_curl(),
  }
  }

  /// Generate a curl command for a system + user message conversation
  ///
  /// # Arguments
  ///
  /// * `system_message` - The system prompt
  /// * `user_message` - The user message
  /// * `options` - Optional curl formatting options
  ///
  /// # Examples
  ///
  /// ```no_run
  /// use api_huggingface::diagnostics::{ debug_helpers, CurlOptions };
  ///
  /// let curl_cmd = debug_helpers::chat_with_system_curl(
  ///   "You are a helpful assistant",
  ///   "Hello",
  ///   Some( &CurlOptions::pretty() )
  /// );
  /// println!( "{}", curl_cmd );
  /// ```
  #[ inline ]
  #[ must_use ]
  pub fn chat_with_system_curl(
  system_message : &str,
  user_message : &str,
  options : Option< &CurlOptions >
  ) -> String
  {
  let request = ChatCompletionRequest
  {
      messages : vec![
  ChatMessage
  {
          role : "system".to_string(),
          content : system_message.to_string(),
          tool_calls : None,
          tool_call_id : None,
  },
  ChatMessage
  {
          role : "user".to_string(),
          content : user_message.to_string(),
          tool_calls : None,
          tool_call_id : None,
  }
      ],
      model : "moonshotai/Kimi-K2-Instruct-0905:groq".to_string(),
      temperature : Some( 0.7 ),
      max_tokens : Some( 150 ),
      top_p : Some( 0.9 ),
      stream : Some( false ),
      tools : None,
      tool_choice : None,
  };

  match options
  {
      Some( opts ) => request.as_curl_with_options( opts ),
      None => request.as_curl(),
  }
  }
}
} // end mod private

crate::mod_interface!
{
  exposed use private::
  {
  AsCurl,
  CurlOptions,
  debug_helpers,
  };
}