Skip to main content

rig_core/client/
signed_in.rs

1//! A catalog model served with a signed-in credential that each request
2//! reads afresh, so a long session outlives its access token. ChatGPT's and
3//! Copilot's authenticators both sign in this way.
4
5use std::future::Future;
6use std::sync::{Arc, Mutex};
7
8use crate::catalog::{Catalog, ModelFacts, ModelSpec};
9use crate::completion::UnsupportedOption;
10use crate::effect::{EffectKind, HandlerDescriptor, family};
11use crate::error::{ErrorKind, ErrorReport, ProviderError};
12use crate::http_client::DynHttpClient;
13use crate::operation::Completion;
14use crate::providers::auth::{AuthContext, AuthError};
15use crate::providers::registry::{ConnectError, ConnectOptions, ProviderConfig};
16use crate::providers::{chatgpt, copilot};
17use crate::serve::adapters::ModelAdapter;
18use crate::serve::{Dispatch, Reply, Serve};
19use crate::wasm_compat::{WasmCompatSend, WasmCompatSync};
20
21/// Where a [`SignedInModel`] reads its credential on every request.
22pub trait CredentialSource: WasmCompatSend + WasmCompatSync + 'static {
23    /// The credential to send with now, refreshed through `http` when it
24    /// has expired.
25    fn auth_context(
26        &self,
27        http: &DynHttpClient,
28    ) -> impl Future<Output = Result<AuthContext, AuthError>> + WasmCompatSend;
29}
30
31impl CredentialSource for chatgpt::auth::Authenticator {
32    fn auth_context(
33        &self,
34        http: &DynHttpClient,
35    ) -> impl Future<Output = Result<AuthContext, AuthError>> + WasmCompatSend {
36        chatgpt::auth::Authenticator::auth_context(self, http)
37    }
38}
39
40impl CredentialSource for copilot::auth::Authenticator {
41    fn auth_context(
42        &self,
43        http: &DynHttpClient,
44    ) -> impl Future<Output = Result<AuthContext, AuthError>> + WasmCompatSend {
45        copilot::auth::Authenticator::auth_context(self, http)
46    }
47}
48
49/// A catalog model as an effect handler whose every request carries the
50/// credential its [`CredentialSource`] resolves at that moment, refreshed
51/// when it has expired: the key, the account it belongs to, and the API root the
52/// sign-in names. The model connected with a credential serves every
53/// request until the credential changes, so its memos last across turns.
54/// ChatGPT also reads its dialect's endpoint and caller identity overrides.
55/// Described as [`ModelAdapter`] describes the model, under its
56/// [`reference`](ModelSpec::reference).
57///
58/// ```no_run
59/// use rig_core::catalog::Catalog;
60/// use rig_core::providers::auth::{DeviceCodeHandler, FileTokenStore};
61/// use rig_core::providers::chatgpt::auth::{AuthSource, Authenticator};
62/// use rig_core::client::signed_in::SignedInModel;
63/// use rig_core::serve::ErasedHandler;
64///
65/// # fn run(http: rig_core::http_client::DynHttpClient) -> Result<(), Box<dyn std::error::Error>> {
66/// let spec = Catalog::builtin().resolve("chatgpt/gpt-6.2-sol")?.spec.clone();
67/// let auth = Authenticator::new(AuthSource::OAuth, FileTokenStore::new("/path/to/credentials"), DeviceCodeHandler::default(), false);
68/// let handler = ErasedHandler::new(SignedInModel::new(spec, auth, http)?);
69/// # let _ = handler;
70/// # Ok(())
71/// # }
72/// ```
73pub struct SignedInModel<A> {
74    spec: ModelSpec,
75    credentials: A,
76    http: DynHttpClient,
77    /// The model connected without a credential: what it is and what it
78    /// would leave out, neither of which sends anything.
79    unsigned: ModelAdapter<Completion>,
80    /// The last credential and the model connected with it.
81    connected: Mutex<Option<(AuthContext, Arc<ModelAdapter<Completion>>)>>,
82}
83
84impl<A: CredentialSource> SignedInModel<A> {
85    /// `spec` served with what `credentials` resolves, through `http`.
86    ///
87    /// # Errors
88    ///
89    /// What [`Catalog::connect_with`] reports for `spec`.
90    pub fn new(spec: ModelSpec, credentials: A, http: DynHttpClient) -> Result<Self, ConnectError> {
91        let unsigned = Catalog::builtin()
92            .connect_with(&spec, ConnectOptions::new().api_key("").http(http.clone()))?;
93        Ok(Self {
94            unsigned: ModelAdapter::new(spec.reference(), unsigned),
95            spec,
96            credentials,
97            http,
98            connected: Mutex::default(),
99        })
100    }
101
102    /// The model connected with the current credential: the one already
103    /// connected while the credential is the same.
104    async fn model(&self) -> Result<Arc<ModelAdapter<Completion>>, ErrorReport> {
105        let context = self
106            .credentials
107            .auth_context(&self.http)
108            .await
109            .map_err(failed_sign_in)?;
110        if let Ok(connected) = self.connected.lock()
111            && let Some((held, model)) = connected.as_ref()
112            && *held == context
113        {
114            return Ok(Arc::clone(model));
115        }
116        let model = if self.spec.provider.vendor() == chatgpt::PROVIDER_NAME {
117            chatgpt::signed_in_config(&context)
118                .map(|config| {
119                    ProviderConfig::OpenAi(config).completion_model(
120                        &self.spec.id,
121                        self.http.clone(),
122                        ModelFacts::new(self.spec.clone()).with_catalog(Catalog::builtin()),
123                    )
124                })
125                .map_err(ConnectError::from)
126        } else {
127            let mut options = ConnectOptions::new()
128                .api_key(context.api_key.clone())
129                .http(self.http.clone());
130            if let Some(account_id) = &context.account_id {
131                options = options.account_id(account_id);
132            }
133            if let Some(api_base) = &context.api_base {
134                options = options.base_url(api_base);
135            }
136            Catalog::builtin().connect_with(&self.spec, options)
137        }
138        .map_err(|error| ErrorReport::new(ErrorKind::Internal, error.to_string()))?;
139        let model = Arc::new(ModelAdapter::new(self.spec.reference(), model));
140        if let Ok(mut connected) = self.connected.lock() {
141            *connected = Some((context, Arc::clone(&model)));
142        }
143        Ok(model)
144    }
145}
146
147/// The report of a call whose sign-in gave no credential. An HTTP failure
148/// underneath classifies it as it would any provider call, so a dropped
149/// connection or a 503 is retried and its `Retry-After` honoured; any other
150/// failure is final and asks to sign in again.
151pub fn failed_sign_in(error: AuthError) -> ErrorReport {
152    let message = format!("the sign-in gave no credential ({error})");
153    let (AuthError::Http(source) | AuthError::Reply { source, .. }) = error else {
154        return ErrorReport::new(ErrorKind::Provider, format!("{message}; sign in again"));
155    };
156    let report = ProviderError::from_transport_error(source).report();
157    let message = if report.retryable {
158        message
159    } else {
160        format!("{message}; sign in again")
161    };
162    ErrorReport { message, ..report }
163}
164
165impl<A: CredentialSource> Serve for SignedInModel<A> {
166    type Family = family::Completion;
167
168    fn descriptor(&self) -> HandlerDescriptor {
169        self.unsigned.descriptor()
170    }
171
172    /// What the model leaves out, from the unsigned model: a check is a
173    /// dry run, which needs no credential.
174    fn check(&self, kind: &EffectKind) -> Vec<UnsupportedOption> {
175        self.unsigned.check(kind)
176    }
177
178    async fn serve(&self, kind: EffectKind, dispatch: Dispatch) -> Reply {
179        match self.model().await {
180            Ok(model) => model.serve(kind, dispatch).await,
181            Err(report) => Reply::Outcome(Err(report)),
182        }
183    }
184}
185
186#[cfg(all(test, not(target_family = "wasm")))]
187mod tests;