Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle assistant messages with 'tool_calls' #824

Merged
merged 8 commits into from
Nov 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 9 additions & 8 deletions mistralrs-core/src/pipeline/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -561,6 +561,7 @@ mod tests {
use crate::MessageContent;
use either::Either;
use indexmap::IndexMap;
use serde_json::Value;

macro_rules! hashmap {
(@single $($x:tt)*) => (());
Expand All @@ -572,7 +573,7 @@ mod tests {
let _cap = hashmap!(@count $($key),*);
let mut _map = ::indexmap::IndexMap::with_capacity(_cap);
$(
let _ = _map.insert($key, $value);
let _ = _map.insert($key, Value::String($value));
)*
_map
}
Expand Down Expand Up @@ -677,7 +678,7 @@ mod tests {
];
let mut inputs = Vec::new();
for [role, content] in messages {
let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, String>>>> =
let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, Value>>>> =
IndexMap::new();
message.insert("role".to_string(), Either::Left(role.to_string()));
message.insert("content".to_string(), Either::Left(content.to_string()));
Expand Down Expand Up @@ -711,7 +712,7 @@ mod tests {

let mut inputs = Vec::new();

let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, String>>>> =
let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, Value>>>> =
IndexMap::new();
message.insert("role".to_string(), Either::Left("system".to_string()));
message.insert(
Expand All @@ -723,7 +724,7 @@ mod tests {
);
inputs.push(message);

let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, String>>>> =
let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, Value>>>> =
IndexMap::new();
message.insert("role".to_string(), Either::Left("user".to_string()));
message.insert(
Expand All @@ -740,7 +741,7 @@ mod tests {
);
inputs.push(message);

let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, String>>>> =
let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, Value>>>> =
IndexMap::new();
message.insert("role".to_string(), Either::Left("assistant".to_string()));
message.insert(
Expand All @@ -752,7 +753,7 @@ mod tests {
);
inputs.push(message);

let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, String>>>> =
let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, Value>>>> =
IndexMap::new();
message.insert("role".to_string(), Either::Left("user".to_string()));
message.insert(
Expand All @@ -769,7 +770,7 @@ mod tests {
);
inputs.push(message);

let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, String>>>> =
let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, Value>>>> =
IndexMap::new();
message.insert("role".to_string(), Either::Left("assistant".to_string()));
message.insert(
Expand All @@ -781,7 +782,7 @@ mod tests {
);
inputs.push(message);

let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, String>>>> =
let mut message: IndexMap<String, Either<String, Vec<IndexMap<String, Value>>>> =
IndexMap::new();
message.insert("role".to_string(), Either::Left("user".to_string()));
message.insert(
Expand Down
11 changes: 8 additions & 3 deletions mistralrs-core/src/pipeline/processing.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,13 @@ pub(crate) fn apply_chat_template(
'outer: for content_row in rv {
for (content_k, content_v) in content_row {
if content_k == "text" {
new_message.insert(k, Either::Left(content_v));
break 'outer;
if let Some(content_str) = content_v.as_str() {
new_message.insert(
k,
Either::Left(content_str.to_string()),
);
break 'outer;
}
}
}
}
Expand Down Expand Up @@ -149,6 +154,6 @@ impl Processor for BasicProcessor {
&[]
}
fn template_action(&self) -> MessagesAction {
MessagesAction::FlattenOnlyText
MessagesAction::Keep
}
}
3 changes: 2 additions & 1 deletion mistralrs-core/src/request.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use either::Either;
use indexmap::IndexMap;
use mistralrs_quant::IsqType;
use serde::{Deserialize, Serialize};
use serde_json::Value;

use crate::{
response::Response,
Expand All @@ -28,7 +29,7 @@ pub enum ImageGenerationResponseFormat {
B64Json,
}

pub type MessageContent = Either<String, Vec<IndexMap<String, String>>>;
pub type MessageContent = Either<String, Vec<IndexMap<String, Value>>>;

#[derive(Clone, Debug)]
/// Message or messages for a [`Request`].
Expand Down
8 changes: 8 additions & 0 deletions mistralrs-core/src/tools/response.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,14 @@ pub enum ToolCallType {
Function,
}

impl std::fmt::Display for ToolCallType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ToolCallType::Function => write!(f, "function"),
}
}
}

#[cfg_attr(feature = "pyo3_macros", pyo3::pyclass)]
#[cfg_attr(feature = "pyo3_macros", pyo3(get_all))]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
Expand Down
15 changes: 9 additions & 6 deletions mistralrs-pyo3/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use anymoe::{AnyMoeConfig, AnyMoeExpertType};
use either::Either;
use indexmap::IndexMap;
use requests::{ChatCompletionRequest, CompletionRequest, ToolChoice};
use serde_json::Value;
use std::{
cell::RefCell,
collections::HashMap,
Expand Down Expand Up @@ -683,7 +684,7 @@ impl Runner {
Either::Left(content) => {
let mut message_map: IndexMap<
String,
Either<String, Vec<IndexMap<String, String>>>,
Either<String, Vec<IndexMap<String, Value>>>,
> = IndexMap::new();
message_map.insert(
"role".to_string(),
Expand Down Expand Up @@ -760,7 +761,7 @@ impl Runner {
}
let mut message_map: IndexMap<
String,
Either<String, Vec<IndexMap<String, String>>>,
Either<String, Vec<IndexMap<String, Value>>>,
> = IndexMap::new();
message_map.insert(
"role".to_string(),
Expand All @@ -774,11 +775,13 @@ impl Runner {

let mut content_map = Vec::new();
let mut content_image_map = IndexMap::new();
content_image_map.insert("type".to_string(), "image".to_string());
content_image_map
.insert("type".to_string(), Value::String("image".to_string()));
content_map.push(content_image_map);
let mut content_text_map = IndexMap::new();
content_text_map.insert("type".to_string(), "text".to_string());
content_text_map.insert("text".to_string(), content);
content_text_map
.insert("type".to_string(), Value::String("text".to_string()));
content_text_map.insert("text".to_string(), Value::String(content));
content_map.push(content_text_map);

message_map
Expand Down Expand Up @@ -808,7 +811,7 @@ impl Runner {
let mut messages = Vec::new();
let mut message_map: IndexMap<
String,
Either<String, Vec<IndexMap<String, String>>>,
Either<String, Vec<IndexMap<String, Value>>>,
> = IndexMap::new();
message_map.insert("role".to_string(), Either::Left("user".to_string()));
message_map.insert("content".to_string(), Either::Left(prompt.to_string()));
Expand Down
17 changes: 10 additions & 7 deletions mistralrs-server/src/chat_completion.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use serde_json::Value;
use std::{
collections::HashMap,
env,
Expand Down Expand Up @@ -173,7 +174,7 @@ async fn parse_request(
Either::Left(content) => {
let mut message_map: IndexMap<
String,
Either<String, Vec<IndexMap<String, String>>>,
Either<String, Vec<IndexMap<String, Value>>>,
> = IndexMap::new();
message_map.insert("role".to_string(), Either::Left(message.role));
message_map
Expand Down Expand Up @@ -234,7 +235,7 @@ async fn parse_request(
}
let mut message_map: IndexMap<
String,
Either<String, Vec<IndexMap<String, String>>>,
Either<String, Vec<IndexMap<String, Value>>>,
> = IndexMap::new();
message_map.insert("role".to_string(), Either::Left(message.role));
let (content, url) = if items[0] == "text" {
Expand All @@ -243,13 +244,15 @@ async fn parse_request(
get_content_and_url(1, 0, image_messages)?
};

let mut content_map = Vec::new();
let mut content_map: Vec<IndexMap<String, Value>> = Vec::new();
let mut content_image_map = IndexMap::new();
content_image_map.insert("type".to_string(), "image".to_string());
content_image_map
.insert("type".to_string(), Value::String("image".to_string()));
content_map.push(content_image_map);
let mut content_text_map = IndexMap::new();
content_text_map.insert("type".to_string(), "text".to_string());
content_text_map.insert("text".to_string(), content);
content_text_map
.insert("type".to_string(), Value::String("text".to_string()));
content_text_map.insert("text".to_string(), Value::String(content));
content_map.push(content_text_map);

message_map.insert("content".to_string(), Either::Right(content_map));
Expand All @@ -276,7 +279,7 @@ async fn parse_request(
}
Either::Right(prompt) => {
let mut messages = Vec::new();
let mut message_map: IndexMap<String, Either<String, Vec<IndexMap<String, String>>>> =
let mut message_map: IndexMap<String, Either<String, Vec<IndexMap<String, Value>>>> =
IndexMap::new();
message_map.insert("role".to_string(), Either::Left("user".to_string()));
message_map.insert("content".to_string(), Either::Left(prompt));
Expand Down
5 changes: 3 additions & 2 deletions mistralrs-server/src/interactive_mode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use mistralrs_core::{
};
use once_cell::sync::Lazy;
use regex::Regex;
use serde_json::Value;
use std::{
io::{self, Write},
sync::{atomic::Ordering, Arc, Mutex},
Expand Down Expand Up @@ -221,7 +222,7 @@ async fn text_interactive_mode(mistralrs: Arc<MistralRs>, throughput: bool) {
println!();
info!("Average T/s: {}", toks as f64 / time);
}
let mut assistant_message: IndexMap<String, Either<String, Vec<IndexMap<String, String>>>> =
let mut assistant_message: IndexMap<String, Either<String, Vec<IndexMap<String, Value>>>> =
IndexMap::new();
assistant_message.insert("role".to_string(), Either::Left("assistant".to_string()));
assistant_message.insert("content".to_string(), Either::Left(assistant_output));
Expand Down Expand Up @@ -431,7 +432,7 @@ async fn vision_interactive_mode(mistralrs: Arc<MistralRs>, throughput: bool) {
println!();
info!("Average T/s: {}", toks as f64 / time);
}
let mut assistant_message: IndexMap<String, Either<String, Vec<IndexMap<String, String>>>> =
let mut assistant_message: IndexMap<String, Either<String, Vec<IndexMap<String, Value>>>> =
IndexMap::new();
assistant_message.insert("role".to_string(), Either::Left("assistant".to_string()));
assistant_message.insert("content".to_string(), Either::Left(assistant_output));
Expand Down
22 changes: 14 additions & 8 deletions mistralrs/examples/lower_level/tools/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,20 +126,26 @@ fn main() -> anyhow::Result<()> {
// Add tool call message from assistant so it knows what it called
messages.push(IndexMap::from([
("role".to_string(), Either::Left("assistant".to_string())),
("content".to_string(), Either::Left("".to_string())),
(
"content".to_string(),
Either::Left(
json!({
"name": called.function.name,
"parameters": called.function.arguments,
})
.to_string(),
),
"tool_calls".to_string(),
Either::Right(Vec![IndexMap::from([
("id".to_string(), tool_call.id),
(
"function".to_string(),
json!({
"name": called.function.name,
"arguments": called.function.arguments,
})
),
("type".to_string(), "function".to_string()),
])]),
),
]));
// Add message from the tool
messages.push(IndexMap::from([
("role".to_string(), Either::Left("tool".to_string())),
("tool_call_id".to_string(), Either::Left(tool_call.id)),
("content".to_string(), Either::Left(result)),
]));

Expand Down
11 changes: 4 additions & 7 deletions mistralrs/examples/tools/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,15 +66,12 @@ async fn main() -> Result<()> {
// Add tool call message from assistant so it knows what it called
// Then, add message from the tool
messages = messages
.add_message(
.add_message_with_tool_call(
TextMessageRole::Assistant,
json!({
"name": called.function.name,
"parameters": called.function.arguments,
})
.to_string(),
String::new(),
vec![called.clone()],
)
.add_message(TextMessageRole::Tool, result)
.add_tool_message(result, called.id.clone())
.set_tool_choice(ToolChoice::None);

let response = model.send_chat_request(messages.clone()).await?;
Expand Down
Loading
Loading