|
| 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) |
0 commit comments