1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
use http_req::{
request::{Method, Request},
uri::Uri,
};
use serde::{Deserialize, Serialize, Serializer};
use urlencoding::encode;
/// Models for Chat
#[derive(Debug, Clone, Copy)]
pub enum ChatModel {
ChatBison,
}
impl Serialize for ChatModel {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match self {
ChatModel::ChatBison => serializer.serialize_str("chat-bison"),
}
}
}
impl Default for ChatModel {
fn default() -> ChatModel {
ChatModel::ChatBison
}
}
/// struct for setting the chat options.
#[derive(Debug, Default, Serialize)]
pub struct ChatOptions<'a> {
/// The ID or name of the model to use for completion.
pub model: ChatModel,
/// When true, a new conversation will be created.
pub restart: bool,
/// Context shapes how the model responds throughout the conversation
#[serde(skip_serializing_if = "Option::is_none")]
pub context: Option<&'a str>,
/// List of structured messages to the model to learn how to respond to the conversation.
#[serde(skip_serializing_if = "Option::is_none")]
pub examples: Option<Vec<(String, String)>>,
/// The temperature is used for sampling during the response generation, which occurs when topP and topK are applied.
#[serde(skip_serializing_if = "Option::is_none")]
pub temperature: Option<f32>,
/// Top-p changes how the model selects tokens for output.
#[serde(skip_serializing_if = "Option::is_none")]
pub top_p: Option<f32>,
/// Top-k changes how the model selects tokens for output.
#[serde(skip_serializing_if = "Option::is_none")]
pub top_k: Option<u8>,
/// Maximum number of tokens that can be generated in the response.
#[serde(skip_serializing_if = "Option::is_none")]
pub max_output_tokens: Option<u16>,
}
/// Create chat completion with the provided sentence.
/// It uses Vertex's [chat-bison](https://cloud.google.com/vertex-ai/docs/generative-ai/learn/models?hl=en) model to make a conversation.
///
/// `conversation_id` is the identifier of the conversation.
/// The history will be fetched and attached to the `sentence` as a whole prompt for Vertex.
///
/// `sentence` is a String that reprensents the current utterance of the conversation.
///
///```rust
/// // Create a conversation_id.
/// // Only numbers, letters, underscores, dashes, and pound signs are allowed, up to 50 characters.
/// let chat_id = format!("news-summary-N");
/// // System_prompt content in text.
/// let system = &format!("You're a news editor AI.");
///
/// // Create ChatOptions.
/// let co = ChatOptions {
/// model: ChatModel::ChatBison,
/// restart: true,
/// context: Some(system),
/// // Use .. to extract the default value for the remaining fields.
/// ..Default::default()
/// };
///
/// // Create a `sentence`, the concatenation of user prompt and the text to work with.
/// let question = format!("Make a concise summary within 200 words on this: {news_body}.");
///
/// // Chat to get the result and handle the failure.
/// match chat(&chat_id, &question, &co).await {
/// Ok(r) => Ok(r),
/// Err(e) => Err(e.into()),
/// }
/// ```
pub async fn chat(
conversation_id: &str,
sentence: &str,
options: &ChatOptions<'_>,
) -> Result<String, String> {
let flows_user = unsafe { crate::_get_flows_user() };
let flow_id = unsafe { crate::_get_flow_id() };
let mut writer = Vec::new();
let uri = format!(
"{}/{}/{}/vertex/chat?&conversation={}",
crate::GOOGLE_CLOUD_SERVICE_API_PREFIX.as_str(),
flows_user,
flow_id,
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 => String::from_utf8(writer).or(Err(String::from("Unexpected error"))),
false => Err(String::from_utf8_lossy(&writer).into_owned()),
},
Err(e) => Err(e.to_string()),
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum ChatAuthor {
User,
Assistant,
}
#[derive(Debug, Deserialize)]
pub struct ChatMessage {
pub author: ChatAuthor,
pub content: String,
}
/// Fetch the question history of conversation_id
/// Result will be an array of string whose length is
/// restricted by limit.
/// When limit is 0, all history will be returned.
///
///```rust,no_run
/// // The conversation_id we are interested in.
/// let conversation_id = "unique_conversation_id";
/// // Limit the number of messages returned.
/// let limit: u8 = 10;
/// // Call `chat_history` to fetch the conversation history.
/// let history = chat_history(conversation_id, limit);
///
/// match history {
/// Some(messages) => {
/// println!("Chat history (most recent {} messages):", limit);
/// for message in messages.iter().rev() {
/// let author = match message.author {
/// ChatAuthor::User => "user",
/// ChatAuthor::Assistant => "assistant",
/// };
/// println!("{}: {}", author, message.content);
/// }
/// }
/// None => {
/// println!(
/// "Failed to fetch chat history for conversation {}",
/// conversation_id
/// );
/// }
/// }
/// ```
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!(
"{}/{}/{}/vertex/chat_history?conversation={}&limit={}",
crate::GOOGLE_CLOUD_SERVICE_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,
}
}