Skip to content

Commit 9ed9c19

Browse files
authored
Merge pull request #799 from parea-ai/PAI-897-claude-auto-tracing-images
Pai 897 claude auto tracing images
2 parents 337a244 + f5db6ca commit 9ed9c19

File tree

3 files changed

+76
-2
lines changed

3 files changed

+76
-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: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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+
from typing import Optional
32+
33+
import base64
34+
35+
import requests
36+
37+
38+
@trace
39+
def ask_vision(image_url: str) -> Optional[str]:
40+
image_data = requests.get(image_url).content
41+
base64_image = base64.b64encode(image_data).decode("utf-8")
42+
43+
response = a_client.messages.create(
44+
model="claude-3-haiku-20240307",
45+
messages=[
46+
{
47+
"role": "user",
48+
"content": [
49+
{
50+
"type": "image",
51+
"source": {
52+
"type": "base64",
53+
"media_type": "image/png",
54+
"data": base64_image,
55+
},
56+
},
57+
{"type": "text", "text": "What’s in this image?"},
58+
],
59+
}
60+
],
61+
max_tokens=300,
62+
)
63+
return response.content[0].text
64+
65+
66+
@trace
67+
def main(query: str) -> str:
68+
image_url = image_maker(query)
69+
return ask_vision(image_url)
70+
71+
72+
if __name__ == "__main__":
73+
result = main("A dog sitting comfortably on a chair")
74+
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)