Skip to main content

rig/providers/cohere/
completion.rs

1use crate::{
2    OneOrMany,
3    completion::{self, CompletionError, GetTokenUsage},
4    http_client::{self, HttpClientExt},
5    json_utils,
6    message::{self, Reasoning, ToolChoice},
7    telemetry::SpanCombinator,
8};
9use std::collections::HashMap;
10
11use super::client::Client;
12use crate::completion::CompletionRequest;
13use crate::providers::cohere::streaming::StreamingCompletionResponse;
14use serde::{Deserialize, Serialize};
15use tracing::{Instrument, Level, enabled, info_span};
16
17#[derive(Debug, Deserialize, Serialize)]
18pub struct CompletionResponse {
19    pub id: String,
20    pub finish_reason: FinishReason,
21    message: Message,
22    #[serde(default)]
23    pub usage: Option<Usage>,
24}
25
26impl CompletionResponse {
27    /// Return that parts of the response for assistant messages w/o dealing with the other variants
28    pub fn message(&self) -> (Vec<AssistantContent>, Vec<Citation>, Vec<ToolCall>) {
29        let Message::Assistant {
30            content,
31            citations,
32            tool_calls,
33            ..
34        } = self.message.clone()
35        else {
36            unreachable!("Completion responses will only return an assistant message")
37        };
38
39        (content, citations, tool_calls)
40    }
41}
42
43impl crate::telemetry::ProviderResponseExt for CompletionResponse {
44    type OutputMessage = Message;
45    type Usage = Usage;
46
47    fn get_response_id(&self) -> Option<String> {
48        Some(self.id.clone())
49    }
50
51    fn get_response_model_name(&self) -> Option<String> {
52        None
53    }
54
55    fn get_output_messages(&self) -> Vec<Self::OutputMessage> {
56        vec![self.message.clone()]
57    }
58
59    fn get_text_response(&self) -> Option<String> {
60        let Message::Assistant { ref content, .. } = self.message else {
61            return None;
62        };
63
64        let res = content
65            .iter()
66            .filter_map(|x| {
67                if let AssistantContent::Text { text } = x {
68                    Some(text.to_string())
69                } else {
70                    None
71                }
72            })
73            .collect::<Vec<String>>()
74            .join("\n");
75
76        if res.is_empty() { None } else { Some(res) }
77    }
78
79    fn get_usage(&self) -> Option<Self::Usage> {
80        self.usage.clone()
81    }
82}
83
84#[derive(Debug, Deserialize, PartialEq, Eq, Clone, Serialize)]
85#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
86pub enum FinishReason {
87    MaxTokens,
88    StopSequence,
89    Complete,
90    Error,
91    ToolCall,
92}
93
94#[derive(Debug, Deserialize, Clone, Serialize)]
95pub struct Usage {
96    #[serde(default)]
97    pub billed_units: Option<BilledUnits>,
98    #[serde(default)]
99    pub tokens: Option<Tokens>,
100}
101
102impl GetTokenUsage for Usage {
103    fn token_usage(&self) -> Option<crate::completion::Usage> {
104        let mut usage = crate::completion::Usage::new();
105
106        if let Some(ref billed_units) = self.billed_units {
107            usage.input_tokens = billed_units.input_tokens.unwrap_or_default() as u64;
108            usage.output_tokens = billed_units.output_tokens.unwrap_or_default() as u64;
109            usage.total_tokens = usage.input_tokens + usage.output_tokens;
110        }
111
112        Some(usage)
113    }
114}
115
116#[derive(Debug, Deserialize, Clone, Serialize)]
117pub struct BilledUnits {
118    #[serde(default)]
119    pub output_tokens: Option<f64>,
120    #[serde(default)]
121    pub classifications: Option<f64>,
122    #[serde(default)]
123    pub search_units: Option<f64>,
124    #[serde(default)]
125    pub input_tokens: Option<f64>,
126}
127
128#[derive(Debug, Deserialize, Clone, Serialize)]
129pub struct Tokens {
130    #[serde(default)]
131    pub input_tokens: Option<f64>,
132    #[serde(default)]
133    pub output_tokens: Option<f64>,
134}
135
136impl TryFrom<CompletionResponse> for completion::CompletionResponse<CompletionResponse> {
137    type Error = CompletionError;
138
139    fn try_from(response: CompletionResponse) -> Result<Self, Self::Error> {
140        let (content, _, tool_calls) = response.message();
141
142        let model_response = if !tool_calls.is_empty() {
143            OneOrMany::many(
144                tool_calls
145                    .into_iter()
146                    .filter_map(|tool_call| {
147                        let ToolCallFunction { name, arguments } = tool_call.function?;
148                        let id = tool_call.id.unwrap_or_else(|| name.clone());
149
150                        Some(completion::AssistantContent::tool_call(id, name, arguments))
151                    })
152                    .collect::<Vec<_>>(),
153            )
154            .expect("We have atleast 1 tool call in this if block")
155        } else {
156            OneOrMany::many(content.into_iter().map(|content| match content {
157                AssistantContent::Text { text } => completion::AssistantContent::text(text),
158                AssistantContent::Thinking { thinking } => {
159                    completion::AssistantContent::Reasoning(Reasoning::new(&thinking))
160                }
161            }))
162            .map_err(|_| {
163                CompletionError::ResponseError(
164                    "Response contained no message or tool call (empty)".to_owned(),
165                )
166            })?
167        };
168
169        let usage = response
170            .usage
171            .as_ref()
172            .and_then(|usage| usage.tokens.as_ref())
173            .map(|tokens| {
174                let input_tokens = tokens.input_tokens.unwrap_or(0.0);
175                let output_tokens = tokens.output_tokens.unwrap_or(0.0);
176
177                completion::Usage {
178                    input_tokens: input_tokens as u64,
179                    output_tokens: output_tokens as u64,
180                    total_tokens: (input_tokens + output_tokens) as u64,
181                    cached_input_tokens: 0,
182                }
183            })
184            .unwrap_or_default();
185
186        Ok(completion::CompletionResponse {
187            choice: OneOrMany::many(model_response).expect("There is atleast one content"),
188            usage,
189            raw_response: response,
190            message_id: None,
191        })
192    }
193}
194
195#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
196pub struct Document {
197    pub id: String,
198    pub data: HashMap<String, serde_json::Value>,
199}
200
201impl From<completion::Document> for Document {
202    fn from(document: completion::Document) -> Self {
203        let mut data: HashMap<String, serde_json::Value> = HashMap::new();
204
205        // We use `.into()` here explicitly since the `document.additional_props` type will likely
206        //  evolve into `serde_json::Value` in the future.
207        document
208            .additional_props
209            .into_iter()
210            .for_each(|(key, value)| {
211                data.insert(key, value.into());
212            });
213
214        data.insert("text".to_string(), document.text.into());
215
216        Self {
217            id: document.id,
218            data,
219        }
220    }
221}
222
223#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
224pub struct ToolCall {
225    #[serde(default)]
226    pub id: Option<String>,
227    #[serde(default)]
228    pub r#type: Option<ToolType>,
229    #[serde(default)]
230    pub function: Option<ToolCallFunction>,
231}
232
233#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
234pub struct ToolCallFunction {
235    pub name: String,
236    #[serde(with = "json_utils::stringified_json")]
237    pub arguments: serde_json::Value,
238}
239
240#[derive(Clone, Default, Debug, Deserialize, Serialize, PartialEq, Eq)]
241#[serde(rename_all = "lowercase")]
242pub enum ToolType {
243    #[default]
244    Function,
245}
246
247#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
248pub struct Tool {
249    pub r#type: ToolType,
250    pub function: Function,
251}
252
253#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
254pub struct Function {
255    pub name: String,
256    #[serde(default)]
257    pub description: Option<String>,
258    pub parameters: serde_json::Value,
259}
260
261impl From<completion::ToolDefinition> for Tool {
262    fn from(tool: completion::ToolDefinition) -> Self {
263        Self {
264            r#type: ToolType::default(),
265            function: Function {
266                name: tool.name,
267                description: Some(tool.description),
268                parameters: tool.parameters,
269            },
270        }
271    }
272}
273
274#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
275#[serde(tag = "role", rename_all = "lowercase")]
276pub enum Message {
277    User {
278        content: OneOrMany<UserContent>,
279    },
280
281    Assistant {
282        #[serde(default)]
283        content: Vec<AssistantContent>,
284        #[serde(default)]
285        citations: Vec<Citation>,
286        #[serde(default)]
287        tool_calls: Vec<ToolCall>,
288        #[serde(default)]
289        tool_plan: Option<String>,
290    },
291
292    Tool {
293        content: OneOrMany<ToolResultContent>,
294        tool_call_id: String,
295    },
296
297    System {
298        content: String,
299    },
300}
301
302#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
303#[serde(tag = "type", rename_all = "lowercase")]
304pub enum UserContent {
305    Text { text: String },
306    ImageUrl { image_url: ImageUrl },
307}
308
309#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
310#[serde(tag = "type", rename_all = "lowercase")]
311pub enum AssistantContent {
312    Text { text: String },
313    Thinking { thinking: String },
314}
315
316#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
317pub struct ImageUrl {
318    pub url: String,
319}
320
321#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
322pub enum ToolResultContent {
323    Text { text: String },
324    Document { document: Document },
325}
326
327#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
328pub struct Citation {
329    #[serde(default)]
330    pub start: Option<u32>,
331    #[serde(default)]
332    pub end: Option<u32>,
333    #[serde(default)]
334    pub text: Option<String>,
335    #[serde(rename = "type")]
336    pub citation_type: Option<CitationType>,
337    #[serde(default)]
338    pub sources: Vec<Source>,
339}
340
341#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
342#[serde(tag = "type", rename_all = "lowercase")]
343pub enum Source {
344    Document {
345        id: Option<String>,
346        document: Option<serde_json::Map<String, serde_json::Value>>,
347    },
348    Tool {
349        id: Option<String>,
350        tool_output: Option<serde_json::Map<String, serde_json::Value>>,
351    },
352}
353
354#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
355#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
356pub enum CitationType {
357    TextContent,
358    Plan,
359}
360
361impl TryFrom<message::Message> for Vec<Message> {
362    type Error = message::MessageError;
363
364    fn try_from(message: message::Message) -> Result<Self, Self::Error> {
365        Ok(match message {
366            message::Message::User { content } => content
367                .into_iter()
368                .map(|content| match content {
369                    message::UserContent::Text(message::Text { text }) => Ok(Message::User {
370                        content: OneOrMany::one(UserContent::Text { text }),
371                    }),
372                    message::UserContent::ToolResult(message::ToolResult {
373                        id, content, ..
374                    }) => Ok(Message::Tool {
375                        tool_call_id: id,
376                        content: content.try_map(|content| match content {
377                            message::ToolResultContent::Text(text) => {
378                                Ok(ToolResultContent::Text { text: text.text })
379                            }
380                            _ => Err(message::MessageError::ConversionError(
381                                "Only text tool result content is supported by Cohere".to_owned(),
382                            )),
383                        })?,
384                    }),
385                    _ => Err(message::MessageError::ConversionError(
386                        "Only text content is supported by Cohere".to_owned(),
387                    )),
388                })
389                .collect::<Result<Vec<_>, _>>()?,
390            message::Message::System { content } => {
391                vec![Message::System { content }]
392            }
393            message::Message::Assistant { content, .. } => {
394                let mut text_content = vec![];
395                let mut tool_calls = vec![];
396
397                for content in content.into_iter() {
398                    match content {
399                        message::AssistantContent::Text(message::Text { text }) => {
400                            text_content.push(AssistantContent::Text { text });
401                        }
402                        message::AssistantContent::ToolCall(message::ToolCall {
403                            id,
404                            function:
405                                message::ToolFunction {
406                                    name, arguments, ..
407                                },
408                            ..
409                        }) => {
410                            tool_calls.push(ToolCall {
411                                id: Some(id),
412                                r#type: Some(ToolType::Function),
413                                function: Some(ToolCallFunction {
414                                    name,
415                                    arguments: serde_json::to_value(arguments).unwrap_or_default(),
416                                }),
417                            });
418                        }
419                        message::AssistantContent::Reasoning(reasoning) => {
420                            let thinking = reasoning.display_text();
421                            text_content.push(AssistantContent::Thinking { thinking });
422                        }
423                        message::AssistantContent::Image(_) => {
424                            return Err(message::MessageError::ConversionError(
425                                "Cohere currently doesn't support images.".to_owned(),
426                            ));
427                        }
428                    }
429                }
430
431                vec![Message::Assistant {
432                    content: text_content,
433                    citations: vec![],
434                    tool_calls,
435                    tool_plan: None,
436                }]
437            }
438        })
439    }
440}
441
442impl TryFrom<Message> for message::Message {
443    type Error = message::MessageError;
444
445    fn try_from(message: Message) -> Result<Self, Self::Error> {
446        match message {
447            Message::User { content } => Ok(message::Message::User {
448                content: content.map(|content| match content {
449                    UserContent::Text { text } => {
450                        message::UserContent::Text(message::Text { text })
451                    }
452                    UserContent::ImageUrl { image_url } => {
453                        message::UserContent::image_url(image_url.url, None, None)
454                    }
455                }),
456            }),
457            Message::Assistant {
458                content,
459                tool_calls,
460                ..
461            } => {
462                let mut content = content
463                    .into_iter()
464                    .map(|content| match content {
465                        AssistantContent::Text { text } => message::AssistantContent::text(text),
466                        AssistantContent::Thinking { thinking } => {
467                            message::AssistantContent::Reasoning(Reasoning::new(&thinking))
468                        }
469                    })
470                    .collect::<Vec<_>>();
471
472                content.extend(tool_calls.into_iter().filter_map(|tool_call| {
473                    let ToolCallFunction { name, arguments } = tool_call.function?;
474
475                    Some(message::AssistantContent::tool_call(
476                        tool_call.id.unwrap_or_else(|| name.clone()),
477                        name,
478                        arguments,
479                    ))
480                }));
481
482                let content = OneOrMany::many(content).map_err(|_| {
483                    message::MessageError::ConversionError(
484                        "Expected either text content or tool calls".to_string(),
485                    )
486                })?;
487
488                Ok(message::Message::Assistant { id: None, content })
489            }
490            Message::Tool {
491                content,
492                tool_call_id,
493            } => {
494                let content = content.try_map(|content| {
495                    Ok(match content {
496                        ToolResultContent::Text { text } => message::ToolResultContent::text(text),
497                        ToolResultContent::Document { document } => {
498                            message::ToolResultContent::text(
499                                serde_json::to_string(&document.data).map_err(|e| {
500                                    message::MessageError::ConversionError(
501                                        format!("Failed to convert tool result document content into text: {e}"),
502                                    )
503                                })?,
504                            )
505                        }
506                    })
507                })?;
508
509                Ok(message::Message::User {
510                    content: OneOrMany::one(message::UserContent::tool_result(
511                        tool_call_id,
512                        content,
513                    )),
514                })
515            }
516            Message::System { content } => Ok(message::Message::user(content)),
517        }
518    }
519}
520
521#[derive(Clone)]
522pub struct CompletionModel<T = reqwest::Client> {
523    pub(crate) client: Client<T>,
524    pub model: String,
525}
526
527#[derive(Debug, Serialize, Deserialize)]
528pub(super) struct CohereCompletionRequest {
529    model: String,
530    pub messages: Vec<Message>,
531    documents: Vec<crate::completion::Document>,
532    #[serde(skip_serializing_if = "Option::is_none")]
533    temperature: Option<f64>,
534    #[serde(skip_serializing_if = "Vec::is_empty")]
535    tools: Vec<Tool>,
536    #[serde(skip_serializing_if = "Option::is_none")]
537    tool_choice: Option<ToolChoice>,
538    #[serde(flatten, skip_serializing_if = "Option::is_none")]
539    pub additional_params: Option<serde_json::Value>,
540}
541
542impl TryFrom<(&str, CompletionRequest)> for CohereCompletionRequest {
543    type Error = CompletionError;
544
545    fn try_from((model, req): (&str, CompletionRequest)) -> Result<Self, Self::Error> {
546        if req.output_schema.is_some() {
547            tracing::warn!("Structured outputs currently not supported for Cohere");
548        }
549
550        let model = req.model.clone().unwrap_or_else(|| model.to_string());
551        let mut partial_history = vec![];
552        if let Some(docs) = req.normalized_documents() {
553            partial_history.push(docs);
554        }
555        partial_history.extend(req.chat_history);
556
557        let mut full_history: Vec<Message> = req.preamble.map_or_else(Vec::new, |preamble| {
558            vec![Message::System { content: preamble }]
559        });
560
561        full_history.extend(
562            partial_history
563                .into_iter()
564                .map(message::Message::try_into)
565                .collect::<Result<Vec<Vec<Message>>, _>>()?
566                .into_iter()
567                .flatten()
568                .collect::<Vec<_>>(),
569        );
570
571        let tool_choice = if let Some(tool_choice) = req.tool_choice {
572            if !matches!(tool_choice, ToolChoice::Auto) {
573                Some(tool_choice)
574            } else {
575                return Err(CompletionError::RequestError(
576                    "\"auto\" is not an allowed tool_choice value in the Cohere API".into(),
577                ));
578            }
579        } else {
580            None
581        };
582
583        Ok(Self {
584            model: model.to_string(),
585            messages: full_history,
586            documents: req.documents,
587            temperature: req.temperature,
588            tools: req.tools.into_iter().map(Tool::from).collect::<Vec<_>>(),
589            tool_choice,
590            additional_params: req.additional_params,
591        })
592    }
593}
594
595impl<T> CompletionModel<T>
596where
597    T: HttpClientExt,
598{
599    pub fn new(client: Client<T>, model: impl Into<String>) -> Self {
600        Self {
601            client,
602            model: model.into(),
603        }
604    }
605}
606
607impl<T> completion::CompletionModel for CompletionModel<T>
608where
609    T: HttpClientExt + Clone + 'static,
610{
611    type Response = CompletionResponse;
612    type StreamingResponse = StreamingCompletionResponse;
613    type Client = Client<T>;
614
615    fn make(client: &Self::Client, model: impl Into<String>) -> Self {
616        Self::new(client.clone(), model.into())
617    }
618
619    async fn completion(
620        &self,
621        completion_request: completion::CompletionRequest,
622    ) -> Result<completion::CompletionResponse<CompletionResponse>, CompletionError> {
623        let request = CohereCompletionRequest::try_from((self.model.as_ref(), completion_request))?;
624
625        let llm_span = if tracing::Span::current().is_disabled() {
626            info_span!(
627            target: "rig::completions",
628            "chat",
629            gen_ai.operation.name = "chat",
630            gen_ai.provider.name = "cohere",
631            gen_ai.request.model = self.model,
632            gen_ai.response.id = tracing::field::Empty,
633            gen_ai.response.model = self.model,
634            gen_ai.usage.output_tokens = tracing::field::Empty,
635            gen_ai.usage.input_tokens = tracing::field::Empty,
636            gen_ai.usage.cached_tokens = tracing::field::Empty,
637            )
638        } else {
639            tracing::Span::current()
640        };
641
642        if enabled!(Level::TRACE) {
643            tracing::trace!(
644                "Cohere completion request: {}",
645                serde_json::to_string_pretty(&request)?
646            );
647        }
648
649        let req_body = serde_json::to_vec(&request)?;
650
651        let req = self.client.post("/v2/chat")?.body(req_body).unwrap();
652
653        async {
654            let response = self
655                .client
656                .send::<_, bytes::Bytes>(req)
657                .await
658                .map_err(|e| http_client::Error::Instance(e.into()))?;
659
660            let status = response.status();
661            let body = response.into_body().into_future().await?.to_owned();
662
663            if status.is_success() {
664                let json_response: CompletionResponse = serde_json::from_slice(&body)?;
665                let span = tracing::Span::current();
666                span.record_token_usage(&json_response.usage);
667                span.record_response_metadata(&json_response);
668
669                if enabled!(Level::TRACE) {
670                    tracing::trace!(
671                        target: "rig::completions",
672                        "Cohere completion response: {}",
673                        serde_json::to_string_pretty(&json_response)?
674                    );
675                }
676
677                let completion: completion::CompletionResponse<CompletionResponse> =
678                    json_response.try_into()?;
679                Ok(completion)
680            } else {
681                Err(CompletionError::ProviderError(
682                    String::from_utf8_lossy(&body).to_string(),
683                ))
684            }
685        }
686        .instrument(llm_span)
687        .await
688    }
689
690    async fn stream(
691        &self,
692        request: CompletionRequest,
693    ) -> Result<
694        crate::streaming::StreamingCompletionResponse<Self::StreamingResponse>,
695        CompletionError,
696    > {
697        CompletionModel::stream(self, request).await
698    }
699}
700#[cfg(test)]
701mod tests {
702    use super::*;
703    use serde_path_to_error::deserialize;
704
705    #[test]
706    fn test_deserialize_completion_response() {
707        let json_data = r#"
708        {
709            "id": "abc123",
710            "message": {
711                "role": "assistant",
712                "tool_plan": "I will use the subtract tool to find the difference between 2 and 5.",
713                "tool_calls": [
714                        {
715                            "id": "subtract_sm6ps6fb6y9f",
716                            "type": "function",
717                            "function": {
718                                "name": "subtract",
719                                "arguments": "{\"x\":5,\"y\":2}"
720                            }
721                        }
722                    ]
723                },
724                "finish_reason": "TOOL_CALL",
725                "usage": {
726                "billed_units": {
727                    "input_tokens": 78,
728                    "output_tokens": 27
729                },
730                "tokens": {
731                    "input_tokens": 1028,
732                    "output_tokens": 63
733                }
734            }
735        }
736        "#;
737
738        let mut deserializer = serde_json::Deserializer::from_str(json_data);
739        let result: Result<CompletionResponse, _> = deserialize(&mut deserializer);
740
741        let response = result.unwrap();
742        let (_, citations, tool_calls) = response.message();
743        let CompletionResponse {
744            id,
745            finish_reason,
746            usage,
747            ..
748        } = response;
749
750        assert_eq!(id, "abc123");
751        assert_eq!(finish_reason, FinishReason::ToolCall);
752
753        let Usage {
754            billed_units,
755            tokens,
756        } = usage.unwrap();
757        let BilledUnits {
758            input_tokens: billed_input_tokens,
759            output_tokens: billed_output_tokens,
760            ..
761        } = billed_units.unwrap();
762        let Tokens {
763            input_tokens,
764            output_tokens,
765        } = tokens.unwrap();
766
767        assert_eq!(billed_input_tokens.unwrap(), 78.0);
768        assert_eq!(billed_output_tokens.unwrap(), 27.0);
769        assert_eq!(input_tokens.unwrap(), 1028.0);
770        assert_eq!(output_tokens.unwrap(), 63.0);
771
772        assert!(citations.is_empty());
773        assert_eq!(tool_calls.len(), 1);
774
775        let ToolCallFunction { name, arguments } = tool_calls[0].function.clone().unwrap();
776
777        assert_eq!(name, "subtract");
778        assert_eq!(arguments, serde_json::json!({"x": 5, "y": 2}));
779    }
780
781    #[test]
782    fn test_convert_completion_message_to_message_and_back() {
783        let completion_message = completion::Message::User {
784            content: OneOrMany::one(completion::message::UserContent::Text(
785                completion::message::Text {
786                    text: "Hello, world!".to_string(),
787                },
788            )),
789        };
790
791        let messages: Vec<Message> = completion_message.clone().try_into().unwrap();
792        let _converted_back: Vec<completion::Message> = messages
793            .into_iter()
794            .map(|msg| msg.try_into().unwrap())
795            .collect::<Vec<_>>();
796    }
797
798    #[test]
799    fn test_convert_message_to_completion_message_and_back() {
800        let message = Message::User {
801            content: OneOrMany::one(UserContent::Text {
802                text: "Hello, world!".to_string(),
803            }),
804        };
805
806        let completion_message: completion::Message = message.clone().try_into().unwrap();
807        let _converted_back: Vec<Message> = completion_message.try_into().unwrap();
808    }
809}