1use super::openai;
14use crate::client::{
15 self, BearerAuth, Capabilities, Capable, DebugExt, Nothing, Provider, ProviderBuilder,
16 ProviderClient,
17};
18use crate::http_client::{self, HttpClientExt};
19use crate::message::MessageError;
20use crate::providers::openai::send_compatible_streaming_request;
21use crate::streaming::StreamingCompletionResponse;
22use crate::{
23 OneOrMany,
24 completion::{self, CompletionError, CompletionRequest},
25 json_utils, message,
26};
27use serde::{Deserialize, Serialize};
28use tracing::{Instrument, enabled, info_span};
29
30const GALADRIEL_API_BASE_URL: &str = "https://api.galadriel.com/v1/verified";
34
35#[derive(Debug, Default, Clone)]
36pub struct GaladrielExt {
37 fine_tune_api_key: Option<String>,
38}
39
40#[derive(Debug, Default, Clone)]
41pub struct GaladrielBuilder {
42 fine_tune_api_key: Option<String>,
43}
44
45type GaladrielApiKey = BearerAuth;
46
47impl Provider for GaladrielExt {
48 type Builder = GaladrielBuilder;
49
50 const VERIFY_PATH: &'static str = "";
52}
53
54impl<H> Capabilities<H> for GaladrielExt {
55 type Completion = Capable<CompletionModel<H>>;
56 type Embeddings = Nothing;
57 type Transcription = Nothing;
58 type ModelListing = Nothing;
59 #[cfg(feature = "image")]
60 type ImageGeneration = Nothing;
61 #[cfg(feature = "audio")]
62 type AudioGeneration = Nothing;
63}
64
65impl DebugExt for GaladrielExt {
66 fn fields(&self) -> impl Iterator<Item = (&'static str, &dyn std::fmt::Debug)> {
67 std::iter::once((
68 "fine_tune_api_key",
69 (&self.fine_tune_api_key as &dyn std::fmt::Debug),
70 ))
71 }
72}
73
74impl ProviderBuilder for GaladrielBuilder {
75 type Extension<H>
76 = GaladrielExt
77 where
78 H: HttpClientExt;
79 type ApiKey = GaladrielApiKey;
80
81 const BASE_URL: &'static str = GALADRIEL_API_BASE_URL;
82
83 fn build<H>(
84 builder: &crate::client::ClientBuilder<Self, Self::ApiKey, H>,
85 ) -> http_client::Result<Self::Extension<H>>
86 where
87 H: HttpClientExt,
88 {
89 let GaladrielBuilder { fine_tune_api_key } = builder.ext().clone();
90
91 Ok(GaladrielExt { fine_tune_api_key })
92 }
93}
94
95pub type Client<H = reqwest::Client> = client::Client<GaladrielExt, H>;
96pub type ClientBuilder<H = reqwest::Client> =
97 client::ClientBuilder<GaladrielBuilder, GaladrielApiKey, H>;
98
99impl<T> ClientBuilder<T> {
100 pub fn fine_tune_api_key<S>(mut self, fine_tune_api_key: S) -> Self
101 where
102 S: AsRef<str>,
103 {
104 *self.ext_mut() = GaladrielBuilder {
105 fine_tune_api_key: Some(fine_tune_api_key.as_ref().into()),
106 };
107
108 self
109 }
110}
111
112impl ProviderClient for Client {
113 type Input = (String, Option<String>);
114
115 fn from_env() -> Self {
119 let api_key = std::env::var("GALADRIEL_API_KEY").expect("GALADRIEL_API_KEY not set");
120 let fine_tune_api_key = std::env::var("GALADRIEL_FINE_TUNE_API_KEY").ok();
121
122 let mut builder = Self::builder().api_key(api_key);
123
124 if let Some(fine_tune_api_key) = fine_tune_api_key.as_deref() {
125 builder = builder.fine_tune_api_key(fine_tune_api_key);
126 }
127
128 builder.build().unwrap()
129 }
130
131 fn from_val((api_key, fine_tune_api_key): Self::Input) -> Self {
132 let mut builder = Self::builder().api_key(api_key);
133
134 if let Some(fine_tune_key) = fine_tune_api_key {
135 builder = builder.fine_tune_api_key(fine_tune_key)
136 }
137
138 builder.build().unwrap()
139 }
140}
141
142#[derive(Debug, Deserialize)]
143struct ApiErrorResponse {
144 message: String,
145}
146
147#[derive(Debug, Deserialize)]
148#[serde(untagged)]
149enum ApiResponse<T> {
150 Ok(T),
151 Err(ApiErrorResponse),
152}
153
154#[derive(Clone, Debug, Deserialize, Serialize)]
155pub struct Usage {
156 pub prompt_tokens: usize,
157 pub total_tokens: usize,
158}
159
160impl std::fmt::Display for Usage {
161 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
162 write!(
163 f,
164 "Prompt tokens: {} Total tokens: {}",
165 self.prompt_tokens, self.total_tokens
166 )
167 }
168}
169
170pub const O1_PREVIEW: &str = "o1-preview";
176pub const O1_PREVIEW_2024_09_12: &str = "o1-preview-2024-09-12";
178pub const O1_MINI: &str = "o1-mini";
180pub const O1_MINI_2024_09_12: &str = "o1-mini-2024-09-12";
182pub const GPT_4O: &str = "gpt-4o";
184pub const GPT_4O_2024_05_13: &str = "gpt-4o-2024-05-13";
186pub const GPT_4_TURBO: &str = "gpt-4-turbo";
188pub const GPT_4_TURBO_2024_04_09: &str = "gpt-4-turbo-2024-04-09";
190pub const GPT_4_TURBO_PREVIEW: &str = "gpt-4-turbo-preview";
192pub const GPT_4_0125_PREVIEW: &str = "gpt-4-0125-preview";
194pub const GPT_4_1106_PREVIEW: &str = "gpt-4-1106-preview";
196pub const GPT_4_VISION_PREVIEW: &str = "gpt-4-vision-preview";
198pub const GPT_4_1106_VISION_PREVIEW: &str = "gpt-4-1106-vision-preview";
200pub const GPT_4: &str = "gpt-4";
202pub const GPT_4_0613: &str = "gpt-4-0613";
204pub const GPT_4_32K: &str = "gpt-4-32k";
206pub const GPT_4_32K_0613: &str = "gpt-4-32k-0613";
208pub const GPT_35_TURBO: &str = "gpt-3.5-turbo";
210pub const GPT_35_TURBO_0125: &str = "gpt-3.5-turbo-0125";
212pub const GPT_35_TURBO_1106: &str = "gpt-3.5-turbo-1106";
214pub const GPT_35_TURBO_INSTRUCT: &str = "gpt-3.5-turbo-instruct";
216
217#[derive(Debug, Deserialize, Serialize)]
218pub struct CompletionResponse {
219 pub id: String,
220 pub object: String,
221 pub created: u64,
222 pub model: String,
223 pub system_fingerprint: Option<String>,
224 pub choices: Vec<Choice>,
225 pub usage: Option<Usage>,
226}
227
228impl From<ApiErrorResponse> for CompletionError {
229 fn from(err: ApiErrorResponse) -> Self {
230 CompletionError::ProviderError(err.message)
231 }
232}
233
234impl TryFrom<CompletionResponse> for completion::CompletionResponse<CompletionResponse> {
235 type Error = CompletionError;
236
237 fn try_from(response: CompletionResponse) -> Result<Self, Self::Error> {
238 let Choice { message, .. } = response.choices.first().ok_or_else(|| {
239 CompletionError::ResponseError("Response contained no choices".to_owned())
240 })?;
241
242 let mut content = message
243 .content
244 .as_ref()
245 .map(|c| vec![completion::AssistantContent::text(c)])
246 .unwrap_or_default();
247
248 content.extend(message.tool_calls.iter().map(|call| {
249 completion::AssistantContent::tool_call(
250 &call.function.name,
251 &call.function.name,
252 call.function.arguments.clone(),
253 )
254 }));
255
256 let choice = OneOrMany::many(content).map_err(|_| {
257 CompletionError::ResponseError(
258 "Response contained no message or tool call (empty)".to_owned(),
259 )
260 })?;
261 let usage = response
262 .usage
263 .as_ref()
264 .map(|usage| completion::Usage {
265 input_tokens: usage.prompt_tokens as u64,
266 output_tokens: (usage.total_tokens - usage.prompt_tokens) as u64,
267 total_tokens: usage.total_tokens as u64,
268 cached_input_tokens: 0,
269 })
270 .unwrap_or_default();
271
272 Ok(completion::CompletionResponse {
273 choice,
274 usage,
275 raw_response: response,
276 message_id: None,
277 })
278 }
279}
280
281#[derive(Debug, Deserialize, Serialize)]
282pub struct Choice {
283 pub index: usize,
284 pub message: Message,
285 pub logprobs: Option<serde_json::Value>,
286 pub finish_reason: String,
287}
288
289#[derive(Debug, Serialize, Deserialize)]
290pub struct Message {
291 pub role: String,
292 pub content: Option<String>,
293 #[serde(default, deserialize_with = "json_utils::null_or_vec")]
294 pub tool_calls: Vec<openai::ToolCall>,
295}
296
297impl Message {
298 fn system(preamble: &str) -> Self {
299 Self {
300 role: "system".to_string(),
301 content: Some(preamble.to_string()),
302 tool_calls: Vec::new(),
303 }
304 }
305}
306
307impl TryFrom<Message> for message::Message {
308 type Error = message::MessageError;
309
310 fn try_from(message: Message) -> Result<Self, Self::Error> {
311 let tool_calls: Vec<message::ToolCall> = message
312 .tool_calls
313 .into_iter()
314 .map(|tool_call| tool_call.into())
315 .collect();
316
317 match message.role.as_str() {
318 "user" => Ok(Self::User {
319 content: OneOrMany::one(
320 message
321 .content
322 .map(|content| message::UserContent::text(&content))
323 .ok_or_else(|| {
324 message::MessageError::ConversionError("Empty user message".to_string())
325 })?,
326 ),
327 }),
328 "assistant" => Ok(Self::Assistant {
329 id: None,
330 content: OneOrMany::many(
331 tool_calls
332 .into_iter()
333 .map(message::AssistantContent::ToolCall)
334 .chain(
335 message
336 .content
337 .map(|content| message::AssistantContent::text(&content))
338 .into_iter(),
339 ),
340 )
341 .map_err(|_| {
342 message::MessageError::ConversionError("Empty assistant message".to_string())
343 })?,
344 }),
345 _ => Err(message::MessageError::ConversionError(format!(
346 "Unknown role: {}",
347 message.role
348 ))),
349 }
350 }
351}
352
353impl TryFrom<message::Message> for Message {
354 type Error = message::MessageError;
355
356 fn try_from(message: message::Message) -> Result<Self, Self::Error> {
357 match message {
358 message::Message::User { content } => Ok(Self {
359 role: "user".to_string(),
360 content: content.iter().find_map(|c| match c {
361 message::UserContent::Text(text) => Some(text.text.clone()),
362 _ => None,
363 }),
364 tool_calls: vec![],
365 }),
366 message::Message::Assistant { content, .. } => {
367 let mut text_content: Option<String> = None;
368 let mut tool_calls = vec![];
369
370 for c in content.iter() {
371 match c {
372 message::AssistantContent::Text(text) => {
373 text_content = Some(
374 text_content
375 .map(|mut existing| {
376 existing.push('\n');
377 existing.push_str(&text.text);
378 existing
379 })
380 .unwrap_or_else(|| text.text.clone()),
381 );
382 }
383 message::AssistantContent::ToolCall(tool_call) => {
384 tool_calls.push(tool_call.clone().into());
385 }
386 message::AssistantContent::Reasoning(_) => {
387 return Err(MessageError::ConversionError(
388 "Galadriel currently doesn't support reasoning.".into(),
389 ));
390 }
391 message::AssistantContent::Image(_) => {
392 return Err(MessageError::ConversionError(
393 "Galadriel currently doesn't support images.".into(),
394 ));
395 }
396 }
397 }
398
399 Ok(Self {
400 role: "assistant".to_string(),
401 content: text_content,
402 tool_calls,
403 })
404 }
405 }
406 }
407}
408
409#[derive(Clone, Debug, Deserialize, Serialize)]
410pub struct ToolDefinition {
411 pub r#type: String,
412 pub function: completion::ToolDefinition,
413}
414
415impl From<completion::ToolDefinition> for ToolDefinition {
416 fn from(tool: completion::ToolDefinition) -> Self {
417 Self {
418 r#type: "function".into(),
419 function: tool,
420 }
421 }
422}
423
424#[derive(Debug, Deserialize)]
425pub struct Function {
426 pub name: String,
427 pub arguments: String,
428}
429
430#[derive(Debug, Serialize, Deserialize)]
431pub(super) struct GaladrielCompletionRequest {
432 model: String,
433 pub messages: Vec<Message>,
434 #[serde(skip_serializing_if = "Option::is_none")]
435 temperature: Option<f64>,
436 #[serde(skip_serializing_if = "Vec::is_empty")]
437 tools: Vec<ToolDefinition>,
438 #[serde(skip_serializing_if = "Option::is_none")]
439 tool_choice: Option<crate::providers::openai::completion::ToolChoice>,
440 #[serde(flatten, skip_serializing_if = "Option::is_none")]
441 pub additional_params: Option<serde_json::Value>,
442}
443
444impl TryFrom<(&str, CompletionRequest)> for GaladrielCompletionRequest {
445 type Error = CompletionError;
446
447 fn try_from((model, req): (&str, CompletionRequest)) -> Result<Self, Self::Error> {
448 if req.output_schema.is_some() {
449 tracing::warn!("Structured outputs currently not supported for Galadriel");
450 }
451 let model = req.model.clone().unwrap_or_else(|| model.to_string());
452 let mut partial_history = vec![];
454 if let Some(docs) = req.normalized_documents() {
455 partial_history.push(docs);
456 }
457 partial_history.extend(req.chat_history);
458
459 let mut full_history: Vec<Message> = match &req.preamble {
461 Some(preamble) => vec![Message::system(preamble)],
462 None => vec![],
463 };
464
465 full_history.extend(
467 partial_history
468 .into_iter()
469 .map(message::Message::try_into)
470 .collect::<Result<Vec<Message>, _>>()?,
471 );
472
473 let tool_choice = req
474 .tool_choice
475 .clone()
476 .map(crate::providers::openai::completion::ToolChoice::try_from)
477 .transpose()?;
478
479 Ok(Self {
480 model: model.to_string(),
481 messages: full_history,
482 temperature: req.temperature,
483 tools: req
484 .tools
485 .clone()
486 .into_iter()
487 .map(ToolDefinition::from)
488 .collect::<Vec<_>>(),
489 tool_choice,
490 additional_params: req.additional_params,
491 })
492 }
493}
494
495#[derive(Clone)]
496pub struct CompletionModel<T = reqwest::Client> {
497 client: Client<T>,
498 pub model: String,
500}
501
502impl<T> CompletionModel<T>
503where
504 T: HttpClientExt,
505{
506 pub fn new(client: Client<T>, model: impl Into<String>) -> Self {
507 Self {
508 client,
509 model: model.into(),
510 }
511 }
512
513 pub fn with_model(client: Client<T>, model: &str) -> Self {
514 Self {
515 client,
516 model: model.into(),
517 }
518 }
519}
520
521impl<T> completion::CompletionModel for CompletionModel<T>
522where
523 T: HttpClientExt + Clone + Default + std::fmt::Debug + Send + 'static,
524{
525 type Response = CompletionResponse;
526 type StreamingResponse = openai::StreamingCompletionResponse;
527
528 type Client = Client<T>;
529
530 fn make(client: &Self::Client, model: impl Into<String>) -> Self {
531 Self::new(client.clone(), model.into())
532 }
533
534 async fn completion(
535 &self,
536 completion_request: CompletionRequest,
537 ) -> Result<completion::CompletionResponse<CompletionResponse>, CompletionError> {
538 let span = if tracing::Span::current().is_disabled() {
539 info_span!(
540 target: "rig::completions",
541 "chat",
542 gen_ai.operation.name = "chat",
543 gen_ai.provider.name = "galadriel",
544 gen_ai.request.model = self.model,
545 gen_ai.system_instructions = tracing::field::Empty,
546 gen_ai.response.id = tracing::field::Empty,
547 gen_ai.response.model = tracing::field::Empty,
548 gen_ai.usage.output_tokens = tracing::field::Empty,
549 gen_ai.usage.input_tokens = tracing::field::Empty,
550 )
551 } else {
552 tracing::Span::current()
553 };
554
555 span.record("gen_ai.system_instructions", &completion_request.preamble);
556
557 let request =
558 GaladrielCompletionRequest::try_from((self.model.as_ref(), completion_request))?;
559
560 if enabled!(tracing::Level::TRACE) {
561 tracing::trace!(target: "rig::completions",
562 "Galadriel completion request: {}",
563 serde_json::to_string_pretty(&request)?
564 );
565 }
566
567 let body = serde_json::to_vec(&request)?;
568
569 let req = self
570 .client
571 .post("/chat/completions")?
572 .body(body)
573 .map_err(http_client::Error::from)?;
574
575 async move {
576 let response = self.client.send(req).await?;
577
578 if response.status().is_success() {
579 let t = http_client::text(response).await?;
580
581 if enabled!(tracing::Level::TRACE) {
582 tracing::trace!(target: "rig::completions",
583 "Galadriel completion response: {}",
584 serde_json::to_string_pretty(&t)?
585 );
586 }
587
588 match serde_json::from_str::<ApiResponse<CompletionResponse>>(&t)? {
589 ApiResponse::Ok(response) => {
590 let span = tracing::Span::current();
591 span.record("gen_ai.response.id", response.id.clone());
592 span.record("gen_ai.response.model_name", response.model.clone());
593 if let Some(ref usage) = response.usage {
594 span.record("gen_ai.usage.input_tokens", usage.prompt_tokens);
595 span.record(
596 "gen_ai.usage.output_tokens",
597 usage.total_tokens - usage.prompt_tokens,
598 );
599 }
600 response.try_into()
601 }
602 ApiResponse::Err(err) => Err(CompletionError::ProviderError(err.message)),
603 }
604 } else {
605 let text = http_client::text(response).await?;
606
607 Err(CompletionError::ProviderError(text))
608 }
609 }
610 .instrument(span)
611 .await
612 }
613
614 async fn stream(
615 &self,
616 completion_request: CompletionRequest,
617 ) -> Result<StreamingCompletionResponse<Self::StreamingResponse>, CompletionError> {
618 let preamble = completion_request.preamble.clone();
619 let mut request =
620 GaladrielCompletionRequest::try_from((self.model.as_ref(), completion_request))?;
621
622 let params = json_utils::merge(
623 request.additional_params.unwrap_or(serde_json::json!({})),
624 serde_json::json!({"stream": true, "stream_options": {"include_usage": true} }),
625 );
626
627 request.additional_params = Some(params);
628
629 let body = serde_json::to_vec(&request)?;
630
631 let req = self
632 .client
633 .post("/chat/completions")?
634 .body(body)
635 .map_err(http_client::Error::from)?;
636
637 let span = if tracing::Span::current().is_disabled() {
638 info_span!(
639 target: "rig::completions",
640 "chat_streaming",
641 gen_ai.operation.name = "chat_streaming",
642 gen_ai.provider.name = "galadriel",
643 gen_ai.request.model = self.model,
644 gen_ai.system_instructions = preamble,
645 gen_ai.response.id = tracing::field::Empty,
646 gen_ai.response.model = tracing::field::Empty,
647 gen_ai.usage.output_tokens = tracing::field::Empty,
648 gen_ai.usage.input_tokens = tracing::field::Empty,
649 gen_ai.input.messages = serde_json::to_string(&request.messages)?,
650 gen_ai.output.messages = tracing::field::Empty,
651 )
652 } else {
653 tracing::Span::current()
654 };
655
656 send_compatible_streaming_request(self.client.clone(), req)
657 .instrument(span)
658 .await
659 }
660}
661#[cfg(test)]
662mod tests {
663 #[test]
664 fn test_client_initialization() {
665 let _client =
666 crate::providers::galadriel::Client::new("dummy-key").expect("Client::new() failed");
667 let _client_from_builder = crate::providers::galadriel::Client::builder()
668 .api_key("dummy-key")
669 .build()
670 .expect("Client::builder() failed");
671 }
672}