Skip to content

Commit 9ea9165

Browse files
committed
feat: add anthropic image tracing example
1 parent 337a244 commit 9ea9165

File tree

3 files changed

+73
-2
lines changed

3 files changed

+73
-2
lines changed

parea/api_client.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212

1313
load_dotenv()
1414

15-
MAX_RETRIES = 7
15+
MAX_RETRIES = 8
1616
BACKOFF_FACTOR = 0.5
1717

1818

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import json
2+
import os
3+
4+
from anthropic import Anthropic
5+
from dotenv import load_dotenv
6+
from openai import OpenAI
7+
8+
from parea import Parea, trace, trace_insert
9+
from parea.schemas import TraceLogImage
10+
11+
load_dotenv()
12+
13+
14+
oai_client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
15+
a_client = Anthropic(api_key=os.getenv("ANTHROPIC_API_KEY"))
16+
17+
p = Parea(api_key=os.getenv("PAREA_API_KEY"))
18+
p.wrap_openai_client(oai_client)
19+
p.wrap_anthropic_client(a_client)
20+
21+
22+
@trace
23+
def image_maker(query: str) -> str:
24+
response = oai_client.images.generate(prompt=query, model="dall-e-3")
25+
image_url = response.data[0].url
26+
caption = {"original_prompt": query, "revised_prompt": response.data[0].revised_prompt}
27+
trace_insert({"images": [TraceLogImage(url=image_url, caption=json.dumps(caption))]})
28+
return image_url
29+
30+
31+
import requests
32+
import base64
33+
from typing import Optional
34+
35+
@trace
36+
def ask_vision(image_url: str) -> Optional[str]:
37+
image_data = requests.get(image_url).content
38+
base64_image = base64.b64encode(image_data).decode('utf-8')
39+
40+
response = a_client.messages.create(
41+
model="claude-3-haiku-20240307",
42+
messages=[
43+
{
44+
"role": "user",
45+
"content": [
46+
{
47+
"type": "image",
48+
"source": {
49+
"type": "base64",
50+
"media_type": "image/png",
51+
"data": base64_image,
52+
},
53+
},
54+
{"type": "text", "text": "What’s in this image?"},
55+
],
56+
}
57+
],
58+
max_tokens=300,
59+
)
60+
return response.content[0].text
61+
62+
63+
@trace
64+
def main(query: str) -> str:
65+
image_url = image_maker(query)
66+
return ask_vision(image_url)
67+
68+
69+
if __name__ == "__main__":
70+
result = main("A dog sitting comfortably on a chair")
71+
print(result)

parea/cookbook/tracing_with_images_open_ai.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ def image_maker(query: str) -> str:
3030
@trace
3131
def ask_vision(image_url: str) -> Optional[str]:
3232
response = client.chat.completions.create(
33-
model="gpt-4-vision-preview",
33+
model="gpt-4-turbo",
3434
messages=[
3535
{
3636
"role": "user",

0 commit comments

Comments
 (0)