Skip to content

Commit 895f1c8

Browse files
committed
Gracefully close thread when there's an exception in the anthropic llm thread. Include full stack traces.
1 parent 1790140 commit 895f1c8

File tree

2 files changed

+27
-24
lines changed

2 files changed

+27
-24
lines changed

src/khoj/processor/conversation/anthropic/utils.py

+26-23
Original file line numberDiff line numberDiff line change
@@ -89,26 +89,29 @@ def anthropic_chat_completion_with_backoff(
8989
def anthropic_llm_thread(
9090
g, messages, system_prompt, model_name, temperature, api_key, max_prompt_size=None, model_kwargs=None
9191
):
92-
if api_key not in anthropic_clients:
93-
client: anthropic.Anthropic = anthropic.Anthropic(api_key=api_key)
94-
anthropic_clients[api_key] = client
95-
else:
96-
client: anthropic.Anthropic = anthropic_clients[api_key]
97-
98-
formatted_messages: List[anthropic.types.MessageParam] = [
99-
anthropic.types.MessageParam(role=message.role, content=message.content) for message in messages
100-
]
101-
102-
with client.messages.stream(
103-
messages=formatted_messages,
104-
model=model_name, # type: ignore
105-
temperature=temperature,
106-
system=system_prompt,
107-
timeout=20,
108-
max_tokens=DEFAULT_MAX_TOKENS_ANTHROPIC,
109-
**(model_kwargs or dict()),
110-
) as stream:
111-
for text in stream.text_stream:
112-
g.send(text)
113-
114-
g.close()
92+
try:
93+
if api_key not in anthropic_clients:
94+
client: anthropic.Anthropic = anthropic.Anthropic(api_key=api_key)
95+
anthropic_clients[api_key] = client
96+
else:
97+
client: anthropic.Anthropic = anthropic_clients[api_key]
98+
99+
formatted_messages: List[anthropic.types.MessageParam] = [
100+
anthropic.types.MessageParam(role=message.role, content=message.content) for message in messages
101+
]
102+
103+
with client.messages.stream(
104+
messages=formatted_messages,
105+
model=model_name, # type: ignore
106+
temperature=temperature,
107+
system=system_prompt,
108+
timeout=20,
109+
max_tokens=DEFAULT_MAX_TOKENS_ANTHROPIC,
110+
**(model_kwargs or dict()),
111+
) as stream:
112+
for text in stream.text_stream:
113+
g.send(text)
114+
except Exception as e:
115+
logger.error(f"Error in anthropic_llm_thread: {e}", exc_info=True)
116+
finally:
117+
g.close()

src/khoj/processor/conversation/openai/utils.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,6 @@ def llm_thread(g, messages, model_name, temperature, openai_api_key=None, api_ba
131131
elif delta_chunk.content:
132132
g.send(delta_chunk.content)
133133
except Exception as e:
134-
logger.error(f"Error in llm_thread: {e}")
134+
logger.error(f"Error in llm_thread: {e}", exc_info=True)
135135
finally:
136136
g.close()

0 commit comments

Comments
 (0)