Skip to main content

mockql_core/llm_provider/http/
github_copilot.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
15use crate::GraphQLResponse;
16use crate::ProviderError;
17use crate::graphql::mock_response_prompt::MockResponsePrompt;
18use reqwest::Client;
19use serde_json::json;
20use std::env;
21
22/// GitHub Copilot HTTP provider.
23#[derive(Debug, Clone)]
24pub struct GithubCopilotHttpProvider {
25  /// Model identifier forwarded to the GitHub Copilot request.
26  pub model: String,
27}
28
29impl GithubCopilotHttpProvider {
30  const ENDPOINT: &str = "https://api.githubcopilot.com/chat/completions";
31  const TOKEN_ENV_VAR: &str = "GITHUB_TOKEN";
32
33  pub(crate) async fn run(
34    &self,
35    prompt: &MockResponsePrompt,
36    client: &Client,
37  ) -> Result<GraphQLResponse, ProviderError> {
38    let token =
39      env::var(Self::TOKEN_ENV_VAR).map_err(|_| ProviderError::MissingEnv(Self::TOKEN_ENV_VAR.to_string()))?;
40    let response = client
41      .post(Self::ENDPOINT)
42      .bearer_auth(token)
43      .header("Content-Type", "application/json")
44      .json(&json!({
45        "model": self.model,
46        "response_format": { "type": "json_object" },
47        "messages": [{ "role": "user", "content": prompt.to_markdown()? }],
48        "stream": false
49      }))
50      .send()
51      .await?;
52
53    let status = response.status();
54    let text = response.text().await?;
55
56    if !status.is_success() {
57      return Err(ProviderError::UnexpectedStatus { status, body: text });
58    }
59
60    Self::parse_response(&text)
61  }
62
63  fn parse_response(body: &str) -> Result<GraphQLResponse, ProviderError> {
64    let payload: serde_json::Value = serde_json::from_str(body)?;
65    let content = payload
66      .get("choices")
67      .and_then(|choices| choices.as_array())
68      .and_then(|choices| choices.first())
69      .and_then(|choice| choice.get("message"))
70      .and_then(|message| message.get("content"))
71      .and_then(|content| content.as_str())
72      .ok_or(ProviderError::MalformedResponse("choices[0].message.content"))?;
73
74    crate::llm_provider::parse_llm_json(content)
75  }
76}
77
78#[cfg(test)]
79mod tests {
80  use super::*;
81
82  #[test]
83  fn parses_fixture_response() {
84    let response = GithubCopilotHttpProvider::parse_response(include_str!("mock-response.github-copilot.json"))
85      .expect("fixture should parse");
86
87    let data = response.data.expect("response should contain data");
88    assert_eq!(data["allFilms"]["films"][0]["director"], "George Lucas");
89  }
90
91  #[test]
92  fn rejects_missing_content() {
93    let body = json!({ "choices": [] }).to_string();
94    let error = GithubCopilotHttpProvider::parse_response(&body).unwrap_err();
95    assert!(matches!(
96      error,
97      ProviderError::MalformedResponse("choices[0].message.content")
98    ));
99  }
100
101  #[test]
102  fn rejects_invalid_json() {
103    let error = GithubCopilotHttpProvider::parse_response("{not json}").unwrap_err();
104    assert!(matches!(error, ProviderError::InvalidJson(_)));
105  }
106}