rig_core/client/
signed_in.rs1use 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
21pub trait CredentialSource: WasmCompatSend + WasmCompatSync + 'static {
23 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
49pub struct SignedInModel<A> {
74 spec: ModelSpec,
75 credentials: A,
76 http: DynHttpClient,
77 unsigned: ModelAdapter<Completion>,
80 connected: Mutex<Option<(AuthContext, Arc<ModelAdapter<Completion>>)>>,
82}
83
84impl<A: CredentialSource> SignedInModel<A> {
85 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 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
147pub 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 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;