api_openai_compatible 0.2.0

Shared OpenAI wire-protocol HTTP layer for OpenAI-compatible APIs.
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
//! Wire types for `OpenAI` chat completion requests and responses.
//!
//! These types serialise to and deserialise from the JSON shapes described in
//! the `OpenAI` chat completions API reference. Absent optional fields are
//! omitted from the wire representation (`skip_serializing_if = "Option::is_none"`).

mod private
{
  use serde::{ Serialize, Deserialize };
  use former::Former;

  // ------------------------------------------------------------------ //
  //  Role
  // ------------------------------------------------------------------ //

  /// Role of a participant in a chat conversation.
  ///
  /// Serialises to lowercase strings as required by the `OpenAI` wire protocol
  /// (e.g. `Role::User` → `"user"`).
  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Eq ) ]
  #[ serde( rename_all = "lowercase" ) ]
  pub enum Role
  {
    /// System-level instructions provided before the conversation begins.
    System,

    /// Message from the human user.
    User,

    /// Response generated by the AI assistant.
    Assistant,

    /// Result message from a tool/function call execution.
    Tool,
  }

  // ------------------------------------------------------------------ //
  //  ToolCall / FunctionCall
  // ------------------------------------------------------------------ //

  /// A function invocation requested by the assistant.
  ///
  /// When the model decides to call a tool it includes one or more `ToolCall`
  /// objects in the assistant message's `tool_calls` field.
  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
  pub struct ToolCall
  {
    /// Unique identifier for this invocation (used to correlate tool results).
    pub id : String,

    /// Always `"function"` for function-calling tools.
    #[ serde( rename = "type" ) ]
    pub tool_type : String,

    /// Name and serialised arguments for the function to invoke.
    pub function : FunctionCall,
  }

  /// Name and arguments for a specific function invocation.
  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
  pub struct FunctionCall
  {
    /// Registered function name.
    pub name : String,

    /// JSON-encoded arguments string (not a `Value` — must be re-parsed by caller).
    pub arguments : String,
  }

  // ------------------------------------------------------------------ //
  //  Message
  // ------------------------------------------------------------------ //

  /// A single message in a chat conversation.
  ///
  /// All fields except `role` are optional; `None` fields are omitted from
  /// serialised JSON (`skip_serializing_if = "Option::is_none"`).
  ///
  /// # Examples
  ///
  /// ```
  /// # #[ cfg( feature = "enabled" ) ]
  /// # {
  /// use api_openai_compatible::Message;
  ///
  /// let sys  = Message::system( "You are a helpful assistant." );
  /// let user = Message::user( "What is 2 + 2?" );
  /// # }
  /// ```
  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
  pub struct Message
  {
    /// Who sent this message.
    pub role : Role,

    /// Text content of the message.
    #[ serde( skip_serializing_if = "Option::is_none" ) ]
    pub content : Option< String >,

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

    /// ID of the `ToolCall` this message responds to (tool role only).
    #[ serde( skip_serializing_if = "Option::is_none" ) ]
    pub tool_call_id : Option< String >,
  }

  impl Message
  {
    /// Creates a system-role message.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[ cfg( feature = "enabled" ) ]
    /// # {
    /// use api_openai_compatible::Message;
    ///
    /// let msg = Message::system( "You are a helpful coding assistant." );
    /// # }
    /// ```
    #[ inline ]
    pub fn system( content : impl Into< String > ) -> Self
    {
      Self
      {
        role         : Role::System,
        content      : Some( content.into() ),
        tool_calls   : None,
        tool_call_id : None,
      }
    }

    /// Creates a user-role message.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[ cfg( feature = "enabled" ) ]
    /// # {
    /// use api_openai_compatible::Message;
    ///
    /// let msg = Message::user( "Explain monads." );
    /// # }
    /// ```
    #[ inline ]
    pub fn user( content : impl Into< String > ) -> Self
    {
      Self
      {
        role         : Role::User,
        content      : Some( content.into() ),
        tool_calls   : None,
        tool_call_id : None,
      }
    }

    /// Creates an assistant-role message.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[ cfg( feature = "enabled" ) ]
    /// # {
    /// use api_openai_compatible::Message;
    ///
    /// let msg = Message::assistant( "A monad is a design pattern…" );
    /// # }
    /// ```
    #[ inline ]
    pub fn assistant( content : impl Into< String > ) -> Self
    {
      Self
      {
        role         : Role::Assistant,
        content      : Some( content.into() ),
        tool_calls   : None,
        tool_call_id : None,
      }
    }

    /// Creates a tool-result message.
    ///
    /// # Arguments
    ///
    /// * `tool_call_id` — Must match the `id` of the `ToolCall` being answered.
    /// * `content` — Serialised result from the tool execution.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[ cfg( feature = "enabled" ) ]
    /// # {
    /// use api_openai_compatible::Message;
    ///
    /// let msg = Message::tool( "call_abc123", r#"{"temperature":22}"# );
    /// # }
    /// ```
    #[ inline ]
    pub fn tool
    (
      tool_call_id : impl Into< String >,
      content      : impl Into< String >,
    )
    -> Self
    {
      Self
      {
        role         : Role::Tool,
        content      : Some( content.into() ),
        tool_calls   : None,
        tool_call_id : Some( tool_call_id.into() ),
      }
    }
  }

  // ------------------------------------------------------------------ //
  //  Tool / Function definitions
  // ------------------------------------------------------------------ //

  /// A function tool definition passed in the `tools` array of a request.
  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Former ) ]
  pub struct Tool
  {
    /// Always `"function"` for function-type tools.
    #[ serde( rename = "type" ) ]
    pub tool_type : String,

    /// Function specification.
    pub function : Function,
  }

  impl Tool
  {
    /// Convenience constructor for a function-type tool.
    ///
    /// # Examples
    ///
    /// ```
    /// # #[ cfg( feature = "enabled" ) ]
    /// # {
    /// use api_openai_compatible::Tool;
    ///
    /// let tool = Tool::function(
    ///   "get_weather",
    ///   "Get current weather for a location",
    ///   serde_json::json!({ "type": "object", "properties": {} }),
    /// );
    /// # }
    /// ```
    #[ inline ]
    pub fn function
    (
      name        : impl Into< String >,
      description : impl Into< String >,
      parameters  : serde_json::Value,
    )
    -> Self
    {
      Self
      {
        tool_type : "function".to_string(),
        function  : Function
        {
          name        : name.into(),
          description : description.into(),
          parameters,
        },
      }
    }
  }

  /// Function specification (name, description, JSON Schema parameters).
  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Former ) ]
  pub struct Function
  {
    /// Registered function name.
    pub name : String,

    /// Human-readable description used by the model to decide when to call.
    pub description : String,

    /// JSON Schema describing the expected parameters.
    pub parameters : serde_json::Value,
  }

  // ------------------------------------------------------------------ //
  //  Usage
  // ------------------------------------------------------------------ //

  /// Token usage statistics returned in every completion response.
  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Eq ) ]
  pub struct Usage
  {
    /// Number of tokens in the prompt (input).
    pub prompt_tokens : u32,

    /// Number of tokens in the completion (output).
    pub completion_tokens : u32,

    /// Total tokens consumed (`prompt_tokens + completion_tokens`).
    pub total_tokens : u32,
  }

  // ------------------------------------------------------------------ //
  //  ChatCompletionRequest
  // ------------------------------------------------------------------ //

  /// Request body for the `POST chat/completions` endpoint.
  ///
  /// Uses the `Former` builder pattern for ergonomic construction.
  ///
  /// # Examples
  ///
  /// ```
  /// # #[ cfg( feature = "enabled" ) ]
  /// # {
  /// use api_openai_compatible::{ ChatCompletionRequest, Message };
  ///
  /// let req = ChatCompletionRequest::former()
  ///   .model( "gpt-4o".to_string() )
  ///   .messages( vec![ Message::user( "Hello!" ) ] )
  ///   .max_tokens( 100_u32 )
  ///   .form();
  /// # }
  /// ```
  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq, Former ) ]
  pub struct ChatCompletionRequest
  {
    /// Model identifier (e.g. `"gpt-4o"`, `"grok-2-1212"`).
    pub model : String,

    /// Ordered list of conversation messages.
    pub messages : Vec< Message >,

    /// Sampling temperature in `[0.0, 2.0]`. Higher = more random.
    #[ serde( skip_serializing_if = "Option::is_none" ) ]
    pub temperature : Option< f32 >,

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

    /// Nucleus sampling threshold in `[0.0, 1.0]`.
    #[ serde( skip_serializing_if = "Option::is_none" ) ]
    pub top_p : Option< f32 >,

    /// Frequency penalty in `[0.0, 2.0]` (reduces token repetition).
    #[ serde( skip_serializing_if = "Option::is_none" ) ]
    pub frequency_penalty : Option< f32 >,

    /// Presence penalty in `[0.0, 2.0]` (encourages topic diversity).
    #[ serde( skip_serializing_if = "Option::is_none" ) ]
    pub presence_penalty : Option< f32 >,

    /// When `true`, the response is streamed as Server-Sent Events.
    #[ serde( skip_serializing_if = "Option::is_none" ) ]
    pub stream : Option< bool >,

    /// Tool definitions available for function calling.
    #[ serde( skip_serializing_if = "Option::is_none" ) ]
    pub tools : Option< Vec< Tool > >,
  }

  // ------------------------------------------------------------------ //
  //  ChatCompletionResponse / Choice
  // ------------------------------------------------------------------ //

  /// Response body from the `POST chat/completions` endpoint.
  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
  pub struct ChatCompletionResponse
  {
    /// Opaque completion identifier (e.g. `"chatcmpl-abc123"`).
    pub id : String,

    /// Object type — always `"chat.completion"`.
    pub object : String,

    /// Unix timestamp of when the completion was created.
    pub created : u64,

    /// Model that generated this completion.
    pub model : String,

    /// One or more completion choices (`n` defaults to 1).
    pub choices : Vec< Choice >,

    /// Token usage statistics for billing.
    pub usage : Usage,
  }

  /// One completion alternative within a `ChatCompletionResponse`.
  #[ derive( Debug, Serialize, Deserialize, Clone, PartialEq ) ]
  pub struct Choice
  {
    /// Zero-based index of this choice.
    pub index : u32,

    /// The generated message.
    pub message : Message,

    /// Reason the generation stopped (`"stop"`, `"length"`, `"tool_calls"`).
    pub finish_reason : Option< String >,
  }
}

crate::mod_interface!
{
  exposed use
  {
    Role,
    ToolCall,
    FunctionCall,
    Message,
    Tool,
    Function,
    Usage,
    ChatCompletionRequest,
    ChatCompletionResponse,
    Choice,
  };
}