Skip to main content

rig_core/completion/
handle.rs

1//! Serializable model labels resolved to live handles by a runtime.
2//!
3//! ```
4//! use rig_core::completion::ModelRef;
5//!
6//! let model = ModelRef::new("assistant");
7//! assert_eq!(model.as_str(), "assistant");
8//! ```
9
10use std::{fmt, sync::Arc};
11
12use serde::{Deserialize, Serialize};
13
14/// Model label serialized as a string. Equality compares labels without
15/// provider interpretation; resolving a label to a live handle is the runtime's responsibility.
16#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
17pub struct ModelRef(Arc<str>);
18
19// Transparent string (de)serialization without serde's `rc` feature.
20impl Serialize for ModelRef {
21    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
22        serializer.serialize_str(&self.0)
23    }
24}
25
26impl<'de> Deserialize<'de> for ModelRef {
27    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
28        let label = <std::borrow::Cow<'de, str>>::deserialize(deserializer)?;
29        Ok(Self(Arc::from(&*label)))
30    }
31}
32
33impl ModelRef {
34    /// Build a reference from any string-like value.
35    pub fn new(label: impl Into<Arc<str>>) -> Self {
36        Self(label.into())
37    }
38
39    /// The label as a string slice.
40    pub fn as_str(&self) -> &str {
41        &self.0
42    }
43}
44
45impl std::ops::Deref for ModelRef {
46    type Target = str;
47
48    fn deref(&self) -> &str {
49        &self.0
50    }
51}
52
53impl AsRef<str> for ModelRef {
54    fn as_ref(&self) -> &str {
55        &self.0
56    }
57}
58
59impl fmt::Display for ModelRef {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.write_str(&self.0)
62    }
63}
64
65impl From<&str> for ModelRef {
66    fn from(label: &str) -> Self {
67        Self(Arc::from(label))
68    }
69}
70
71impl From<String> for ModelRef {
72    fn from(label: String) -> Self {
73        Self(Arc::from(label))
74    }
75}
76
77impl From<Arc<str>> for ModelRef {
78    fn from(label: Arc<str>) -> Self {
79        Self(label)
80    }
81}
82
83impl From<ModelRef> for String {
84    fn from(label: ModelRef) -> Self {
85        label.0.to_string()
86    }
87}
88
89impl PartialEq<str> for ModelRef {
90    fn eq(&self, other: &str) -> bool {
91        &*self.0 == other
92    }
93}
94
95impl PartialEq<&str> for ModelRef {
96    fn eq(&self, other: &&str) -> bool {
97        &*self.0 == *other
98    }
99}