Expand description
REST API client module for OpenAI interface
This module provides the core HTTP functionality for making requests to OpenAI-compatible APIs. It includes traits and implementations for both streaming and non-streaming API calls.
§Overview
The rest module contains:
post: HTTP POST request functionality with streaming and non-streaming supportget: HTTP GET request functionality with various parameter handling optionsdelete: HTTP DELETE request functionalitydefault_client: Areqwest::Clientconstructor shared by all request traitscheck_status: Shared non-2xx response handling which parses the error body
§Usage
The module is designed to be used through the higher-level API modules (chat, completions,
etc.). However, you can use the traits directly if needed:
§POST Requests
use openai_interface::rest::post::{Post, PostNoStream};
use openai_interface::errors::OapiError;
use serde::{Serialize, Deserialize};
use std::str::FromStr;
#[derive(Serialize)]
struct MyRequest {
prompt: String,
stream: bool,
}
#[derive(Deserialize)]
struct MyResponse {
// Define the fields of your response here
id: String,
}
impl FromStr for MyResponse {
type Err = OapiError;
fn from_str(content: &str) -> Result<Self, Self::Err> {
let parse_result: Result<Self, _> = serde_json::from_str(content)
.map_err(|e| OapiError::DeserializationError(e.to_string()));
parse_result
}
}
impl Post for MyRequest {
fn is_streaming(&self) -> bool {
self.stream
}
fn build_url(&self, base_url: &str) -> Result<String, OapiError> {
Ok(format!("{}/service", base_url))
}
}
impl PostNoStream for MyRequest {
type Response = MyResponse;
}
// Send it with a client:
// let client = openai_interface::rest::default_client();
// let response: MyResponse = request
// .get_response(&client, "https://api.openai.com/v1/chat/completions", "API_KEY")
// .await?;§GET Requests
use openai_interface::rest::get::Get;
use openai_interface::errors::OapiError;
// GET request with URL building
struct ComplexRequest {
resource_id: String,
limit: Option<u32>,
}
impl Get for ComplexRequest {
fn build_url(&self, base_url: &str) -> Result<String, OapiError> {
let mut url = format!("{}/{}", base_url, self.resource_id);
if let Some(limit) = self.limit {
url.push_str(&format!("?limit={}", limit));
}
Ok(url)
}
}§Client configuration
Every request method takes the client as its first argument, so callers
control proxies, timeouts and connection pooling. Use
default_client for a sensible default, or build your own, e.g. with a
proxy:
let client = reqwest::Client::builder()
.proxy(reqwest::Proxy::http("http://127.0.0.1:10808")?)
.timeout(std::time::Duration::from_secs(60))
.build()?;Modules§
Functions§
- check_
status - Checks a response status, turning a non-2xx response into an
OapiError::ApiErrorthat carries the parsed error body. - default_
client - Builds a
reqwest::Clientwith library defaults.