Compare commits
11 Commits
v0.1.3
..
d5e0728532
| Author | SHA1 | Date | |
|---|---|---|---|
|
d5e0728532
|
|||
|
25c0885dcc
|
|||
|
f56ed7d005
|
|||
|
d79e4b9dff
|
|||
|
cdd829199f
|
|||
|
e3c644b8ca
|
|||
|
5cb8070da1
|
|||
|
66801b5d07
|
|||
|
f2de196e22
|
|||
|
2eba530895
|
|||
| 3baa3102a3 |
+2
-1
@@ -48,7 +48,8 @@ cz commit
|
|||||||
1. Clone this repo
|
1. Clone this repo
|
||||||
2. Run `cargo test` to set up hooks
|
2. Run `cargo test` to set up hooks
|
||||||
3. Make changes
|
3. Make changes
|
||||||
4. Run the application using `make run` or `cargo run`
|
4. Run the application using `just run` or `just run`
|
||||||
|
- Install `just` (`cargo install just`) if you haven't already to use the [justfile](./justfile) in this project.
|
||||||
5. Commit changes. This will trigger pre-commit hooks that will run format, test and lint. If there are errors or
|
5. Commit changes. This will trigger pre-commit hooks that will run format, test and lint. If there are errors or
|
||||||
warnings from Clippy, please fix them.
|
warnings from Clippy, please fix them.
|
||||||
6. Push your code to a new branch named after the feature/bug/etc. you're adding. This will trigger pre-push hooks that
|
6. Push your code to a new branch named after the feature/bug/etc. you're adding. This will trigger pre-push hooks that
|
||||||
|
|||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
# Credits
|
||||||
|
|
||||||
|
## AIChat
|
||||||
|
Loki originally started as a fork of the fantastic
|
||||||
|
[AIChat CLI](https://github.com/sigoden/aichat). The initial goal was simply
|
||||||
|
to fix a bug in how MCP servers worked with AIChat, allowing different MCP
|
||||||
|
servers to be specified per agent. Since then, Loki has evolved far beyond
|
||||||
|
its original scope and grown into a passion project with a life of its own.
|
||||||
|
|
||||||
|
Today, Loki includes first-class MCP server support (for both local and remote
|
||||||
|
servers), a built-in vault for interpolating secrets in configuration files,
|
||||||
|
built-in agents and macros, dynamic tab completions, integrated custom
|
||||||
|
functions (no external `argc` dependency), improved documentation, and much
|
||||||
|
more with many more ideas planned for the future.
|
||||||
|
|
||||||
|
Loki is now developed and maintained as an independent project. Full credit
|
||||||
|
for the original foundation goes to the developers of the wonderful
|
||||||
|
AIChat project.
|
||||||
|
|
||||||
|
This project is not affiliated with or endorsed by the AIChat maintainers.
|
||||||
|
|
||||||
|
## AIChat
|
||||||
|
|
||||||
|
Loki originally began as a fork of [AIChat CLI](https://github.com/sigoden/aichat),
|
||||||
|
created and maintained by the AIChat contributors.
|
||||||
|
|
||||||
|
While Loki has since diverged significantly and is now developed as an
|
||||||
|
independent project, its early foundation and inspiration came from the
|
||||||
|
AIChat project.
|
||||||
|
|
||||||
|
AIChat is licensed under the MIT License.
|
||||||
@@ -245,15 +245,10 @@ The appearance of Loki can be modified using the following settings:
|
|||||||
---
|
---
|
||||||
|
|
||||||
## History
|
## History
|
||||||
Loki originally started as a fork of the fantastic [AIChat CLI](https://github.com/sigoden/aichat). The purpose was to
|
|
||||||
simply fix a bug in how MCP servers worked with AIChat so that I could specify different ones for agents. However, it
|
|
||||||
has since evolved far beyond that and become a passion project with a life of its own!
|
|
||||||
|
|
||||||
Loki now has first class MCP server support (with support for local and remote servers alike), a built-in vault for
|
Loki began as a fork of [AIChat CLI](https://github.com/sigoden/aichat) and has since evolved into an independent project.
|
||||||
interpolating secrets in configuration files, built-in agents, built-in macros, dynamic tab completions, integrated
|
|
||||||
custom functions (no `argc` dependency), improved documentation, and much more with many more plans for the future!
|
|
||||||
|
|
||||||
The original kudos goes out to all the developers of the wonderful AIChat project!
|
See [CREDITS.md](./CREDITS.md) for full attribution and background.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -507,6 +507,7 @@ open_link() {
|
|||||||
|
|
||||||
guard_operation() {
|
guard_operation() {
|
||||||
if [[ -t 1 ]]; then
|
if [[ -t 1 ]]; then
|
||||||
|
if [[ -z "$AUTO_CONFIRM" ]]; then
|
||||||
ans="$(confirm "${1:-Are you sure you want to continue?}")"
|
ans="$(confirm "${1:-Are you sure you want to continue?}")"
|
||||||
|
|
||||||
if [[ "$ans" == 0 ]]; then
|
if [[ "$ans" == 0 ]]; then
|
||||||
@@ -514,6 +515,7 @@ guard_operation() {
|
|||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
fi
|
fi
|
||||||
|
fi
|
||||||
}
|
}
|
||||||
|
|
||||||
# Here is an example of a patch block that can be applied to modify the file to request the user's name:
|
# Here is an example of a patch block that can be applied to modify the file to request the user's name:
|
||||||
@@ -657,7 +659,7 @@ guard_path() {
|
|||||||
path="$(_to_real_path "$1")"
|
path="$(_to_real_path "$1")"
|
||||||
confirmation_prompt="$2"
|
confirmation_prompt="$2"
|
||||||
|
|
||||||
if [[ ! "$path" == "$(pwd)"* ]]; then
|
if [[ ! "$path" == "$(pwd)"* && -z "$AUTO_CONFIRM" ]]; then
|
||||||
ans="$(confirm "$confirmation_prompt")"
|
ans="$(confirm "$confirmation_prompt")"
|
||||||
|
|
||||||
if [[ "$ans" == 0 ]]; then
|
if [[ "$ans" == 0 ]]; then
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ loki --info | grep 'config_dir' | awk '{print $2}'
|
|||||||
- [Files and Directory Related Variables](#files-and-directory-related-variables)
|
- [Files and Directory Related Variables](#files-and-directory-related-variables)
|
||||||
- [Agent Related Variables](#agent-related-variables)
|
- [Agent Related Variables](#agent-related-variables)
|
||||||
- [Logging Related Variables](#logging-related-variables)
|
- [Logging Related Variables](#logging-related-variables)
|
||||||
|
- [Miscellaneous Variables](#miscellaneous-variables)
|
||||||
<!--toc:end-->
|
<!--toc:end-->
|
||||||
|
|
||||||
---
|
---
|
||||||
@@ -104,3 +105,8 @@ The following variables can be used to change the log level of Loki or the locat
|
|||||||
|
|
||||||
**Pro-Tip:** You can always tail the Loki logs using the `--tail-logs` flag. If you need to disable color output, you
|
**Pro-Tip:** You can always tail the Loki logs using the `--tail-logs` flag. If you need to disable color output, you
|
||||||
can also pass the `--disable-log-colors` flag as well.
|
can also pass the `--disable-log-colors` flag as well.
|
||||||
|
|
||||||
|
## Miscellaneous Variables
|
||||||
|
| Environment Variable | Description | Default Value |
|
||||||
|
|----------------------|--------------------------------------------------------------------------------------------------|---------------|
|
||||||
|
| `AUTO_CONFIRM` | Bypass all `guard_*` checks in the bash prompt helpers; useful for agent composition and routing | |
|
||||||
@@ -207,7 +207,9 @@ open_link https://www.google.com
|
|||||||
```
|
```
|
||||||
|
|
||||||
### guard_operation
|
### guard_operation
|
||||||
Prompt for permission to run an operation
|
Prompt for permission to run an operation.
|
||||||
|
|
||||||
|
Can be disabled by setting the environment variable `AUTO_CONFIRM`.
|
||||||
|
|
||||||
**Example:**
|
**Example:**
|
||||||
```bash
|
```bash
|
||||||
@@ -216,7 +218,9 @@ _run_sql
|
|||||||
```
|
```
|
||||||
|
|
||||||
### guard_path
|
### guard_path
|
||||||
Prompt for permission to perform path operations
|
Prompt for permission to perform path operations.
|
||||||
|
|
||||||
|
Can be disabled by setting the environment variable `AUTO_CONFIRM`.
|
||||||
|
|
||||||
**Example:***
|
**Example:***
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# List all recipes
|
||||||
|
default:
|
||||||
|
@just --list
|
||||||
|
|
||||||
|
# Run all tests
|
||||||
|
[group: 'test']
|
||||||
|
test:
|
||||||
|
cargo test --all
|
||||||
|
|
||||||
|
# See what linter errors and warnings are unaddressed
|
||||||
|
[group: 'style']
|
||||||
|
lint:
|
||||||
|
cargo clippy --all
|
||||||
|
|
||||||
|
# Run Rustfmt against all source files
|
||||||
|
[group: 'style']
|
||||||
|
fmt:
|
||||||
|
cargo fmt --all
|
||||||
|
|
||||||
|
# Build the project for the current system architecture
|
||||||
|
# (Gets stored at ./target/[debug|release]/loki)
|
||||||
|
[group: 'build']
|
||||||
|
[arg('build_type', pattern="debug|release")]
|
||||||
|
build build_type='debug':
|
||||||
|
@cargo build {{ if build_type == "release" { "--release" } else { "" } }}
|
||||||
+34
@@ -290,6 +290,32 @@
|
|||||||
thinking:
|
thinking:
|
||||||
type: enabled
|
type: enabled
|
||||||
budget_tokens: 16000
|
budget_tokens: 16000
|
||||||
|
- name: claude-opus-4-5-20251101
|
||||||
|
type: chat
|
||||||
|
max_input_tokens: 200000
|
||||||
|
input_price: 15.0
|
||||||
|
output_price: 75.0
|
||||||
|
max_output_tokens: 8192
|
||||||
|
require_max_tokens: true
|
||||||
|
supports_vision: true
|
||||||
|
supports_function_calling: true
|
||||||
|
- name: claude-opus-4-5-20251101:thinking
|
||||||
|
type: chat
|
||||||
|
real_name: claude-opus-4-5-20251101
|
||||||
|
max_input_tokens: 200000
|
||||||
|
input_price: 15.0
|
||||||
|
output_price: 75.0
|
||||||
|
patch:
|
||||||
|
body:
|
||||||
|
temperature: null
|
||||||
|
top_p: null
|
||||||
|
thinking:
|
||||||
|
type: enabled
|
||||||
|
budget_tokens: 16000
|
||||||
|
max_output_tokens: 24000
|
||||||
|
require_max_tokens: true
|
||||||
|
supports_vision: true
|
||||||
|
supports_function_calling: true
|
||||||
- name: claude-opus-4-1-20250805
|
- name: claude-opus-4-1-20250805
|
||||||
max_input_tokens: 200000
|
max_input_tokens: 200000
|
||||||
max_output_tokens: 8192
|
max_output_tokens: 8192
|
||||||
@@ -633,6 +659,14 @@
|
|||||||
# - https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/gemini
|
# - https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/gemini
|
||||||
- provider: vertexai
|
- provider: vertexai
|
||||||
models:
|
models:
|
||||||
|
- name: gemini-3-pro-preview
|
||||||
|
hipaa_safe: true
|
||||||
|
max_input_tokens: 1048576
|
||||||
|
max_output_tokens: 65536
|
||||||
|
input_price: 0
|
||||||
|
output_price: 0
|
||||||
|
supports_vision: true
|
||||||
|
supports_function_calling: true
|
||||||
- name: gemini-2.5-flash
|
- name: gemini-2.5-flash
|
||||||
max_input_tokens: 1048576
|
max_input_tokens: 1048576
|
||||||
max_output_tokens: 65536
|
max_output_tokens: 65536
|
||||||
|
|||||||
@@ -234,7 +234,7 @@ async fn chat_completions_streaming(
|
|||||||
}
|
}
|
||||||
let arguments: Value =
|
let arguments: Value =
|
||||||
function_arguments.parse().with_context(|| {
|
function_arguments.parse().with_context(|| {
|
||||||
format!("Tool call '{function_name}' have non-JSON arguments '{function_arguments}'")
|
format!("Tool call '{function_name}' has non-JSON arguments '{function_arguments}'")
|
||||||
})?;
|
})?;
|
||||||
handler.tool_call(ToolCall::new(
|
handler.tool_call(ToolCall::new(
|
||||||
function_name.clone(),
|
function_name.clone(),
|
||||||
@@ -272,7 +272,7 @@ async fn chat_completions_streaming(
|
|||||||
function_arguments = String::from("{}");
|
function_arguments = String::from("{}");
|
||||||
}
|
}
|
||||||
let arguments: Value = function_arguments.parse().with_context(|| {
|
let arguments: Value = function_arguments.parse().with_context(|| {
|
||||||
format!("Tool call '{function_name}' have non-JSON arguments '{function_arguments}'")
|
format!("Tool call '{function_name}' has non-JSON arguments '{function_arguments}'")
|
||||||
})?;
|
})?;
|
||||||
handler.tool_call(ToolCall::new(
|
handler.tool_call(ToolCall::new(
|
||||||
function_name.clone(),
|
function_name.clone(),
|
||||||
|
|||||||
@@ -93,10 +93,13 @@ pub async fn claude_chat_completions_streaming(
|
|||||||
data["content_block"]["id"].as_str(),
|
data["content_block"]["id"].as_str(),
|
||||||
) {
|
) {
|
||||||
if !function_name.is_empty() {
|
if !function_name.is_empty() {
|
||||||
let arguments: Value =
|
let arguments: Value = if function_arguments.is_empty() {
|
||||||
|
json!({})
|
||||||
|
} else {
|
||||||
function_arguments.parse().with_context(|| {
|
function_arguments.parse().with_context(|| {
|
||||||
format!("Tool call '{function_name}' have non-JSON arguments '{function_arguments}'")
|
format!("Tool call '{function_name}' has non-JSON arguments '{function_arguments}'")
|
||||||
})?;
|
})?
|
||||||
|
};
|
||||||
handler.tool_call(ToolCall::new(
|
handler.tool_call(ToolCall::new(
|
||||||
function_name.clone(),
|
function_name.clone(),
|
||||||
arguments,
|
arguments,
|
||||||
@@ -134,7 +137,7 @@ pub async fn claude_chat_completions_streaming(
|
|||||||
json!({})
|
json!({})
|
||||||
} else {
|
} else {
|
||||||
function_arguments.parse().with_context(|| {
|
function_arguments.parse().with_context(|| {
|
||||||
format!("Tool call '{function_name}' have non-JSON arguments '{function_arguments}'")
|
format!("Tool call '{function_name}' has non-JSON arguments '{function_arguments}'")
|
||||||
})?
|
})?
|
||||||
};
|
};
|
||||||
handler.tool_call(ToolCall::new(
|
handler.tool_call(ToolCall::new(
|
||||||
@@ -286,7 +289,7 @@ pub fn claude_build_chat_completions_body(
|
|||||||
body["tools"] = functions
|
body["tools"] = functions
|
||||||
.iter()
|
.iter()
|
||||||
.map(|v| {
|
.map(|v| {
|
||||||
if v.parameters.type_value.is_none() {
|
if v.parameters.is_empty_properties() {
|
||||||
json!({
|
json!({
|
||||||
"name": v.name,
|
"name": v.name,
|
||||||
"description": v.description,
|
"description": v.description,
|
||||||
|
|||||||
@@ -167,7 +167,7 @@ async fn chat_completions_streaming(
|
|||||||
"tool-call-end" => {
|
"tool-call-end" => {
|
||||||
if !function_name.is_empty() {
|
if !function_name.is_empty() {
|
||||||
let arguments: Value = function_arguments.parse().with_context(|| {
|
let arguments: Value = function_arguments.parse().with_context(|| {
|
||||||
format!("Tool call '{function_name}' have non-JSON arguments '{function_arguments}'")
|
format!("Tool call '{function_name}' has non-JSON arguments '{function_arguments}'")
|
||||||
})?;
|
})?;
|
||||||
handler.tool_call(ToolCall::new(
|
handler.tool_call(ToolCall::new(
|
||||||
function_name.clone(),
|
function_name.clone(),
|
||||||
@@ -230,7 +230,7 @@ fn extract_chat_completions(data: &Value) -> Result<ChatCompletionsOutput> {
|
|||||||
call["id"].as_str(),
|
call["id"].as_str(),
|
||||||
) {
|
) {
|
||||||
let arguments: Value = arguments.parse().with_context(|| {
|
let arguments: Value = arguments.parse().with_context(|| {
|
||||||
format!("Tool call '{name}' have non-JSON arguments '{arguments}'")
|
format!("Tool call '{name}' has non-JSON arguments '{arguments}'")
|
||||||
})?;
|
})?;
|
||||||
tool_calls.push(ToolCall::new(
|
tool_calls.push(ToolCall::new(
|
||||||
name.to_string(),
|
name.to_string(),
|
||||||
|
|||||||
+14
-8
@@ -433,10 +433,13 @@ pub async fn call_chat_completions(
|
|||||||
client.global_config().read().print_markdown(&text)?;
|
client.global_config().read().print_markdown(&text)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Ok((
|
let tool_results = eval_tool_calls(client.global_config(), tool_calls).await?;
|
||||||
text,
|
if let Some(tracker) = client.global_config().write().tool_call_tracker.as_mut() {
|
||||||
eval_tool_calls(client.global_config(), tool_calls).await?,
|
tool_results
|
||||||
))
|
.iter()
|
||||||
|
.for_each(|res| tracker.record_call(res.call.clone()));
|
||||||
|
}
|
||||||
|
Ok((text, tool_results))
|
||||||
}
|
}
|
||||||
Err(err) => Err(err),
|
Err(err) => Err(err),
|
||||||
}
|
}
|
||||||
@@ -467,10 +470,13 @@ pub async fn call_chat_completions_streaming(
|
|||||||
if !text.is_empty() && !text.ends_with('\n') {
|
if !text.is_empty() && !text.ends_with('\n') {
|
||||||
println!();
|
println!();
|
||||||
}
|
}
|
||||||
Ok((
|
let tool_results = eval_tool_calls(client.global_config(), tool_calls).await?;
|
||||||
text,
|
if let Some(tracker) = client.global_config().write().tool_call_tracker.as_mut() {
|
||||||
eval_tool_calls(client.global_config(), tool_calls).await?,
|
tool_results
|
||||||
))
|
.iter()
|
||||||
|
.for_each(|res| tracker.record_call(res.call.clone()));
|
||||||
|
}
|
||||||
|
Ok((text, tool_results))
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
if !text.is_empty() {
|
if !text.is_empty() {
|
||||||
|
|||||||
@@ -228,7 +228,7 @@ macro_rules! config_get_fn {
|
|||||||
std::env::var(&env_name)
|
std::env::var(&env_name)
|
||||||
.ok()
|
.ok()
|
||||||
.or_else(|| self.config.$field_name.clone())
|
.or_else(|| self.config.$field_name.clone())
|
||||||
.ok_or_else(|| anyhow::anyhow!("Miss '{}'", stringify!($field_name)))
|
.ok_or_else(|| anyhow::anyhow!("Missing '{}'", stringify!($field_name)))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -164,7 +164,7 @@ pub async fn openai_chat_completions_streaming(
|
|||||||
function_arguments = String::from("{}");
|
function_arguments = String::from("{}");
|
||||||
}
|
}
|
||||||
let arguments: Value = function_arguments.parse().with_context(|| {
|
let arguments: Value = function_arguments.parse().with_context(|| {
|
||||||
format!("Tool call '{function_name}' have non-JSON arguments '{function_arguments}'")
|
format!("Tool call '{function_name}' has non-JSON arguments '{function_arguments}'")
|
||||||
})?;
|
})?;
|
||||||
handler.tool_call(ToolCall::new(
|
handler.tool_call(ToolCall::new(
|
||||||
function_name.clone(),
|
function_name.clone(),
|
||||||
@@ -370,7 +370,7 @@ pub fn openai_extract_chat_completions(data: &Value) -> Result<ChatCompletionsOu
|
|||||||
call["id"].as_str(),
|
call["id"].as_str(),
|
||||||
) {
|
) {
|
||||||
let arguments: Value = arguments.parse().with_context(|| {
|
let arguments: Value = arguments.parse().with_context(|| {
|
||||||
format!("Tool call '{name}' have non-JSON arguments '{arguments}'")
|
format!("Tool call '{name}' has non-JSON arguments '{arguments}'")
|
||||||
})?;
|
})?;
|
||||||
tool_calls.push(ToolCall::new(
|
tool_calls.push(ToolCall::new(
|
||||||
name.to_string(),
|
name.to_string(),
|
||||||
|
|||||||
+153
-2
@@ -13,6 +13,9 @@ pub struct SseHandler {
|
|||||||
abort_signal: AbortSignal,
|
abort_signal: AbortSignal,
|
||||||
buffer: String,
|
buffer: String,
|
||||||
tool_calls: Vec<ToolCall>,
|
tool_calls: Vec<ToolCall>,
|
||||||
|
last_tool_calls: Vec<ToolCall>,
|
||||||
|
max_call_repeats: usize,
|
||||||
|
call_repeat_chain_len: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SseHandler {
|
impl SseHandler {
|
||||||
@@ -22,11 +25,13 @@ impl SseHandler {
|
|||||||
abort_signal,
|
abort_signal,
|
||||||
buffer: String::new(),
|
buffer: String::new(),
|
||||||
tool_calls: Vec::new(),
|
tool_calls: Vec::new(),
|
||||||
|
last_tool_calls: Vec::new(),
|
||||||
|
max_call_repeats: 2,
|
||||||
|
call_repeat_chain_len: 3,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn text(&mut self, text: &str) -> Result<()> {
|
pub fn text(&mut self, text: &str) -> Result<()> {
|
||||||
// debug!("HandleText: {}", text);
|
|
||||||
if text.is_empty() {
|
if text.is_empty() {
|
||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
@@ -45,7 +50,6 @@ impl SseHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn done(&mut self) {
|
pub fn done(&mut self) {
|
||||||
// debug!("HandleDone");
|
|
||||||
let ret = self.sender.send(SseEvent::Done);
|
let ret = self.sender.send(SseEvent::Done);
|
||||||
if ret.is_err() {
|
if ret.is_err() {
|
||||||
if self.abort_signal.aborted() {
|
if self.abort_signal.aborted() {
|
||||||
@@ -56,14 +60,114 @@ impl SseHandler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn tool_call(&mut self, call: ToolCall) -> Result<()> {
|
pub fn tool_call(&mut self, call: ToolCall) -> Result<()> {
|
||||||
|
if self.is_call_loop(&call) {
|
||||||
|
let loop_message = self.create_loop_detection_message(&call);
|
||||||
|
return Err(anyhow!(loop_message));
|
||||||
|
}
|
||||||
|
|
||||||
|
if self.last_tool_calls.len() == self.call_repeat_chain_len * self.max_call_repeats {
|
||||||
|
self.last_tool_calls.remove(0);
|
||||||
|
}
|
||||||
|
self.last_tool_calls.push(call.clone());
|
||||||
|
|
||||||
self.tool_calls.push(call);
|
self.tool_calls.push(call);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn is_call_loop(&self, new_call: &ToolCall) -> bool {
|
||||||
|
if self.last_tool_calls.len() < self.call_repeat_chain_len {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(last_call) = self.last_tool_calls.last()
|
||||||
|
&& self.calls_match(last_call, new_call)
|
||||||
|
{
|
||||||
|
let mut repeat_count = 1;
|
||||||
|
for i in (0..self.last_tool_calls.len()).rev() {
|
||||||
|
if i == 0 {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if self.calls_match(&self.last_tool_calls[i - 1], &self.last_tool_calls[i]) {
|
||||||
|
repeat_count += 1;
|
||||||
|
if repeat_count >= self.max_call_repeats {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let chain_start = self
|
||||||
|
.last_tool_calls
|
||||||
|
.len()
|
||||||
|
.saturating_sub(self.call_repeat_chain_len);
|
||||||
|
let chain = &self.last_tool_calls[chain_start..];
|
||||||
|
|
||||||
|
if chain.len() == self.call_repeat_chain_len {
|
||||||
|
let mut is_repeating = true;
|
||||||
|
for i in 0..chain.len() - 1 {
|
||||||
|
if !self.calls_match(&chain[i], &chain[i + 1]) {
|
||||||
|
is_repeating = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if is_repeating && self.calls_match(&chain[chain.len() - 1], new_call) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
false
|
||||||
|
}
|
||||||
|
|
||||||
|
fn calls_match(&self, call1: &ToolCall, call2: &ToolCall) -> bool {
|
||||||
|
call1.name == call2.name && call1.arguments == call2.arguments
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_loop_detection_message(&self, new_call: &ToolCall) -> String {
|
||||||
|
let mut message = String::from("⚠️ Call loop detected! ⚠️");
|
||||||
|
|
||||||
|
message.push_str(&format!(
|
||||||
|
"The call '{}' with arguments '{}' is repeating.\n",
|
||||||
|
new_call.name, new_call.arguments
|
||||||
|
));
|
||||||
|
|
||||||
|
if self.last_tool_calls.len() >= self.call_repeat_chain_len {
|
||||||
|
let chain_start = self
|
||||||
|
.last_tool_calls
|
||||||
|
.len()
|
||||||
|
.saturating_sub(self.call_repeat_chain_len);
|
||||||
|
let chain = &self.last_tool_calls[chain_start..];
|
||||||
|
|
||||||
|
message.push_str("The following sequence of calls is repeating:\n");
|
||||||
|
for (i, call) in chain.iter().enumerate() {
|
||||||
|
message.push_str(&format!(
|
||||||
|
" {}. {} with arguments {}\n",
|
||||||
|
i + 1,
|
||||||
|
call.name,
|
||||||
|
call.arguments
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
message.push_str("\nPlease move on to the next task in your sequence using the last output you got from the call or chain you are trying to re-execute. ");
|
||||||
|
message.push_str(
|
||||||
|
"Consider using different parameters or a different approach to avoid this loop.",
|
||||||
|
);
|
||||||
|
|
||||||
|
message
|
||||||
|
}
|
||||||
|
|
||||||
pub fn abort(&self) -> AbortSignal {
|
pub fn abort(&self) -> AbortSignal {
|
||||||
self.abort_signal.clone()
|
self.abort_signal.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
pub fn last_tool_calls(&self) -> &[ToolCall] {
|
||||||
|
&self.last_tool_calls
|
||||||
|
}
|
||||||
|
|
||||||
pub fn take(self) -> (String, Vec<ToolCall>) {
|
pub fn take(self) -> (String, Vec<ToolCall>) {
|
||||||
let Self {
|
let Self {
|
||||||
buffer, tool_calls, ..
|
buffer, tool_calls, ..
|
||||||
@@ -239,6 +343,53 @@ mod tests {
|
|||||||
use bytes::Bytes;
|
use bytes::Bytes;
|
||||||
use futures_util::stream;
|
use futures_util::stream;
|
||||||
use rand::Rng;
|
use rand::Rng;
|
||||||
|
use serde_json::json;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_last_tool_calls_ring_buffer() {
|
||||||
|
let (sender, _) = tokio::sync::mpsc::unbounded_channel();
|
||||||
|
let abort_signal = crate::utils::create_abort_signal();
|
||||||
|
let mut handler = SseHandler::new(sender, abort_signal);
|
||||||
|
|
||||||
|
for i in 0..15 {
|
||||||
|
let call = ToolCall::new(format!("test_function_{}", i), json!({"param": i}), None);
|
||||||
|
handler.tool_call(call.clone()).unwrap();
|
||||||
|
}
|
||||||
|
let lt_len = handler.call_repeat_chain_len * handler.max_call_repeats;
|
||||||
|
assert_eq!(handler.last_tool_calls().len(), lt_len);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
handler.last_tool_calls()[lt_len - 1].name,
|
||||||
|
"test_function_14"
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
handler.last_tool_calls()[0].name,
|
||||||
|
format!("test_function_{}", 14 - lt_len + 1)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_call_loop_detection() {
|
||||||
|
let (sender, _) = tokio::sync::mpsc::unbounded_channel();
|
||||||
|
let abort_signal = crate::utils::create_abort_signal();
|
||||||
|
let mut handler = SseHandler::new(sender, abort_signal);
|
||||||
|
|
||||||
|
handler.max_call_repeats = 2;
|
||||||
|
handler.call_repeat_chain_len = 3;
|
||||||
|
|
||||||
|
let call = ToolCall::new("test_function_loop".to_string(), json!({"param": 1}), None);
|
||||||
|
|
||||||
|
for _ in 0..3 {
|
||||||
|
handler.tool_call(call.clone()).unwrap();
|
||||||
|
}
|
||||||
|
|
||||||
|
let result = handler.tool_call(call.clone());
|
||||||
|
assert!(result.is_err());
|
||||||
|
let error_message = result.unwrap_err().to_string();
|
||||||
|
assert!(error_message.contains("Call loop detected!"));
|
||||||
|
assert!(error_message.contains("test_function_loop"));
|
||||||
|
}
|
||||||
|
|
||||||
fn split_chunks(text: &str) -> Vec<Vec<u8>> {
|
fn split_chunks(text: &str) -> Vec<Vec<u8>> {
|
||||||
let mut rng = rand::rng();
|
let mut rng = rand::rng();
|
||||||
|
|||||||
+22
-4
@@ -219,7 +219,14 @@ pub async fn gemini_chat_completions_streaming(
|
|||||||
part["functionCall"]["name"].as_str(),
|
part["functionCall"]["name"].as_str(),
|
||||||
part["functionCall"]["args"].as_object(),
|
part["functionCall"]["args"].as_object(),
|
||||||
) {
|
) {
|
||||||
handler.tool_call(ToolCall::new(name.to_string(), json!(args), None))?;
|
let thought_signature = part["thoughtSignature"]
|
||||||
|
.as_str()
|
||||||
|
.or_else(|| part["thought_signature"].as_str())
|
||||||
|
.map(|s| s.to_string());
|
||||||
|
handler.tool_call(
|
||||||
|
ToolCall::new(name.to_string(), json!(args), None)
|
||||||
|
.with_thought_signature(thought_signature),
|
||||||
|
)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if let Some("SAFETY") = data["promptFeedback"]["blockReason"]
|
} else if let Some("SAFETY") = data["promptFeedback"]["blockReason"]
|
||||||
@@ -280,7 +287,14 @@ fn gemini_extract_chat_completions_text(data: &Value) -> Result<ChatCompletionsO
|
|||||||
part["functionCall"]["name"].as_str(),
|
part["functionCall"]["name"].as_str(),
|
||||||
part["functionCall"]["args"].as_object(),
|
part["functionCall"]["args"].as_object(),
|
||||||
) {
|
) {
|
||||||
tool_calls.push(ToolCall::new(name.to_string(), json!(args), None));
|
let thought_signature = part["thoughtSignature"]
|
||||||
|
.as_str()
|
||||||
|
.or_else(|| part["thought_signature"].as_str())
|
||||||
|
.map(|s| s.to_string());
|
||||||
|
tool_calls.push(
|
||||||
|
ToolCall::new(name.to_string(), json!(args), None)
|
||||||
|
.with_thought_signature(thought_signature),
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -347,12 +361,16 @@ pub fn gemini_build_chat_completions_body(
|
|||||||
},
|
},
|
||||||
MessageContent::ToolCalls(MessageContentToolCalls { tool_results, .. }) => {
|
MessageContent::ToolCalls(MessageContentToolCalls { tool_results, .. }) => {
|
||||||
let model_parts: Vec<Value> = tool_results.iter().map(|tool_result| {
|
let model_parts: Vec<Value> = tool_results.iter().map(|tool_result| {
|
||||||
json!({
|
let mut part = json!({
|
||||||
"functionCall": {
|
"functionCall": {
|
||||||
"name": tool_result.call.name,
|
"name": tool_result.call.name,
|
||||||
"args": tool_result.call.arguments,
|
"args": tool_result.call.arguments,
|
||||||
}
|
}
|
||||||
})
|
});
|
||||||
|
if let Some(sig) = &tool_result.call.thought_signature {
|
||||||
|
part["thoughtSignature"] = json!(sig);
|
||||||
|
}
|
||||||
|
part
|
||||||
}).collect();
|
}).collect();
|
||||||
let function_parts: Vec<Value> = tool_results.into_iter().map(|tool_result| {
|
let function_parts: Vec<Value> = tool_results.into_iter().map(|tool_result| {
|
||||||
json!({
|
json!({
|
||||||
|
|||||||
@@ -204,6 +204,7 @@ impl Agent {
|
|||||||
|
|
||||||
pub fn init_agent_variables(
|
pub fn init_agent_variables(
|
||||||
agent_variables: &[AgentVariable],
|
agent_variables: &[AgentVariable],
|
||||||
|
pre_set_variables: Option<&AgentVariables>,
|
||||||
no_interaction: bool,
|
no_interaction: bool,
|
||||||
) -> Result<AgentVariables> {
|
) -> Result<AgentVariables> {
|
||||||
let mut output = IndexMap::new();
|
let mut output = IndexMap::new();
|
||||||
@@ -214,6 +215,10 @@ impl Agent {
|
|||||||
let mut unset_variables = vec![];
|
let mut unset_variables = vec![];
|
||||||
for agent_variable in agent_variables {
|
for agent_variable in agent_variables {
|
||||||
let key = agent_variable.name.clone();
|
let key = agent_variable.name.clone();
|
||||||
|
if let Some(value) = pre_set_variables.and_then(|v| v.get(&key)) {
|
||||||
|
output.insert(key, value.clone());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
if let Some(value) = agent_variable.default.clone() {
|
if let Some(value) = agent_variable.default.clone() {
|
||||||
output.insert(key, value);
|
output.insert(key, value);
|
||||||
continue;
|
continue;
|
||||||
|
|||||||
+14
-5
@@ -17,7 +17,7 @@ use crate::client::{
|
|||||||
ClientConfig, MessageContentToolCalls, Model, ModelType, OPENAI_COMPATIBLE_PROVIDERS,
|
ClientConfig, MessageContentToolCalls, Model, ModelType, OPENAI_COMPATIBLE_PROVIDERS,
|
||||||
ProviderModels, create_client_config, list_client_types, list_models,
|
ProviderModels, create_client_config, list_client_types, list_models,
|
||||||
};
|
};
|
||||||
use crate::function::{FunctionDeclaration, Functions, ToolResult};
|
use crate::function::{FunctionDeclaration, Functions, ToolCallTracker, ToolResult};
|
||||||
use crate::rag::Rag;
|
use crate::rag::Rag;
|
||||||
use crate::render::{MarkdownRender, RenderOptions};
|
use crate::render::{MarkdownRender, RenderOptions};
|
||||||
use crate::utils::*;
|
use crate::utils::*;
|
||||||
@@ -199,6 +199,8 @@ pub struct Config {
|
|||||||
pub rag: Option<Arc<Rag>>,
|
pub rag: Option<Arc<Rag>>,
|
||||||
#[serde(skip)]
|
#[serde(skip)]
|
||||||
pub agent: Option<Agent>,
|
pub agent: Option<Agent>,
|
||||||
|
#[serde(skip)]
|
||||||
|
pub(crate) tool_call_tracker: Option<ToolCallTracker>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for Config {
|
impl Default for Config {
|
||||||
@@ -271,6 +273,7 @@ impl Default for Config {
|
|||||||
session: None,
|
session: None,
|
||||||
rag: None,
|
rag: None,
|
||||||
agent: None,
|
agent: None,
|
||||||
|
tool_call_tracker: Some(ToolCallTracker::default()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2607,8 +2610,11 @@ impl Config {
|
|||||||
None => return Ok(()),
|
None => return Ok(()),
|
||||||
};
|
};
|
||||||
if !agent.defined_variables().is_empty() && agent.shared_variables().is_empty() {
|
if !agent.defined_variables().is_empty() && agent.shared_variables().is_empty() {
|
||||||
let new_variables =
|
let new_variables = Agent::init_agent_variables(
|
||||||
Agent::init_agent_variables(agent.defined_variables(), self.info_flag)?;
|
agent.defined_variables(),
|
||||||
|
self.agent_variables.as_ref(),
|
||||||
|
self.info_flag,
|
||||||
|
)?;
|
||||||
agent.set_shared_variables(new_variables);
|
agent.set_shared_variables(new_variables);
|
||||||
}
|
}
|
||||||
if !self.info_flag {
|
if !self.info_flag {
|
||||||
@@ -2626,8 +2632,11 @@ impl Config {
|
|||||||
let shared_variables = agent.shared_variables().clone();
|
let shared_variables = agent.shared_variables().clone();
|
||||||
let session_variables =
|
let session_variables =
|
||||||
if !agent.defined_variables().is_empty() && shared_variables.is_empty() {
|
if !agent.defined_variables().is_empty() && shared_variables.is_empty() {
|
||||||
let new_variables =
|
let new_variables = Agent::init_agent_variables(
|
||||||
Agent::init_agent_variables(agent.defined_variables(), self.info_flag)?;
|
agent.defined_variables(),
|
||||||
|
self.agent_variables.as_ref(),
|
||||||
|
self.info_flag,
|
||||||
|
)?;
|
||||||
agent.set_shared_variables(new_variables.clone());
|
agent.set_shared_variables(new_variables.clone());
|
||||||
new_variables
|
new_variables
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+132
-5
@@ -15,6 +15,7 @@ use indoc::formatdoc;
|
|||||||
use rust_embed::Embed;
|
use rust_embed::Embed;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::{Value, json};
|
use serde_json::{Value, json};
|
||||||
|
use std::collections::VecDeque;
|
||||||
use std::ffi::OsStr;
|
use std::ffi::OsStr;
|
||||||
use std::fs::File;
|
use std::fs::File;
|
||||||
use std::io::Write;
|
use std::io::Write;
|
||||||
@@ -90,6 +91,19 @@ pub async fn eval_tool_calls(
|
|||||||
}
|
}
|
||||||
let mut is_all_null = true;
|
let mut is_all_null = true;
|
||||||
for call in calls {
|
for call in calls {
|
||||||
|
if let Some(checker) = &config.read().tool_call_tracker
|
||||||
|
&& let Some(msg) = checker.check_loop(&call.clone())
|
||||||
|
{
|
||||||
|
let dup_msg = format!("{{\"tool_call_loop_alert\":{}}}", &msg.trim());
|
||||||
|
println!(
|
||||||
|
"{}",
|
||||||
|
warning_text(format!("{}: ⚠️ Tool-call loop detected! ⚠️", &call.name).as_str())
|
||||||
|
);
|
||||||
|
let val = json!(dup_msg);
|
||||||
|
output.push(ToolResult::new(call, val));
|
||||||
|
is_all_null = false;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
let mut result = call.eval(config).await?;
|
let mut result = call.eval(config).await?;
|
||||||
if result.is_null() {
|
if result.is_null() {
|
||||||
result = json!("DONE");
|
result = json!("DONE");
|
||||||
@@ -756,6 +770,10 @@ pub struct ToolCall {
|
|||||||
pub name: String,
|
pub name: String,
|
||||||
pub arguments: Value,
|
pub arguments: Value,
|
||||||
pub id: Option<String>,
|
pub id: Option<String>,
|
||||||
|
/// Gemini 3's thought signature for stateful reasoning in function calling.
|
||||||
|
/// Must be preserved and sent back when submitting function responses.
|
||||||
|
#[serde(skip_serializing_if = "Option::is_none")]
|
||||||
|
pub thought_signature: Option<String>,
|
||||||
}
|
}
|
||||||
|
|
||||||
type CallConfig = (String, String, Vec<String>, HashMap<String, String>);
|
type CallConfig = (String, String, Vec<String>, HashMap<String, String>);
|
||||||
@@ -785,9 +803,15 @@ impl ToolCall {
|
|||||||
name,
|
name,
|
||||||
arguments,
|
arguments,
|
||||||
id,
|
id,
|
||||||
|
thought_signature: None,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn with_thought_signature(mut self, thought_signature: Option<String>) -> Self {
|
||||||
|
self.thought_signature = thought_signature;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn eval(&self, config: &GlobalConfig) -> Result<Value> {
|
pub async fn eval(&self, config: &GlobalConfig) -> Result<Value> {
|
||||||
let (call_name, cmd_name, mut cmd_args, envs) = match &config.read().agent {
|
let (call_name, cmd_name, mut cmd_args, envs) = match &config.read().agent {
|
||||||
Some(agent) => self.extract_call_config_from_agent(config, agent)?,
|
Some(agent) => self.extract_call_config_from_agent(config, agent)?,
|
||||||
@@ -831,11 +855,14 @@ impl ToolCall {
|
|||||||
_ if cmd_name.starts_with(MCP_INVOKE_META_FUNCTION_NAME_PREFIX) => {
|
_ if cmd_name.starts_with(MCP_INVOKE_META_FUNCTION_NAME_PREFIX) => {
|
||||||
Self::invoke_mcp_tool(config, &cmd_name, &json_data).await?
|
Self::invoke_mcp_tool(config, &cmd_name, &json_data).await?
|
||||||
}
|
}
|
||||||
_ => match run_llm_function(cmd_name, cmd_args, envs, agent_name)? {
|
_ => match run_llm_function(cmd_name, cmd_args, envs, agent_name) {
|
||||||
Some(contents) => serde_json::from_str(&contents)
|
Ok(Some(contents)) => serde_json::from_str(&contents)
|
||||||
.ok()
|
.ok()
|
||||||
.unwrap_or_else(|| json!({"output": contents})),
|
.unwrap_or_else(|| json!({"output": contents})),
|
||||||
None => Value::Null,
|
Ok(None) => Value::Null,
|
||||||
|
Err(e) => serde_json::from_str(&e.to_string())
|
||||||
|
.ok()
|
||||||
|
.unwrap_or_else(|| json!({"output": e.to_string()})),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -968,7 +995,9 @@ pub fn run_llm_function(
|
|||||||
agent_name: Option<String>,
|
agent_name: Option<String>,
|
||||||
) -> Result<Option<String>> {
|
) -> Result<Option<String>> {
|
||||||
let mut bin_dirs: Vec<PathBuf> = vec![];
|
let mut bin_dirs: Vec<PathBuf> = vec![];
|
||||||
|
let mut command_name = cmd_name.clone();
|
||||||
if let Some(agent_name) = agent_name {
|
if let Some(agent_name) = agent_name {
|
||||||
|
command_name = cmd_args[0].clone();
|
||||||
let dir = Config::agent_bin_dir(&agent_name);
|
let dir = Config::agent_bin_dir(&agent_name);
|
||||||
if dir.exists() {
|
if dir.exists() {
|
||||||
bin_dirs.push(dir);
|
bin_dirs.push(dir);
|
||||||
@@ -991,9 +1020,13 @@ pub fn run_llm_function(
|
|||||||
let cmd_name = polyfill_cmd_name(&cmd_name, &bin_dirs);
|
let cmd_name = polyfill_cmd_name(&cmd_name, &bin_dirs);
|
||||||
|
|
||||||
let exit_code = run_command(&cmd_name, &cmd_args, Some(envs))
|
let exit_code = run_command(&cmd_name, &cmd_args, Some(envs))
|
||||||
.map_err(|err| anyhow!("Unable to run {cmd_name}, {err}"))?;
|
.map_err(|err| anyhow!("Unable to run {command_name}, {err}"))?;
|
||||||
if exit_code != 0 {
|
if exit_code != 0 {
|
||||||
bail!("Tool call exited with {exit_code}");
|
let tool_error_message =
|
||||||
|
format!("⚠️ Tool call '{command_name}' threw exit code {exit_code} ⚠️");
|
||||||
|
println!("{}", warning_text(&tool_error_message));
|
||||||
|
let tool_error_json = format!("{{\"tool_call_error\":\"{}\"}}", &tool_error_message);
|
||||||
|
return Ok(Some(tool_error_json));
|
||||||
}
|
}
|
||||||
let mut output = None;
|
let mut output = None;
|
||||||
if temp_file.exists() {
|
if temp_file.exists() {
|
||||||
@@ -1022,3 +1055,97 @@ fn polyfill_cmd_name<T: AsRef<Path>>(cmd_name: &str, bin_dir: &[T]) -> String {
|
|||||||
}
|
}
|
||||||
cmd_name
|
cmd_name
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ToolCallTracker {
|
||||||
|
last_calls: VecDeque<ToolCall>,
|
||||||
|
max_repeats: usize,
|
||||||
|
chain_len: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ToolCallTracker {
|
||||||
|
pub fn new(max_repeats: usize, chain_len: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
last_calls: VecDeque::new(),
|
||||||
|
max_repeats,
|
||||||
|
chain_len,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn default() -> Self {
|
||||||
|
Self::new(2, 3)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn check_loop(&self, new_call: &ToolCall) -> Option<String> {
|
||||||
|
if self.last_calls.len() < self.max_repeats {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some(last) = self.last_calls.back()
|
||||||
|
&& self.calls_match(last, new_call)
|
||||||
|
{
|
||||||
|
let mut repeat_count = 1;
|
||||||
|
for i in (1..self.last_calls.len()).rev() {
|
||||||
|
if self.calls_match(&self.last_calls[i - 1], &self.last_calls[i]) {
|
||||||
|
repeat_count += 1;
|
||||||
|
if repeat_count >= self.max_repeats {
|
||||||
|
return Some(self.create_loop_message());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let start = self.last_calls.len().saturating_sub(self.chain_len);
|
||||||
|
let chain: Vec<_> = self.last_calls.iter().skip(start).collect();
|
||||||
|
if chain.len() == self.chain_len {
|
||||||
|
let mut is_repeating = true;
|
||||||
|
for i in 0..chain.len() - 1 {
|
||||||
|
if !self.calls_match(chain[i], chain[i + 1]) {
|
||||||
|
is_repeating = false;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if is_repeating && self.calls_match(chain[chain.len() - 1], new_call) {
|
||||||
|
return Some(self.create_loop_message());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
fn calls_match(&self, a: &ToolCall, b: &ToolCall) -> bool {
|
||||||
|
a.name == b.name && a.arguments == b.arguments
|
||||||
|
}
|
||||||
|
|
||||||
|
fn create_loop_message(&self) -> String {
|
||||||
|
let message = r#"{"error":{"message":"⚠️ Tool-call loop detected! ⚠️","code":400,"param":"Use the output of the last call to this function and parameter-set then move on to the next step of workflow, change tools/parameters called, or request assistance in the conversation sream"}}"#;
|
||||||
|
|
||||||
|
if self.last_calls.len() >= self.chain_len {
|
||||||
|
let start = self.last_calls.len().saturating_sub(self.chain_len);
|
||||||
|
let chain: Vec<_> = self.last_calls.iter().skip(start).collect();
|
||||||
|
let mut loopset = "[".to_string();
|
||||||
|
for c in chain {
|
||||||
|
loopset +=
|
||||||
|
format!("{{\"name\":{},\"parameters\":{}}},", c.name, c.arguments).as_str();
|
||||||
|
}
|
||||||
|
let _ = loopset.pop();
|
||||||
|
loopset.push(']');
|
||||||
|
format!(
|
||||||
|
"{},\"call_history\":{}}}}}",
|
||||||
|
&message[..(&message.len() - 2)],
|
||||||
|
loopset
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
message.to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn record_call(&mut self, call: ToolCall) {
|
||||||
|
if self.last_calls.len() >= self.chain_len * self.max_repeats {
|
||||||
|
self.last_calls.pop_front();
|
||||||
|
}
|
||||||
|
self.last_calls.push_back(call);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user