85 lines
1.9 KiB
Python
85 lines
1.9 KiB
Python
import anthropic
|
|
import tomli
|
|
import time
|
|
from anthropic import APIError, APIConnectionError, RateLimitError
|
|
|
|
# Exponential backoff settings
|
|
MAX_RETRIES = 5
|
|
INITIAL_DELAY = 1 # seconds
|
|
BACKOFF_FACTOR = 2
|
|
|
|
# def add_agent_entry():
|
|
def add_user_entry(role: str, message:str):
|
|
return
|
|
|
|
def add_system_entry():
|
|
return
|
|
|
|
def test():
|
|
with open('anthropic.toml', 'rb') as f:
|
|
toml_anthropic = tomli.load(f)
|
|
with open('test_task.toml', 'rb') as f:
|
|
toml_task = tomli.load(f)
|
|
|
|
sonnet_3_7_latest = "claude-3-7-sonnet-20250219"
|
|
|
|
retry_count = 0
|
|
delay = INITIAL_DELAY
|
|
|
|
client = anthropic.Anthropic(api_key=toml_anthropic['API']['API_KEY'])
|
|
|
|
while retry_count < MAX_RETRIES:
|
|
try:
|
|
response = client.messages.create(
|
|
model=sonnet_3_7_latest,
|
|
max_tokens=20000,
|
|
temperature=0.8,
|
|
system=[
|
|
{
|
|
"type": "text",
|
|
# "text": toml_task['System']['content'],
|
|
"text": toml_task['System']['content'],
|
|
"cache_control": {"type": "ephemeral"}
|
|
}
|
|
],
|
|
messages=[
|
|
{
|
|
"role": "user",
|
|
"content": [
|
|
{
|
|
"type": "text",
|
|
"text": toml_task['User']['background'],
|
|
"cache_control": {"type": "ephemeral"}
|
|
},
|
|
{
|
|
"type": "text",
|
|
"text": toml_task['User']['request'],
|
|
"cache_control": {"type": "ephemeral"}
|
|
}
|
|
],
|
|
}
|
|
]
|
|
)
|
|
|
|
print(f"Usage: {response.usage}")
|
|
with open('test_response.md', 'w', encoding='utf-8') as f:
|
|
for content_block in response.content:
|
|
f.write(content_block.text + '\n')
|
|
return
|
|
|
|
except (APIError, APIConnectionError, RateLimitError) as e:
|
|
print(f"Attempt {retry_count + 1} failed: {str(e)}")
|
|
if retry_count == MAX_RETRIES - 1:
|
|
raise
|
|
|
|
time.sleep(delay)
|
|
delay *= BACKOFF_FACTOR
|
|
retry_count += 1
|
|
|
|
except Exception as e:
|
|
print(f"Unexpected error: {str(e)}")
|
|
raise
|
|
|
|
if __name__ == "__main__":
|
|
test()
|