Skip to main content

mockql_core/llm_provider/
mod.rs

1// Copyright 2026 Expedia, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Provider abstractions and built-in provider clients.
16
17pub mod cli;
18pub mod http;
19
20use self::cli::CliProvider;
21use crate::graphql::GraphQLResponse;
22use crate::graphql::mock_response_prompt::MockResponsePrompt;
23use crate::graphql::mock_response_prompt::PromptSerializationError;
24use crate::llm_provider::http::HttpProvider;
25use reqwest::Client;
26use std::time::Duration;
27use thiserror::Error;
28
29/// Supported provider transport configurations.
30#[derive(Debug, Clone)]
31pub enum ProviderConfig {
32  /// CLI provider configuration.
33  Cli {
34    /// CLI provider variant to invoke.
35    provider: CliProvider,
36    /// Maximum amount of time allowed for the CLI invocation.
37    timeout: Duration,
38  },
39  /// HTTP provider configuration.
40  Http {
41    /// HTTP provider variant to invoke.
42    provider: HttpProvider,
43    /// HTTP client used to issue provider requests. Its configured timeout applies.
44    client: Client,
45  },
46}
47
48/// Errors raised while serializing prompts or invoking mock providers.
49#[derive(Debug, Error)]
50pub enum ProviderError {
51  /// Prompt serialization failed before the request could be sent.
52  #[error("failed to serialize prompt: {0}")]
53  Prompt(#[from] PromptSerializationError),
54  /// The provider could not be invoked or returned an execution error.
55  #[error("provider request failed: {0}")]
56  Request(String),
57  /// A required environment variable was not set.
58  #[error("missing environment variable: {0}")]
59  MissingEnv(String),
60  /// HTTP transport failure while invoking an HTTP provider.
61  #[error(transparent)]
62  Http(#[from] reqwest::Error),
63  /// The provider returned a non-success HTTP status.
64  #[error("provider returned status {status}: {body}")]
65  UnexpectedStatus {
66    /// HTTP status code returned by the provider.
67    status: reqwest::StatusCode,
68    /// Raw response body, if any.
69    body: String,
70  },
71  /// The provider response was missing an expected field.
72  #[error("malformed provider response: missing {0}")]
73  MalformedResponse(&'static str),
74  /// The provider returned invalid JSON.
75  #[error("provider returned invalid JSON: {0}")]
76  InvalidJson(#[from] serde_json::Error),
77}
78
79/// Dispatches a mock response prompt to a provider.
80pub async fn generate_mock_response(
81  config: &ProviderConfig,
82  prompt: &MockResponsePrompt,
83) -> Result<GraphQLResponse, ProviderError> {
84  match config {
85    ProviderConfig::Cli { provider, timeout } => provider.run(prompt, *timeout).await,
86    ProviderConfig::Http { provider, client } => provider.run(prompt, client).await,
87  }
88}
89
90/// Parses a `GraphQLResponse` from raw LLM text, tolerating markdown fences, leading prose, and trailing junk.
91pub(crate) fn parse_llm_json(raw: &str) -> Result<GraphQLResponse, ProviderError> {
92  let trimmed = raw.trim();
93  if let Ok(response) = GraphQLResponse::try_from(trimmed) {
94    return Ok(response);
95  }
96
97  // ponytail: O(n) scan over `{` candidates; avoids latching onto non-GraphQL `{...}` in prose
98  let mut first_err = None;
99  for (idx, _) in trimmed.match_indices('{') {
100    match serde_json::Deserializer::from_str(&trimmed[idx..])
101      .into_iter::<GraphQLResponse>()
102      .next()
103    {
104      Some(Ok(response)) if response.data.is_some() || !response.errors.is_empty() => return Ok(response),
105      Some(Err(err)) if first_err.is_none() => first_err = Some(err),
106      _ => {}
107    }
108  }
109
110  Err(ProviderError::InvalidJson(
111    first_err.unwrap_or_else(|| GraphQLResponse::try_from(trimmed).unwrap_err()),
112  ))
113}
114
115#[cfg(test)]
116mod tests {
117  use super::*;
118
119  #[test]
120  fn parse_llm_json_handles_clean_fenced_prose_and_trailing() {
121    let cases = [
122      r#"{"data":{"ok":true}}"#,
123      "```json\n{\"data\":{\"ok\":true}}\n```",
124      "Here is the {example} output:\n{\"data\":{\"ok\":true}}\nHope that helps!",
125      "{\"data\":{\"ok\":true}}} trailing",
126    ];
127    for raw in cases {
128      let resp = parse_llm_json(raw).unwrap_or_else(|e| panic!("failed on {raw:?}: {e}"));
129      assert_eq!(resp.data.unwrap()["ok"], true);
130    }
131  }
132
133  #[test]
134  fn parse_llm_json_rejects_invalid_json() {
135    assert!(matches!(parse_llm_json("not json"), Err(ProviderError::InvalidJson(_))));
136    assert!(matches!(
137      parse_llm_json("{\"data\":{\"ok\":"),
138      Err(ProviderError::InvalidJson(_))
139    ));
140  }
141}