-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy pathllm_client.py
More file actions
614 lines (542 loc) · 22.7 KB
/
llm_client.py
File metadata and controls
614 lines (542 loc) · 22.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
"""LLM client for Anthropic models."""
import json
import os
import random
import time
from dataclasses import dataclass
from typing import Any, Tuple, cast
from dataclasses_json import DataClassJsonMixin
import anthropic
import openai
from anthropic import (
NOT_GIVEN as Anthropic_NOT_GIVEN,
)
from anthropic import (
APIConnectionError as AnthropicAPIConnectionError,
)
from anthropic import (
InternalServerError as AnthropicInternalServerError,
)
from anthropic import (
RateLimitError as AnthropicRateLimitError,
)
from anthropic._exceptions import (
OverloadedError as AnthropicOverloadedError, # pyright: ignore[reportPrivateImportUsage]
)
from anthropic.types import (
TextBlock as AnthropicTextBlock,
ThinkingBlock as AnthropicThinkingBlock,
RedactedThinkingBlock as AnthropicRedactedThinkingBlock,
)
from anthropic.types import ToolParam as AnthropicToolParam
from anthropic.types import (
ToolResultBlockParam as AnthropicToolResultBlockParam,
)
from anthropic.types import (
ToolUseBlock as AnthropicToolUseBlock,
)
from anthropic.types.message_create_params import (
ToolChoiceToolChoiceAny,
ToolChoiceToolChoiceAuto,
ToolChoiceToolChoiceTool,
)
from openai import (
APIConnectionError as OpenAI_APIConnectionError,
)
from openai import (
InternalServerError as OpenAI_InternalServerError,
)
from openai import (
RateLimitError as OpenAI_RateLimitError,
)
from openai._types import (
NOT_GIVEN as OpenAI_NOT_GIVEN, # pyright: ignore[reportPrivateImportUsage]
)
import logging
logging.getLogger("httpx").setLevel(logging.WARNING)
@dataclass
class ToolParam(DataClassJsonMixin):
"""Internal representation of LLM tool."""
name: str
description: str
input_schema: dict[str, Any]
@dataclass
class ToolCall(DataClassJsonMixin):
"""Internal representation of LLM-generated tool call."""
tool_call_id: str
tool_name: str
tool_input: Any
@dataclass
class ToolResult(DataClassJsonMixin):
"""Internal representation of LLM tool result."""
tool_call_id: str
tool_name: str
tool_output: Any
@dataclass
class ToolFormattedResult(DataClassJsonMixin):
"""Internal representation of formatted LLM tool result."""
tool_call_id: str
tool_name: str
tool_output: str
@dataclass
class TextPrompt(DataClassJsonMixin):
"""Internal representation of user-generated text prompt."""
text: str
@dataclass
class TextResult(DataClassJsonMixin):
"""Internal representation of LLM-generated text result."""
text: str
AssistantContentBlock = (
TextResult | ToolCall | AnthropicRedactedThinkingBlock | AnthropicThinkingBlock
)
UserContentBlock = TextPrompt | ToolFormattedResult
GeneralContentBlock = UserContentBlock | AssistantContentBlock
LLMMessages = list[list[GeneralContentBlock]]
class LLMClient:
"""A client for LLM APIs for the use in agents."""
def generate(
self,
messages: LLMMessages,
max_tokens: int,
system_prompt: str | None = None,
temperature: float = 0.0,
tools: list[ToolParam] = [],
tool_choice: dict[str, str] | None = None,
thinking_tokens: int | None = None,
) -> Tuple[list[AssistantContentBlock], dict[str, Any]]:
"""Generate responses.
Args:
messages: A list of messages.
max_tokens: The maximum number of tokens to generate.
system_prompt: A system prompt.
temperature: The temperature.
tools: A list of tools.
tool_choice: A tool choice.
Returns:
A generated response.
"""
raise NotImplementedError
def recursively_remove_invoke_tag(obj):
"""Recursively remove the </invoke> tag from a dictionary or list."""
result_obj = {}
if isinstance(obj, dict):
for key, value in obj.items():
result_obj[key] = recursively_remove_invoke_tag(value)
elif isinstance(obj, list):
result_obj = [recursively_remove_invoke_tag(item) for item in obj]
elif isinstance(obj, str):
if "</invoke>" in obj:
result_obj = json.loads(obj.replace("</invoke>", ""))
else:
result_obj = obj
else:
result_obj = obj
return result_obj
class AnthropicDirectClient(LLMClient):
"""Use Anthropic models via first party API."""
def __init__(
self,
model_name="claude-3-7-sonnet-20250219",
max_retries=2,
use_caching=True,
use_low_qos_server: bool = False,
thinking_tokens: int = 0,
):
"""Initialize the Anthropic first party client."""
api_key = os.getenv("ANTHROPIC_API_KEY")
# Disable retries since we are handling retries ourselves.
self.client = anthropic.Anthropic(
api_key=api_key, max_retries=1, timeout=60 * 5
)
self.model_name = model_name
self.max_retries = max_retries
self.use_caching = use_caching
self.prompt_caching_headers = {"anthropic-beta": "prompt-caching-2024-07-31"}
self.thinking_tokens = thinking_tokens
def generate(
self,
messages: LLMMessages,
max_tokens: int,
system_prompt: str | None = None,
temperature: float = 0.0,
tools: list[ToolParam] = [],
tool_choice: dict[str, str] | None = None,
thinking_tokens: int | None = None,
) -> Tuple[list[AssistantContentBlock], dict[str, Any]]:
"""Generate responses.
Args:
messages: A list of messages.
max_tokens: The maximum number of tokens to generate.
system_prompt: A system prompt.
temperature: The temperature.
tools: A list of tools.
tool_choice: A tool choice.
Returns:
A generated response.
"""
# Turn GeneralContentBlock into Anthropic message format
anthropic_messages = []
for idx, message_list in enumerate(messages):
role = "user" if idx % 2 == 0 else "assistant"
message_content_list = []
for message in message_list:
# Check string type to avoid import issues particularly with reloads.
if str(type(message)) == str(TextPrompt):
message = cast(TextPrompt, message)
message_content = AnthropicTextBlock(
type="text",
text=message.text,
)
elif str(type(message)) == str(TextResult):
message = cast(TextResult, message)
message_content = AnthropicTextBlock(
type="text",
text=message.text,
)
elif str(type(message)) == str(ToolCall):
message = cast(ToolCall, message)
message_content = AnthropicToolUseBlock(
type="tool_use",
id=message.tool_call_id,
name=message.tool_name,
input=message.tool_input,
)
elif str(type(message)) == str(ToolFormattedResult):
message = cast(ToolFormattedResult, message)
message_content = AnthropicToolResultBlockParam(
type="tool_result",
tool_use_id=message.tool_call_id,
content=message.tool_output,
)
elif str(type(message)) == str(AnthropicRedactedThinkingBlock):
message = cast(AnthropicRedactedThinkingBlock, message)
message_content = message
elif str(type(message)) == str(AnthropicThinkingBlock):
message = cast(AnthropicThinkingBlock, message)
message_content = message
else:
print(
f"Unknown message type: {type(message)}, expected one of {str(TextPrompt)}, {str(TextResult)}, {str(ToolCall)}, {str(ToolFormattedResult)}"
)
raise ValueError(
f"Unknown message type: {type(message)}, expected one of {str(TextPrompt)}, {str(TextResult)}, {str(ToolCall)}, {str(ToolFormattedResult)}"
)
message_content_list.append(message_content)
# Anthropic supports up to 4 cache breakpoints, so we put them on the last 4 messages.
if self.use_caching and idx >= len(messages) - 4:
if isinstance(message_content_list[-1], dict):
message_content_list[-1]["cache_control"] = {"type": "ephemeral"}
else:
message_content_list[-1].cache_control = {"type": "ephemeral"}
anthropic_messages.append(
{
"role": role,
"content": message_content_list,
}
)
if self.use_caching:
extra_headers = self.prompt_caching_headers
else:
extra_headers = None
# Turn tool_choice into Anthropic tool_choice format
if tool_choice is None:
tool_choice_param = Anthropic_NOT_GIVEN
elif tool_choice["type"] == "any":
tool_choice_param = ToolChoiceToolChoiceAny(type="any")
elif tool_choice["type"] == "auto":
tool_choice_param = ToolChoiceToolChoiceAuto(type="auto")
elif tool_choice["type"] == "tool":
tool_choice_param = ToolChoiceToolChoiceTool(
type="tool", name=tool_choice["name"]
)
else:
raise ValueError(f"Unknown tool_choice type: {tool_choice['type']}")
if len(tools) == 0:
tool_params = Anthropic_NOT_GIVEN
else:
tool_params = [
AnthropicToolParam(
input_schema=tool.input_schema,
name=tool.name,
description=tool.description,
)
for tool in tools
]
response = None
if thinking_tokens is None:
thinking_tokens = self.thinking_tokens
if thinking_tokens and thinking_tokens > 0:
extra_body = {
"thinking": {"type": "enabled", "budget_tokens": thinking_tokens}
}
temperature = 1
assert max_tokens >= 32_000 and thinking_tokens <= 8192, (
f"As a heuristic, max tokens {max_tokens} must be >= 32k and thinking tokens {thinking_tokens} must be < 8k"
)
else:
extra_body = None
for retry in range(self.max_retries):
try:
response = self.client.messages.create( # type: ignore
max_tokens=max_tokens,
messages=anthropic_messages,
model=self.model_name,
temperature=temperature,
system=system_prompt or Anthropic_NOT_GIVEN,
tool_choice=tool_choice_param, # type: ignore
tools=tool_params,
extra_headers=extra_headers,
extra_body=extra_body,
)
break
except (
AnthropicAPIConnectionError,
AnthropicInternalServerError,
AnthropicRateLimitError,
AnthropicOverloadedError,
) as e:
if retry == self.max_retries - 1:
print(f"Failed Anthropic request after {retry + 1} retries")
raise e
else:
print(f"Retrying LLM request: {retry + 1}/{self.max_retries}")
# Sleep 4-6 seconds with jitter to avoid thundering herd.
time.sleep(5 * random.uniform(0.8, 1.2))
# Convert messages back to Augment format
augment_messages = []
assert response is not None
for message in response.content:
if "</invoke>" in str(message):
warning_msg = "\n".join(
["!" * 80, "WARNING: Unexpected 'invoke' in message", "!" * 80]
)
print(warning_msg)
if str(type(message)) == str(AnthropicTextBlock):
message = cast(AnthropicTextBlock, message)
augment_messages.append(TextResult(text=message.text))
elif str(type(message)) == str(AnthropicRedactedThinkingBlock):
augment_messages.append(message)
elif str(type(message)) == str(AnthropicThinkingBlock):
message = cast(AnthropicThinkingBlock, message)
augment_messages.append(message)
elif str(type(message)) == str(AnthropicToolUseBlock):
message = cast(AnthropicToolUseBlock, message)
augment_messages.append(
ToolCall(
tool_call_id=message.id,
tool_name=message.name,
tool_input=recursively_remove_invoke_tag(message.input),
)
)
else:
raise ValueError(f"Unknown message type: {type(message)}")
message_metadata = {
"raw_response": response,
"input_tokens": response.usage.input_tokens,
"output_tokens": response.usage.output_tokens,
"cache_creation_input_tokens": getattr(
response.usage, "cache_creation_input_tokens", -1
),
"cache_read_input_tokens": getattr(
response.usage, "cache_read_input_tokens", -1
),
}
return augment_messages, message_metadata
class OpenAIDirectClient(LLMClient):
"""Use OpenAI models via first party API."""
def __init__(self, model_name: str, max_retries=2, cot_model: bool = True):
"""Initialize the OpenAI first party client."""
api_key = os.getenv("OPENAI_API_KEY")
base_url = os.getenv("OPENAI_BASE_URL")
# Initialize the client with optional base_url if provided
client_kwargs = {"api_key": api_key, "max_retries": 1}
if base_url:
client_kwargs["base_url"] = base_url
self.client = openai.OpenAI(**client_kwargs)
self.model_name = model_name
self.max_retries = max_retries
self.cot_model = cot_model
def generate(
self,
messages: LLMMessages,
max_tokens: int,
system_prompt: str | None = None,
temperature: float = 0.0,
tools: list[ToolParam] = [],
tool_choice: dict[str, str] | None = None,
thinking_tokens: int | None = None,
) -> Tuple[list[AssistantContentBlock], dict[str, Any]]:
"""Generate responses.
Args:
messages: A list of messages.
system_prompt: A system prompt.
max_tokens: The maximum number of tokens to generate.
temperature: The temperature.
tools: A list of tools.
tool_choice: A tool choice.
Returns:
A generated response.
"""
assert thinking_tokens is None, "Not implemented for OpenAI"
# Turn GeneralContentBlock into OpenAI message format
openai_messages = []
if system_prompt is not None:
if self.cot_model:
raise NotImplementedError("System prompt not supported for cot model")
system_message = {"role": "system", "content": system_prompt}
openai_messages.append(system_message)
for idx, message_list in enumerate(messages):
if len(message_list) > 1:
raise ValueError("Only one entry per message supported for openai")
augment_message = message_list[0]
if str(type(augment_message)) == str(TextPrompt):
augment_message = cast(TextPrompt, augment_message)
message_content = {"type": "text", "text": augment_message.text}
openai_message = {"role": "user", "content": [message_content]}
elif str(type(augment_message)) == str(TextResult):
augment_message = cast(TextResult, augment_message)
message_content = {"type": "text", "text": augment_message.text}
openai_message = {"role": "assistant", "content": [message_content]}
elif str(type(augment_message)) == str(ToolCall):
augment_message = cast(ToolCall, augment_message)
# Ensure arguments are always a JSON string, not an object
if isinstance(augment_message.tool_input, (dict, list)):
tool_input_str = json.dumps(augment_message.tool_input)
else:
tool_input_str = str(augment_message.tool_input)
tool_call = {
"type": "function",
"id": augment_message.tool_call_id,
"function": {
"name": augment_message.tool_name,
"arguments": tool_input_str,
},
}
openai_message = {
"role": "assistant",
"tool_calls": [tool_call],
}
elif str(type(augment_message)) == str(ToolFormattedResult):
augment_message = cast(ToolFormattedResult, augment_message)
openai_message = {
"role": "tool",
"tool_call_id": augment_message.tool_call_id,
"content": augment_message.tool_output,
}
else:
print(
f"Unknown message type: {type(augment_message)}, expected one of {str(TextPrompt)}, {str(TextResult)}, {str(ToolCall)}, {str(ToolFormattedResult)}"
)
raise ValueError(f"Unknown message type: {type(augment_message)}")
openai_messages.append(openai_message)
# Turn tool_choice into OpenAI tool_choice format
if tool_choice is None:
tool_choice_param = OpenAI_NOT_GIVEN
elif tool_choice["type"] == "any":
tool_choice_param = "required"
elif tool_choice["type"] == "auto":
tool_choice_param = "auto"
elif tool_choice["type"] == "tool":
tool_choice_param = {
"type": "function",
"function": {"name": tool_choice["name"]},
}
else:
raise ValueError(f"Unknown tool_choice type: {tool_choice['type']}")
# Turn tools into OpenAI tool format
openai_tools = []
for tool in tools:
tool_def = {
"name": tool.name,
"description": tool.description,
"parameters": tool.input_schema,
}
tool_def["parameters"]["strict"] = True
openai_tool_object = {
"type": "function",
"function": tool_def,
}
openai_tools.append(openai_tool_object)
response = None
for retry in range(self.max_retries):
try:
extra_body = {}
openai_max_tokens = max_tokens
openai_temperature = temperature
if self.cot_model:
extra_body["max_completion_tokens"] = max_tokens
openai_max_tokens = OpenAI_NOT_GIVEN
openai_temperature = OpenAI_NOT_GIVEN
response = self.client.chat.completions.create( # type: ignore
model=self.model_name,
messages=openai_messages,
temperature=openai_temperature,
tools=openai_tools if len(openai_tools) > 0 else OpenAI_NOT_GIVEN,
tool_choice=tool_choice_param, # type: ignore
max_tokens=openai_max_tokens,
extra_body=extra_body,
)
break
except (
OpenAI_APIConnectionError,
OpenAI_InternalServerError,
OpenAI_RateLimitError,
) as e:
if retry == self.max_retries - 1:
print(f"Failed OpenAI request after {retry + 1} retries")
raise e
else:
print(f"Retrying OpenAI request: {retry + 1}/{self.max_retries}")
# Sleep 8-12 seconds with jitter to avoid thundering herd.
time.sleep(10 * random.uniform(0.8, 1.2))
# Convert messages back to Augment format
augment_messages = []
assert response is not None
openai_response_messages = response.choices
if len(openai_response_messages) > 1:
raise ValueError("Only one message supported for OpenAI")
openai_response_message = openai_response_messages[0].message
tool_calls = openai_response_message.tool_calls
content = openai_response_message.content
# Exactly one of tool_calls or content should be present
if tool_calls and content:
raise ValueError("Only one of tool_calls or content should be present")
elif not tool_calls and not content:
raise ValueError("Either tool_calls or content should be present")
if tool_calls:
if len(tool_calls) > 1:
raise ValueError("Only one tool call supported for OpenAI")
tool_call = tool_calls[0]
try:
# Parse the JSON string into a dictionary
tool_input = json.loads(tool_call.function.arguments)
except json.JSONDecodeError as e:
print(f"Failed to parse tool arguments: {tool_call.function.arguments}")
print(f"JSON parse error: {str(e)}")
raise ValueError(f"Invalid JSON in tool arguments: {str(e)}") from e
augment_messages.append(
ToolCall(
tool_name=tool_call.function.name,
tool_input=tool_input,
tool_call_id=tool_call.id,
)
)
elif content:
augment_messages.append(TextResult(text=content))
else:
raise ValueError(f"Unknown message type: {openai_response_message}")
assert response.usage is not None
message_metadata = {
"raw_response": response,
"input_tokens": response.usage.prompt_tokens,
"output_tokens": response.usage.completion_tokens,
}
return augment_messages, message_metadata
def get_client(client_name: str, **kwargs) -> LLMClient:
"""Get a client for a given client name."""
if client_name == "anthropic-direct":
return AnthropicDirectClient(**kwargs)
elif client_name == "openai-direct":
return OpenAIDirectClient(**kwargs)
else:
raise ValueError(f"Unknown client name: {client_name}")