use http_req::{
request::{Method, Request},
uri::Uri,
};
use serde::{Deserialize, Serialize, Serializer};
use std::collections::HashMap;
use urlencoding::encode;
use crate::Retry;
#[derive(Debug, Deserialize)]
pub struct ChatResponse {
pub restarted: bool,
pub choice: String,
}
impl Default for ChatResponse {
fn default() -> ChatResponse {
ChatResponse {
restarted: true,
choice: String::new(),
}
}
}
#[derive(Debug, Clone, Copy)]
pub enum ChatModel {
GPT4Turbo,
GPT4_32K,
GPT4,
GPT35Turbo16K,
GPT35Turbo,
}
impl Serialize for ChatModel {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
ChatModel::GPT4Turbo => serializer.serialize_str("gpt-4-1106-preview"),
ChatModel::GPT4_32K => serializer.serialize_str("gpt-4-32k"),
ChatModel::GPT4 => serializer.serialize_str("gpt-4"),
ChatModel::GPT35Turbo16K => serializer.serialize_str("gpt-3.5-turbo-16k"),
ChatModel::GPT35Turbo => serializer.serialize_str("gpt-3.5-turbo"),
}
}
}
impl Default for ChatModel {
fn default() -> ChatModel {
ChatModel::GPT35Turbo
}
}
#[derive(Debug)]
pub enum ResponseFormatType {
Text,
JsonObject,
}
#[derive(Debug, Serialize)]
pub struct ResponseFormat {
pub r#type: ResponseFormatType,
}
impl Serialize for ResponseFormatType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
ResponseFormatType::Text => serializer.serialize_str("text"),
ResponseFormatType::JsonObject => serializer.serialize_str("json_object"),
}
}
}
#[derive(Debug, Default, Serialize)]
pub struct ChatOptions<'a> {
pub model: ChatModel,
pub restart: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub system_prompt: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub pre_prompt: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub post_prompt: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub temperature: Option<f32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub top_p: Option<f32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub stop: Option<Vec<String>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub max_tokens: Option<u16>,
#[serde(skip_serializing_if = "Option::is_none")]
pub presence_penalty: Option<f32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub frequency_penalty: Option<f32>,
#[serde(skip_serializing_if = "Option::is_none")]
pub logit_bias: Option<HashMap<String, i8>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub response_format: Option<ResponseFormat>,
}
impl crate::OpenAIFlows {
pub async fn chat_completion(
&self,
conversation_id: &str,
sentence: &str,
options: &ChatOptions<'_>,
) -> Result<ChatResponse, String> {
self.keep_trying(|account| {
chat_completion_inner(account, conversation_id, sentence, options)
})
}
}
fn chat_completion_inner(
account: &str,
conversation_id: &str,
sentence: &str,
options: &ChatOptions,
) -> Retry<ChatResponse> {
let flows_user = unsafe { crate::_get_flows_user() };
let flow_id = unsafe { crate::_get_flow_id() };
let mut writer = Vec::new();
let uri = format!(
"{}/{}/{}/chat_completion_08?account={}&conversation={}",
crate::OPENAI_API_PREFIX.as_str(),
flows_user,
flow_id,
encode(account),
encode(conversation_id),
);
let uri = Uri::try_from(uri.as_str()).unwrap();
let body = serde_json::to_vec(&serde_json::json!({
"sentence": sentence,
"params": options
}))
.unwrap_or_default();
match Request::new(&uri)
.method(Method::POST)
.header("Content-Type", "application/json")
.header("Content-Length", &body.len())
.body(&body)
.send(&mut writer)
{
Ok(res) => {
match res.status_code().is_success() {
true => Retry::No(
serde_json::from_slice::<ChatResponse>(&writer)
.or(Err(String::from("Unexpected error"))),
),
false => {
match res.status_code().into() {
409 | 429 | 503 => {
Retry::Yes(String::from_utf8_lossy(&writer).into_owned())
}
_ => Retry::No(Err(String::from_utf8_lossy(&writer).into_owned())),
}
}
}
}
Err(e) => Retry::No(Err(e.to_string())),
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ChatRole {
User,
Assistant,
}
#[derive(Debug, Deserialize)]
pub struct ChatMessage {
pub role: ChatRole,
pub content: String,
}
pub fn chat_history(conversation_id: &str, limit: u8) -> Option<Vec<ChatMessage>> {
let flows_user = unsafe { crate::_get_flows_user() };
let flow_id = unsafe { crate::_get_flow_id() };
let mut writer = Vec::new();
let uri = format!(
"{}/{}/{}/chat_history?conversation={}&limit={}",
crate::OPENAI_API_PREFIX.as_str(),
flows_user,
flow_id,
encode(conversation_id),
limit
);
let uri = Uri::try_from(uri.as_str()).unwrap();
match Request::new(&uri).method(Method::GET).send(&mut writer) {
Ok(res) => match res.status_code().is_success() {
true => serde_json::from_slice::<Vec<ChatMessage>>(&writer).ok(),
false => None,
},
Err(_) => None,
}
}