Skip to content
Closed
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
14 changes: 13 additions & 1 deletion ex_app/lib/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,16 @@
from ex_app.lib.all_tools.lib.tz import user_timezone_async
from ex_app.lib.all_tools.nextcloud_links import get_absolute_base_url
from ex_app.lib.all_tools.skills import list_skills_metadata
from ex_app.lib.context_window import CHARS_PER_TOKEN, MIN_CONTEXT_BUDGET, conversation_budget, render_transcripts, select_context, truncate_text
from ex_app.lib.context_window import (
CHARS_PER_TOKEN,
MIN_CONTEXT_BUDGET,
conversation_budget,
max_tool_result_chars,
render_transcripts,
select_context,
start_tool_result_budget,
truncate_text,
)
from ex_app.lib.graph import CONFIRM_TOOLS_NODE, AgentState, get_graph
from ex_app.lib.jsonplus import JsonPlusSerializer
from ex_app.lib.logger import log
Expand Down Expand Up @@ -180,6 +189,8 @@ async def react(
bound_model = ChatWithNextcloud(nc=nc, multimodal=multimodal).bind_tools(tools)
# The tool descriptions are sent with every request, so they count towards the context budget
tools_size = len(json.dumps(cast(ChatWithNextcloud, bound_model).tools))
# Lets tools that can size their answer stay below the size their results are shortened at
result_budget = start_tool_result_budget()

def tool_enabled(tool_name):
for tool in tools:
Expand Down Expand Up @@ -305,6 +316,7 @@ async def call_model(
f" budget of {context_budget}, so the request to the language model may exceed it."
" Raise the budget or disable some tools.",
)
result_budget.chars = max_tool_result_chars(conversation_budget(context_budget, reserved))
selection = select_context(state["messages"], context_budget, reserved)
update: dict[str, Any] = {"messages": []}
if selection.dropped:
Expand Down
36 changes: 34 additions & 2 deletions ex_app/lib/context_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
remaining turns, only the tool results that still do not fit are shortened.
"""
import json
from contextvars import ContextVar
from dataclasses import dataclass

from langchain_core.messages import AIMessage, BaseMessage
Expand Down Expand Up @@ -247,9 +248,40 @@ def _share_out(sizes: list[int], total: int, floor: int, ceiling: int) -> list[i
return shares


def _compact_current_turn(turn: list[BaseMessage], budget_chars: int) -> list[BaseMessage]:
def max_tool_result_chars(budget_chars: int) -> int:
"""How large a single tool result of the current turn may be before it is shortened"""
# A single tool result must not take up the whole budget
max_result_chars = budget_chars // 2
return budget_chars // 2


@dataclass
class ToolResultBudget:
"""The size a tool result can have without being shortened, for tools that can size their answer

Set by the agent for each request to the model and read by tools while they run, which happens in other
tasks of the same run: the object is shared, so they see the value of the latest request.
"""
chars: int | None = None


_tool_result_budget: ContextVar[ToolResultBudget | None] = ContextVar('tool_result_budget', default=None)


def start_tool_result_budget() -> ToolResultBudget:
"""A budget for the tool calls of the current run, to be updated by the agent"""
budget = ToolResultBudget()
_tool_result_budget.set(budget)
return budget


def tool_result_budget() -> int | None:
"""How many characters a tool result can have without being shortened, or None outside of a run"""
budget = _tool_result_budget.get()
return budget.chars if budget is not None else None


def _compact_current_turn(turn: list[BaseMessage], budget_chars: int) -> list[BaseMessage]:
max_result_chars = max_tool_result_chars(budget_chars)
capped = [_truncate_tool_message(message, max_result_chars, can_refetch=False) for message in turn]
if _turn_size(capped) <= budget_chars:
return capped
Expand Down
34 changes: 33 additions & 1 deletion tests/test_context_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,24 @@ def test_truncate_json_object_without_list_is_cut_as_text():
assert "characters omitted" in truncated


def test_tool_result_budget_is_shared_with_tasks_of_the_run():
from ex_app.lib.context_window import start_tool_result_budget, tool_result_budget

async def tool():
return tool_result_budget()

async def run():
budget = start_tool_result_budget()
# tools run in tasks of their own, created after the run started
before = await asyncio.create_task(tool())
budget.chars = 1234
after = await asyncio.create_task(tool())
return before, after

assert asyncio.run(run()) == (None, 1234)
assert tool_result_budget() is None


def test_split_turns():
messages = tool_turn(1, "x") + tool_turn(2, "y")
turns = split_turns(messages)
Expand Down Expand Up @@ -673,8 +691,22 @@ async def get_tools(nc):
setattr(obj, name, value)
return [t for t in scheduled if t["system_prompt"].startswith("You summarize")]

assert not run([])
budgets = []
original_start = agent.start_tool_result_budget

def start_tool_result_budget():
budget = original_start()
budgets.append(budget)
return budget

agent.start_tool_result_budget = start_tool_result_budget
try:
assert not run([])
finally:
agent.start_tool_result_budget = original_start
assert not any("context budget" in line for line in logged)
# tools learn what is left for a single result once the instructions and tools are counted
assert budgets and 0 < budgets[-1].chars < budget * CHARS_PER_TOKEN // 2

assert len(run([big_tool])) == 1
request = scheduled[-1]
Expand Down
Loading