|
| 1 | +"""Adapter for Anthropic API with vision support.""" |
| 2 | + |
| 3 | +from pprint import pprint |
| 4 | + |
| 5 | +from loguru import logger |
| 6 | +import anthropic |
| 7 | + |
| 8 | +from openadapt import cache, config |
| 9 | + |
| 10 | + |
| 11 | +MAX_TOKENS = 4096 |
| 12 | +# from https://docs.anthropic.com/claude/docs/vision |
| 13 | +MAX_IMAGES = 20 |
| 14 | +MODEL_NAME = "claude-3-opus-20240229" |
| 15 | + |
| 16 | + |
| 17 | +@cache.cache() |
| 18 | +def create_payload( |
| 19 | + prompt: str, |
| 20 | + system_prompt: str | None = None, |
| 21 | + base64_images: list[tuple[str, str]] | None = None, |
| 22 | + model: str = MODEL_NAME, |
| 23 | + max_tokens: int | None = None, |
| 24 | +) -> dict: |
| 25 | + """Creates the payload for the Anthropic API request with image support.""" |
| 26 | + messages = [] |
| 27 | + |
| 28 | + user_message_content = [] |
| 29 | + |
| 30 | + max_tokens = max_tokens or MAX_TOKENS |
| 31 | + if max_tokens > MAX_TOKENS: |
| 32 | + logger.warning(f"{max_tokens=} > {MAX_TOKENS=}") |
| 33 | + max_tokens = MAX_TOKENS |
| 34 | + |
| 35 | + # Add base64 encoded images to the user message content |
| 36 | + if base64_images: |
| 37 | + for image_data in base64_images: |
| 38 | + # Extract media type and base64 data |
| 39 | + media_type, base64_str = image_data.split(";base64,", 1) |
| 40 | + media_type = media_type.split(":")[-1] # Remove 'data:' prefix |
| 41 | + |
| 42 | + user_message_content.append( |
| 43 | + { |
| 44 | + "type": "image", |
| 45 | + "source": { |
| 46 | + "type": "base64", |
| 47 | + "media_type": media_type, |
| 48 | + "data": base64_str, |
| 49 | + }, |
| 50 | + } |
| 51 | + ) |
| 52 | + |
| 53 | + # Add text prompt |
| 54 | + user_message_content.append( |
| 55 | + { |
| 56 | + "type": "text", |
| 57 | + "text": prompt, |
| 58 | + } |
| 59 | + ) |
| 60 | + |
| 61 | + # Construct user message |
| 62 | + messages.append( |
| 63 | + { |
| 64 | + "role": "user", |
| 65 | + "content": user_message_content, |
| 66 | + } |
| 67 | + ) |
| 68 | + |
| 69 | + # Prepare the full payload |
| 70 | + payload = { |
| 71 | + "model": model, |
| 72 | + "max_tokens": max_tokens, |
| 73 | + "messages": messages, |
| 74 | + } |
| 75 | + |
| 76 | + # Add system_prompt as a top-level parameter if provided |
| 77 | + if system_prompt: |
| 78 | + payload["system"] = system_prompt |
| 79 | + |
| 80 | + return payload |
| 81 | + |
| 82 | + |
| 83 | +client = anthropic.Anthropic(api_key=config.ANTHROPIC_API_KEY) |
| 84 | + |
| 85 | + |
| 86 | +@cache.cache() |
| 87 | +def get_completion(payload: dict) -> str: |
| 88 | + """Sends a request to the Anthropic API and returns the response.""" |
| 89 | + try: |
| 90 | + response = client.messages.create(**payload) |
| 91 | + except Exception as exc: |
| 92 | + logger.exception(exc) |
| 93 | + import ipdb |
| 94 | + |
| 95 | + ipdb.set_trace() |
| 96 | + """ |
| 97 | + Message( |
| 98 | + id='msg_01L55ai2A9q92687mmjMSch3', |
| 99 | + content=[ |
| 100 | + ContentBlock( |
| 101 | + text='{ |
| 102 | + "action": [ |
| 103 | + { |
| 104 | + "name": "press", |
| 105 | + "key_name": "cmd", |
| 106 | + "canonical_key_name": "cmd" |
| 107 | + }, |
| 108 | + ... |
| 109 | + ] |
| 110 | + }', |
| 111 | + type='text' |
| 112 | + ) |
| 113 | + ], |
| 114 | + model='claude-3-opus-20240229', |
| 115 | + role='assistant', |
| 116 | + stop_reason='end_turn', |
| 117 | + stop_sequence=None, |
| 118 | + type='message', |
| 119 | + usage=Usage(input_tokens=4379, output_tokens=109)) |
| 120 | + """ |
| 121 | + texts = [content_block.text for content_block in response.content] |
| 122 | + return "\n".join(texts) |
| 123 | + |
| 124 | + |
| 125 | +def prompt( |
| 126 | + prompt: str, |
| 127 | + system_prompt: str | None = None, |
| 128 | + base64_images: list[str] | None = None, |
| 129 | + max_tokens: int | None = None, |
| 130 | +) -> str: |
| 131 | + """Public method to get a response from the Anthropic API with image support.""" |
| 132 | + if len(base64_images) > MAX_IMAGES: |
| 133 | + # XXX TODO handle this |
| 134 | + raise Exception( |
| 135 | + f"{len(base64_images)=} > {MAX_IMAGES=}. Use a different adapter." |
| 136 | + ) |
| 137 | + payload = create_payload( |
| 138 | + prompt, |
| 139 | + system_prompt, |
| 140 | + base64_images, |
| 141 | + max_tokens=max_tokens, |
| 142 | + ) |
| 143 | + # pprint(f"payload=\n{payload}") # Log payload for debugging |
| 144 | + result = get_completion(payload) |
| 145 | + pprint(f"result=\n{result}") # Log result for debugging |
| 146 | + return result |
0 commit comments