From 576af3f29ebeae77902e13591b1df5c0e0b6f548 Mon Sep 17 00:00:00 2001 From: endolith Date: Wed, 29 Jan 2025 16:37:22 -0500 Subject: [PATCH] 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. --- interpreter/core/computer/ai/ai.py | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/interpreter/core/computer/ai/ai.py b/interpreter/core/computer/ai/ai.py index d421117d90..8ece2111da 100644 --- a/interpreter/core/computer/ai/ai.py +++ b/interpreter/core/computer/ai/ai.py @@ -78,16 +78,36 @@ def chunk_responses(responses, tokens, llm): def fast_llm(llm, system_message, user_message): + """ + Creates a temporary chat context to process a single query, then restores the original chat state. + + This is used for auxiliary queries (like summarization) that shouldn't affect the main conversation. + Particularly important for local LLMs where creating new instances is expensive. + + Args: + llm: The LLM instance to use (typically computer.interpreter.llm) + system_message: The system prompt for this specific query + user_message: The user message/content to process + + Returns: + str: The LLM's response content + + Note: + This function temporarily replaces the LLM's conversation state (messages and system prompt), + runs the query, then restores the original state. This allows us to run one-off queries + without disrupting the main conversation context. + """ old_messages = llm.interpreter.messages old_system_message = llm.interpreter.system_message try: llm.interpreter.system_message = system_message llm.interpreter.messages = [] response = llm.interpreter.chat(user_message) + return response[-1].get("content") finally: + # Always restore the old state (before returning) llm.interpreter.messages = old_messages llm.interpreter.system_message = old_system_message - return response[-1].get("content") def query_map_chunks(chunks, llm, query):