Repository navigation
Expand file tree
/
Copy pathconverse.py
More file actions
154 lines (127 loc) · 5.23 KB
/
Copy pathconverse.py
File metadata and controls
154 lines (127 loc) · 5.23 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
import copy
import io
import random
import time
from PIL import Image
from botocore.exceptions import BotoCoreError, ClientError
from bedrock_client import bedrock, TOOL_MODEL, REASONING_MODEL
########################################
# This file contains our own implementation of LLM call APIs
########################################
token_usage_input = 0
token_usage_output = 0
def simple_converse(text, messages=None, reasoning=None, files=None, system=None):
if messages is None:
messages = []
content = [{"text": text}]
if files:
for file_path in files:
format = file_path.split('.')[-1] # Extract file extension as format
if format in ['jpg', 'jpeg', 'png', 'gif', 'webp']:
if format == 'jpg':
format = 'jpeg'
with Image.open(file_path) as img:
# Convert image to bytes
img_byte_arr = io.BytesIO()
img.save(img_byte_arr, format=format)
img_byte_arr.seek(0)
image_bytes = img_byte_arr.getvalue()
content.append({
"image": {
"format": format,
"source": {
"bytes": image_bytes,
}
}
})
else:
with open(file_path, 'r', encoding='utf-8') as f:
file_content = f.read()
file_name = file_path.split('/')[-1] # Extract filename from path
format = file_name.split('.')[-1]
if format == "sh":
format = "txt"
file_content = f"# Shell script: {file_content}"
if format == "py":
format = "txt"
content.append({
"document": {
"format": format, # Extract extension as format
"name": file_name.split('.')[0],
"source": {
"bytes": file_content.encode('utf-8')
}
}
})
messages.append({
"role": "user",
"content": content
})
return converse(messages, reasoning=reasoning, system=system)
def _strip_thinking_blocks(messages):
"""Return a copy of messages with reasoningContent blocks removed from assistant turns."""
cleaned = copy.deepcopy(messages)
for msg in cleaned:
if msg.get('role') == 'assistant' and isinstance(msg.get('content'), list):
msg['content'] = [
block for block in msg['content']
if 'reasoningContent' not in block
]
return cleaned
def converse(messages, system=None, reasoning=None, tool_config=None):
assert not (reasoning and tool_config), "Bedrock does not support reasoning and tool use simultaneously"
if not reasoning:
messages = _strip_thinking_blocks(messages)
kwargs = {
"modelId": REASONING_MODEL if reasoning else TOOL_MODEL,
"messages": messages,
}
if system:
kwargs["system"] = system
if reasoning:
kwargs["additionalModelRequestFields"] = {
"thinking": {"type": "enabled", "budget_tokens": reasoning}
}
kwargs["inferenceConfig"] = {"maxTokens": reasoning + 8000}
if tool_config:
kwargs["toolConfig"] = tool_config
# Retry with exponential backoff
max_retries = 5
base_delay = 10
max_delay = 30
for attempt in range(max_retries + 1):
try:
response = bedrock.converse(**kwargs)
global token_usage_input, token_usage_output
token_usage_input += response['usage']['inputTokens']
token_usage_output += response['usage']['outputTokens']
return response["output"]["message"]
except (BotoCoreError, ClientError) as error:
if attempt >= max_retries:
print(f"Failed after {max_retries} attempts. Last error: {error}")
raise
delay = min(max_delay, base_delay * (2 ** attempt))
jitter = random.uniform(0, 0.1 * delay)
wait_time = delay + jitter
if attempt >= 3:
wait_time += 60
print(f"Bedrock error: {error}")
print(f"Retry {attempt + 1}/{max_retries} after {wait_time:.1f}s...")
time.sleep(wait_time)
def simple_chat(reasoning=None):
messages = []
while True:
text = input("Enter your text: ")
message = simple_converse(text, messages, reasoning=reasoning)
idx = 1 if reasoning else 0
print(message['content'][idx]['text'])
messages.append(message)
if __name__ == "__main__":
# V1: Basic Bedrock call
print("--- V1: Basic call ---")
message = simple_converse("What is the capital of France?")
print(message['content'][0]['text'])
# V2: Reasoning mode
print("\n--- V2: Reasoning mode ---")
message = simple_converse("What is the capital of France?", reasoning=1024)
print(message['content'][1]['text']) # [0] is thinking block, [1] is text