Skip to content

Commit 576af3f

Browse files
committed
fast_llm: Fix UnboundLocalError, add docstring
Previously, fast_llm was trying to access 'response' in the finally block, which would fail with UnboundLocalError if the chat call raised an exception (because of missing API key, etc.) UnboundLocalError: cannot access local variable 'response' where it is not associated with a value Moved the return statement into the try block while keeping state restoration in finally, ensuring proper error propagation while maintaining conversation state. This way, if there's an API key issue or any other problem, any errors from `llm.interpreter.chat()` propagate up and can be handled at the appropriate level in the call stack. Added a detailed docstring to clarify the purpose, behavior, and usage of the `fast_llm` function.
1 parent 21babb1 commit 576af3f

File tree

1 file changed

+21
-1
lines changed
  • interpreter/core/computer/ai

1 file changed

+21
-1
lines changed

interpreter/core/computer/ai/ai.py

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -78,16 +78,36 @@ def chunk_responses(responses, tokens, llm):
7878

7979

8080
def fast_llm(llm, system_message, user_message):
81+
"""
82+
Creates a temporary chat context to process a single query, then restores the original chat state.
83+
84+
This is used for auxiliary queries (like summarization) that shouldn't affect the main conversation.
85+
Particularly important for local LLMs where creating new instances is expensive.
86+
87+
Args:
88+
llm: The LLM instance to use (typically computer.interpreter.llm)
89+
system_message: The system prompt for this specific query
90+
user_message: The user message/content to process
91+
92+
Returns:
93+
str: The LLM's response content
94+
95+
Note:
96+
This function temporarily replaces the LLM's conversation state (messages and system prompt),
97+
runs the query, then restores the original state. This allows us to run one-off queries
98+
without disrupting the main conversation context.
99+
"""
81100
old_messages = llm.interpreter.messages
82101
old_system_message = llm.interpreter.system_message
83102
try:
84103
llm.interpreter.system_message = system_message
85104
llm.interpreter.messages = []
86105
response = llm.interpreter.chat(user_message)
106+
return response[-1].get("content")
87107
finally:
108+
# Always restore the old state (before returning)
88109
llm.interpreter.messages = old_messages
89110
llm.interpreter.system_message = old_system_message
90-
return response[-1].get("content")
91111

92112

93113
def query_map_chunks(chunks, llm, query):

0 commit comments

Comments
 (0)