@@ -89,26 +89,29 @@ def anthropic_chat_completion_with_backoff(
89
89
def anthropic_llm_thread (
90
90
g , messages , system_prompt , model_name , temperature , api_key , max_prompt_size = None , model_kwargs = None
91
91
):
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 ()
0 commit comments