Skip to content

Send a phone call from AI agent, in an API call. Or, directly call the bot from the configured phone number!

Python

perf: Remove LLM cache and lower at maximum the max_tokens params

Clémence Lesné6efdee8e2fca
diff --git a/helpers/call_llm.py b/helpers/call_llm.py
index 8d1ce53..cbe5e84 100644
--- a/helpers/call_llm.py
+++ b/helpers/call_llm.py
@@ -23,6 +23,7 @@ from helpers.llm_worker import (
completion_model_sync,
completion_stream,
completion_sync,
+ MaximumTokensReachedError,
ModelType,
safety_check,
SafetyCheckError,
@@ -386,11 +387,12 @@ async def _execute_llm_chat(
logger.debug(f"Tools: {tools}")
# Execute LLM inference
+ maximum_tokens_reached = False
content_buffer_pointer = 0
tool_calls_buffer: dict[int, MessageToolModel] = {}
try:
async for delta in completion_stream(
- max_tokens=350,
+ max_tokens=107, # Lowest possible value for 90% of the cases, if not sufficient, retry will be triggered, 100 tokens ~= 75 words, 20 words ~= 1 sentence, 3 sentences ~= 107 tokens
messages=call.messages,
system=system,
tools=tools,
@@ -409,9 +411,12 @@ async def _execute_llm_chat(
):
content_buffer_pointer += len(sentence)
plugins.style = await _content_callback(sentence, plugins.style)
+ except MaximumTokensReachedError:
+ logger.warning("Maximum tokens reached for this completion, retry asked")
+ maximum_tokens_reached = True
except APIError as e:
logger.warning(f"OpenAI API call error: {e}")
- return True, True, call
+ return True, True, call # Error, retry
# Flush the remaining buffer
if content_buffer_pointer < len(content_full):
@@ -435,12 +440,12 @@ async def _execute_llm_chat(
tool_call.function_name == "multi_tool_use.parallel" for tool_call in tool_calls
):
logger.warning(f'LLM send back invalid tool schema "multi_tool_use.parallel"')
- return True, True, call
+ return True, True, call # Error, retry
# OpenAI GPT-4 Turbo tends to return empty content, in that case, retry within limits
if not content_full and not tool_calls:
logger.warning("Empty content, retrying")
- return True, True, call
+ return True, True, call # Error, retry
# Execute tools
tool_tasks = [tool_call.execute_function(plugins) for tool_call in tool_calls]
@@ -462,8 +467,10 @@ async def _execute_llm_chat(
)
call.messages.append(message)
- # Recusive call if needed
- if tool_calls:
+ if tool_calls: # Recusive call if needed
return False, True, call
- return False, False, call
+ if maximum_tokens_reached: # Retry if maximum tokens reached
+ return False, True, call # TODO: Should we notify an error?
+
+ return False, False, call # No error, no retry
diff --git a/helpers/llm_worker.py b/helpers/llm_worker.py
index 17695d2..d37e10d 100644
--- a/helpers/llm_worker.py
+++ b/helpers/llm_worker.py
@@ -69,14 +69,11 @@ _contentsafety_client: Optional[ContentSafetyClient] = None
class SafetyCheckError(Exception):
- message: str
+ pass
- def __init__(self, message: str) -> None:
- self.message = message
- super().__init__(message)
- def __str__(self) -> str:
- return self.message
+class MaximumTokensReachedError(Exception):
+ pass
_retried_exceptions = [
@@ -152,19 +149,6 @@ async def _completion_stream_worker(
"""
Returns a stream of completions.
"""
- # Try cache
- cache_key = f"{__name__}-completion_stream-{_llm_key(is_fast)}-{system}-{tools}-{messages}-{max_tokens}"
- cached = await _cache.aget(cache_key)
- if cached:
- try:
- for chunck in TypeAdapter(list[ChoiceDelta]).validate_json(cached):
- yield chunck
- return
- except ValidationError as e:
- logger.debug(f"Parsing error: {e.errors()}")
-
- # Try live
- to_cache: list[ChoiceDelta] = []
client, platform = _use_llm(is_fast)
extra = {}
if tools:
@@ -187,6 +171,7 @@ async def _completion_stream_worker(
"temperature": 0, # Most focused and deterministic
**extra,
} # Shared kwargs for both streaming and non-streaming
+ maximum_tokens_reached = False
if platform.streaming: # Streaming
stream: AsyncStream[ChatCompletionChunk] = await client.chat.completions.create(
@@ -204,9 +189,9 @@ async def _completion_stream_worker(
)
if choice.finish_reason == "length":
logger.warning(f"Maximum tokens reached {max_tokens}, should be fixed")
+ maximum_tokens_reached = True
delta = choice.delta
yield delta
- to_cache.append(delta)
else: # Non-streaming, emulate streaming with a single completion
completion: ChatCompletion = await client.chat.completions.create(**chat_kwargs)
@@ -217,6 +202,7 @@ async def _completion_stream_worker(
)
if choice.finish_reason == "length":
logger.warning(f"Maximum tokens reached {max_tokens}, should be fixed")
+ maximum_tokens_reached = True
message = choice.message
delta = ChoiceDelta(
content=message.content,
@@ -235,10 +221,9 @@ async def _completion_stream_worker(
],
)
yield delta
- to_cache.append(delta)
- # Update cache
- await _cache.aset(cache_key, TypeAdapter(list[ChoiceDelta]).dump_json(to_cache))
+ if maximum_tokens_reached:
+ raise MaximumTokensReachedError(f"Maximum tokens reached {max_tokens}")
@tracer.start_as_current_span("completion_sync")
@@ -295,13 +280,6 @@ async def _completion_sync_worker(
"""
Returns a completion.
"""
- # Try cache
- cache_key = f"{__name__}-completion_sync-{system}-{max_tokens}"
- cached = await _cache.aget(cache_key)
- if cached:
- return cached.decode()
-
- # Try live
content = None
client, platform = _use_llm(is_fast)
extra = {}
@@ -330,13 +308,9 @@ async def _completion_sync_worker(
f"Content filter detected for text: {choice.message.content}"
)
if choice.finish_reason == "length":
- logger.warning(f"Maximum tokens reached {max_tokens}, should be fixed")
+ raise MaximumTokensReachedError(f"Maximum tokens reached {max_tokens}")
content = choice.message.content
- # Update cache
- if content:
- await _cache.aset(cache_key, content.encode())
-
if not content:
return None
if not json_output: