#![doc = include_str!("../README.md")]
use std::{iter::once, marker::PhantomData, ops::ControlFlow};
use async_openai::{
Client,
config::Config,
error::OpenAIError,
types::chat::{
ChatCompletionMessageToolCall, ChatCompletionMessageToolCalls,
ChatCompletionRequestAssistantMessage, ChatCompletionRequestAssistantMessageContent,
ChatCompletionRequestSystemMessage, ChatCompletionRequestToolMessage,
ChatCompletionRequestUserMessage, ChatCompletionTool, ChatCompletionTools,
CreateChatCompletionRequestArgs, FinishReason, FunctionObjectArgs, ResponseFormat,
ResponseFormatJsonSchema,
},
};
use futures_util::StreamExt;
use log::{debug, trace};
use schemars::{JsonSchema, generate::SchemaSettings, transform::RestrictFormats};
use serde::de::DeserializeOwned;
use serde_json::Value;
macro_rules! impl_tools {
($($name:ident),*) => {
impl<R, $($name: Tool<R>),*> Tools<R> for ($($name,)*) {
#[allow(non_snake_case)]
fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
where R: 'r
{
let ($($name,)*) = self;
[
$($name as &mut dyn Tool<R>,)*
].into_iter()
}
}
}
}
impl_tools!(T0);
impl_tools!(T0, T1);
impl_tools!(T0, T1, T2);
impl_tools!(T0, T1, T2, T3);
impl_tools!(T0, T1, T2, T3, T4);
impl_tools!(T0, T1, T2, T3, T4, T5);
impl_tools!(T0, T1, T2, T3, T4, T5, T6);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
impl_tools!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
impl_tools!(
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
);
impl_tools!(
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
);
impl<
D: JsonSchema + DeserializeOwned,
R,
Fut: Future<Output = ControlFlow<R, String>>,
F: FnMut(D) -> Fut,
> Tools<R> for FnTool<D, R, Fut, F>
{
fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
where
R: 'r,
{
once(self as &mut dyn Tool<R>)
}
}
pub trait Tools<R> {
fn iter<'r>(&'r mut self) -> impl Iterator<Item = &'r mut dyn Tool<R>>
where
R: 'r;
}
pub trait Tool<R> {
fn name(&self) -> &str;
fn description(&self) -> &str;
fn parameter_schema(&self) -> Value;
fn invoke<'lt>(
&'lt mut self,
data: &str,
) -> Box<dyn Future<Output = ControlFlow<R, String>> + 'lt>;
}
struct FnTool<D, R, Fut, F> {
name: &'static str,
description: &'static str,
invoke: F,
_phantom: PhantomData<(fn(D) -> R, Fut)>,
}
pub fn tool<
'a,
D: JsonSchema + DeserializeOwned,
R,
Fut: Future<Output = ControlFlow<R, String>>,
F: FnMut(D) -> Fut,
>(
name: &'static str,
description: &'static str,
invoke: F,
) -> impl Tool<R> {
FnTool {
name,
description,
invoke,
_phantom: PhantomData,
}
}
impl<
D: JsonSchema + DeserializeOwned,
R,
Fut: Future<Output = ControlFlow<R, String>>,
F: FnMut(D) -> Fut,
> Tool<R> for FnTool<D, R, Fut, F>
{
fn name(&self) -> &str {
self.name
}
fn description(&self) -> &str {
self.description
}
fn parameter_schema(&self) -> Value {
make_schema::<D>()
}
fn invoke<'lt>(
&'lt mut self,
data: &str,
) -> Box<dyn Future<Output = ControlFlow<R, String>> + 'lt> {
let args = serde_json::from_str::<D>(data).unwrap();
Box::new((self.invoke)(args)) as Box<dyn Future<Output = ControlFlow<R, String>>>
}
}
fn make_schema<D: JsonSchema>() -> Value {
let schema = SchemaSettings::draft2020_12()
.with_transform(RestrictFormats::default())
.with(|s| s.inline_subschemas = true)
.into_generator()
.into_root_schema_for::<D>();
serde_json::to_value(&schema).unwrap()
}
pub struct FinishHandler<R> {
finish: Box<dyn FnMut() -> Box<dyn Future<Output = ControlFlow<R, String>>>>,
}
impl<R> FinishHandler<R> {
fn invoke(&mut self) -> Box<dyn Future<Output = ControlFlow<R, String>>> {
(self.finish)()
}
}
impl<R, Fut: Future<Output = ControlFlow<R, String>> + 'static, F: FnMut() -> Fut + 'static> From<F>
for FinishHandler<R>
{
fn from(mut value: F) -> Self {
Self {
finish: Box::new(move || Box::new((value)())),
}
}
}
pub struct Agent<T, R> {
tools: T,
listen_content: Option<Box<dyn Fn(&str)>>,
listen_tool_call: Option<Box<dyn Fn(&str)>>,
_phantom: PhantomData<R>,
finish: FinishHandler<R>,
}
impl<R, T: Tools<R>> Agent<T, R> {
pub fn new(tools: T, finish: FinishHandler<R>) -> Self {
Self {
tools,
finish,
listen_content: None,
listen_tool_call: None,
_phantom: PhantomData,
}
}
pub fn with_content_listener(mut self, listener: Box<dyn Fn(&str)>) -> Self {
self.listen_content = Some(listener);
self
}
pub fn with_tool_call_listener(mut self, listener: Box<dyn Fn(&str)>) -> Self {
self.listen_tool_call = Some(listener);
self
}
pub async fn run<C: Config>(&mut self, client: &Client<C>, prompt: &str) -> R {
let mut messages = vec![ChatCompletionRequestUserMessage::from(prompt).into()];
loop {
let tools = self
.tools
.iter()
.map(|tool| {
ChatCompletionTools::Function(ChatCompletionTool {
function: FunctionObjectArgs::default()
.name(tool.name())
.description(tool.description())
.parameters(tool.parameter_schema())
.build()
.unwrap(),
})
})
.collect::<Vec<_>>();
let request = CreateChatCompletionRequestArgs::default()
.messages(messages.clone())
.tools(tools)
.build()
.unwrap();
let mut stream = client.chat().create_stream(request).await.unwrap();
let mut tool_calls = Vec::new();
let mut execution_results = Vec::new();
while let Some(result) = stream.next().await {
let response = match result {
Ok(response) => response,
Err(OpenAIError::JSONDeserialize(e, json)) => {
let json: Value = serde_json::from_str(&json).unwrap();
if let Some(err) = json.get("error")
&& let Some(ty) = err.get("type")
&& let Some(ty) = ty.as_str()
&& ty == "exceed_context_size_error"
{
let mut messages_to_summarize = messages
.drain(..messages.len().saturating_sub(3).min(1))
.collect::<Vec<_>>();
debug!(
"Context size exceeded ({err:?}), attempting summary of messages: {messages_to_summarize:#?}."
);
messages_to_summarize.push(
ChatCompletionRequestSystemMessage::from(include_str!(
"summary.txt"
))
.into(),
);
let request = CreateChatCompletionRequestArgs::default()
.messages(messages_to_summarize)
.build()
.unwrap();
let response = client.chat().create(request).await.unwrap();
trace!("Summarized to: {response:#?}");
for (index, choice) in response.choices.into_iter().enumerate() {
messages.insert(
index,
ChatCompletionRequestAssistantMessage {
content: Some(
ChatCompletionRequestAssistantMessageContent::Text(
choice.message.content.unwrap(),
),
),
..Default::default()
}
.into(),
);
}
break;
} else {
panic!("Unexpected error: failed to deserialize JSON: {e} in {json}");
}
}
Err(e) => panic!("Unexpected error: {e}"),
};
for choice in response.choices {
if let Some(content) = &choice.delta.content
&& let Some(f) = &self.listen_content
{
(f)(&content);
}
if let Some(tool_call_chunks) = choice.delta.tool_calls {
for chunk in tool_call_chunks {
let index = chunk.index as usize;
if tool_calls.len() <= index {
tool_calls.resize(
index + 1,
ChatCompletionMessageToolCall {
id: String::new(),
function: Default::default(),
},
);
}
let tool_call = &mut tool_calls[index];
if let Some(id) = chunk.id {
tool_call.id = id;
}
if let Some(function_chunk) = chunk.function {
if let Some(name) = function_chunk.name {
if let Some(f) = &self.listen_tool_call {
(f)(&name);
}
tool_call.function.name = name;
}
if let Some(arguments) = function_chunk.arguments {
if let Some(f) = &self.listen_tool_call {
(f)(&arguments);
}
tool_call.function.arguments.push_str(&arguments);
}
}
}
}
match choice.finish_reason {
Some(FinishReason::ToolCalls) => {
for tool_call in tool_calls.iter() {
let name = tool_call.function.name.clone();
let tool_call_id = tool_call.id.clone();
let result = {
debug!("Executing tool: {name}");
let tool = self.tools.iter().find(|tool| tool.name() == name);
match tool {
Some(tool) => {
let future = tool.invoke(&tool_call.function.arguments);
let pinned = Box::into_pin(future);
pinned.await
}
None => ControlFlow::Continue(String::from(
"ERROR: Tool not found",
)),
}
};
match result {
ControlFlow::Continue(result) => {
execution_results.push((tool_call_id, result))
}
ControlFlow::Break(val) => return val,
}
}
}
Some(FinishReason::Stop) => {
let future = self.finish.invoke();
let pinned = Box::into_pin(future);
let result = pinned.await;
match result {
ControlFlow::Continue(result) => {
messages.push(
ChatCompletionRequestUserMessage::from(result).into(),
);
}
ControlFlow::Break(val) => return val,
}
}
Some(reason) => panic!("Unexpected stop reason: {reason:?}"),
_ => (),
}
}
}
if !execution_results.is_empty() {
let assistant_tool_calls: Vec<ChatCompletionMessageToolCalls> =
tool_calls.iter().map(|tc| tc.clone().into()).collect();
messages.push(
ChatCompletionRequestAssistantMessage {
content: None,
tool_calls: Some(assistant_tool_calls),
..Default::default()
}
.into(),
);
for (tool_call_id, response) in execution_results {
messages.push(
ChatCompletionRequestToolMessage {
content: response.to_string().into(),
tool_call_id,
}
.into(),
);
}
}
}
}
}
pub async fn one_shot<C: Config, R: JsonSchema + DeserializeOwned>(
client: &Client<C>,
prompt: &str,
) -> R {
let request = CreateChatCompletionRequestArgs::default()
.messages(vec![ChatCompletionRequestUserMessage::from(prompt).into()])
.response_format(ResponseFormat::JsonSchema {
json_schema: ResponseFormatJsonSchema {
name: format!("Result"),
description: None,
schema: Some(make_schema::<R>()),
strict: Some(true),
},
})
.build()
.unwrap();
let response = client.chat().create(request).await.unwrap();
let text = response
.choices
.into_iter()
.map(|choice| choice.message.content.unwrap())
.collect::<String>();
serde_json::from_str(&text).unwrap()
}