Skip to main content

artifactize_core/
llm.rs

1//! Adapt Verify credential locations and session records to the harness and HTTP transport.
2
3pub mod claude_agent;
4pub(crate) mod delivery;
5pub mod models;
6#[cfg(test)]
7pub(crate) mod tests;
8
9use artifactize_provider::{auth::Location, llm as http};
10use rig_core::completion::{CompletionRequest, CompletionResponse};
11use serde_json::Value;
12use std::path::Path;
13
14use crate::{
15    agent::error::{Code, Failure},
16    auth::storage::Tokens,
17    config::{Backend, HttpProvider, ModelId, Provider},
18};
19pub use artifactize_harness::{
20    api::{Api, EndpointApi},
21    error::Attempt,
22};
23use http::HttpRoute;
24pub use http::codex;
25pub use http::{TestEndpoint, Turn, active_test_endpoint, variable_endpoint, variable_endpoint_in};
26
27pub fn base_url_variable(provider: Provider) -> Option<&'static str> {
28    HttpProvider::try_from(provider)
29        .ok()
30        .map(http::base_url_variable)
31}
32pub fn test_endpoint(provider: Provider) -> Result<Option<TestEndpoint>, String> {
33    match HttpProvider::try_from(provider) {
34        Ok(provider) => http::test_endpoint(provider),
35        Err(_) => Ok(None),
36    }
37}
38
39pub(crate) fn codex_location(
40    state: Option<&Path>,
41    repo: Option<&Path>,
42) -> Result<Location, String> {
43    crate::auth::writable_credential_location(state, repo, Tokens::Codex)
44}
45
46/// Where a provider's requests go: its API, its root and its key.
47pub(crate) enum Route {
48    ClaudeAgent,
49    Http(Box<HttpRoute>),
50}
51
52/// Resolve a native Claude route or a direct HTTP provider with its credentials.
53pub(crate) fn route(
54    backend: &Backend,
55    state: Option<&Path>,
56    repo: Option<&Path>,
57    purpose: &str,
58) -> Result<Route, Failure> {
59    use artifactize_harness::backend::Selection;
60    let direct = match backend.selection()? {
61        Selection::ClaudeAgent => return Ok(Route::ClaudeAgent),
62        Selection::Http(direct) => direct,
63    };
64    let location = crate::auth::credential_location(state, repo, Tokens::Providers);
65    HttpRoute::resolve(&direct, location.as_ref().map_err(String::as_str), purpose)?
66        .map(Box::new)
67        .map(Route::Http)
68        .ok_or_else(|| Failure::new(Code::Authentication, backend.not_registered()))
69}
70
71pub struct Client(pub(crate) http::Client);
72
73impl Client {
74    #[doc(hidden)]
75    pub fn from_openai(
76        model: Box<rig_core::Model<rig_core::providers::openai::responses_api::wire::Responses>>,
77        key: String,
78    ) -> Self {
79        Self(http::Client::from_openai(model, key))
80    }
81
82    pub fn new(
83        backend: &Backend,
84        model: &ModelId,
85        state: &Path,
86        repo: &Path,
87    ) -> Result<Self, Failure> {
88        match route(backend, Some(state), Some(repo), "for this Agent backend")? {
89            Route::Http(route) => Self::at(*route, model, state, repo),
90            Route::ClaudeAgent => Err(Failure::new(
91                Code::AgentError,
92                "Unsupported client backend: claude-agent runs reviews through Claude Code.",
93            )),
94        }
95    }
96
97    pub(crate) fn at(
98        route: HttpRoute,
99        model: &ModelId,
100        state: &Path,
101        repo: &Path,
102    ) -> Result<Self, Failure> {
103        let location =
104            if route.api() == http::Api::Codex && crate::auth::codex::auth_file().is_none() {
105                codex_location(Some(state), Some(repo))
106            } else {
107                crate::auth::credential_location(Some(state), Some(repo), Tokens::Codex)
108            };
109        Ok(Self(http::Client::at(route, model, location)?))
110    }
111
112    pub fn api(&self) -> Api {
113        self.0.api().into()
114    }
115
116    pub fn parameters(
117        api: Api,
118        reasoning: Option<&str>,
119        session: &crate::types::SessionId,
120    ) -> Result<Value, String> {
121        artifactize_harness::api::parameters(api, reasoning, session.as_str())
122    }
123
124    pub fn output_format(api: Api, parameters: &mut Value, schema: Value) {
125        artifactize_harness::api::output_format(api, parameters, schema);
126    }
127
128    pub async fn turn(
129        &self,
130        request: &CompletionRequest,
131        turn: Turn<'_>,
132        attempts: &mut Vec<Attempt>,
133    ) -> Result<CompletionResponse, Failure> {
134        self.turn_observed(request, turn, attempts, &mut |_| {})
135            .await
136    }
137
138    pub async fn turn_observed(
139        &self,
140        request: &CompletionRequest,
141        turn: Turn<'_>,
142        attempts: &mut Vec<Attempt>,
143        observe: &mut impl FnMut(crate::agent::session::Delivery),
144    ) -> Result<CompletionResponse, Failure> {
145        let mut transported = Vec::new();
146        let result = self
147            .0
148            .turn_observed(request, turn, &mut transported, &mut |event| {
149                observe(event.into())
150            })
151            .await;
152        attempts.extend(transported.into_iter().map(Attempt::from));
153        Ok(result?)
154    }
155}