open_routerer/api/
completion.rs

1use crate::client::{Client, ClientConfig};
2use crate::error::{Error, Result};
3use crate::types::completion::{CompletionRequest, CompletionResponse};
4use reqwest::Client as ReqwestClient;
5
6/// API endpoint for text completions.
7pub struct CompletionApi {
8    pub(crate) http_client: ReqwestClient,
9    pub(crate) config: ClientConfig,
10}
11
12impl CompletionApi {
13    /// Creates a new CompletionApi with the given reqwest client and configuration.
14    pub fn new(http_client: ReqwestClient, config: &ClientConfig) -> Self {
15        Self {
16            http_client,
17            config: config.clone(),
18        }
19    }
20
21    /// Calls the completions endpoint. The request payload includes at minimum the `model` and `prompt` fields,
22    /// along with any additional generation parameters (temperature, top_p, and so on).
23    pub async fn completion(&self, request: CompletionRequest) -> Result<CompletionResponse> {
24        let config = self.config.clone();
25        let client = self.http_client.clone();
26
27        // Build the URL.
28        let url = config
29            .base_url
30            .join("completions")
31            .map_err(|e| Error::ApiError {
32                code: 400,
33                message: format!("Invalid URL for completions: {}", e),
34                metadata: None,
35            })?;
36
37        // Send the POST request.
38        let response = client
39            .post(url)
40            .headers(self.config.build_headers()?)
41            .json(&request)
42            .send()
43            .await?;
44
45        let completion_response = Client::handle_response(response).await?;
46
47        Ok(completion_response)
48    }
49}