|
| 1 | +from typing import List, Optional |
| 2 | +from .base_node import BaseNode |
| 3 | +import base64 |
| 4 | +import requests |
| 5 | + |
| 6 | +class GenerateAnswerFromImageNode(BaseNode): |
| 7 | + """ |
| 8 | + GenerateAnswerFromImageNode analyzes images from the state dictionary using the OpenAI API |
| 9 | + and updates the state with the generated answers. |
| 10 | + """ |
| 11 | + |
| 12 | + def __init__( |
| 13 | + self, |
| 14 | + input: str, |
| 15 | + output: List[str], |
| 16 | + node_config: Optional[dict] = None, |
| 17 | + node_name: str = "GenerateAnswerFromImageNode", |
| 18 | + ): |
| 19 | + super().__init__(node_name, "node", input, output, 2, node_config) |
| 20 | + |
| 21 | + def execute(self, state: dict) -> dict: |
| 22 | + """Processes images from the state, generates answers, and updates the state.""" |
| 23 | + # Retrieve the image data from the state dictionary |
| 24 | + images = state.get('screenshots', []) |
| 25 | + results = [] |
| 26 | + |
| 27 | + # OpenAI API Key |
| 28 | + for image_data in images: |
| 29 | + # Encode the image data to base64 |
| 30 | + base64_image = base64.b64encode(image_data).decode('utf-8') |
| 31 | + |
| 32 | + # Prepare API request |
| 33 | + headers = { |
| 34 | + "Content-Type": "application/json", |
| 35 | + "Authorization": f"Bearer {self.node_config.get("config").get("llm").get("api_key")}" |
| 36 | + } |
| 37 | + |
| 38 | + payload = { |
| 39 | + "model": "gpt-4o-mini", |
| 40 | + "messages": [ |
| 41 | + { |
| 42 | + "role": "user", |
| 43 | + "content": [ |
| 44 | + { |
| 45 | + "type": "text", |
| 46 | + "text": state.get("user_prompt", "Extract information from the image") |
| 47 | + }, |
| 48 | + { |
| 49 | + "type": "image_url", |
| 50 | + "image_url": { |
| 51 | + "url": f"data:image/jpeg;base64,{base64_image}" |
| 52 | + } |
| 53 | + } |
| 54 | + ] |
| 55 | + } |
| 56 | + ], |
| 57 | + "max_tokens": 300 |
| 58 | + } |
| 59 | + |
| 60 | + # Make the API request |
| 61 | + response = requests.post("https://api.openai.com/v1/chat/completions", headers=headers, json=payload) |
| 62 | + result = response.json() |
| 63 | + |
| 64 | + # Extract the response text |
| 65 | + response_text = result.get('choices', [{}])[0].get('message', {}).get('content', 'No response') |
| 66 | + |
| 67 | + # Append the result to the results list |
| 68 | + results.append({ |
| 69 | + "analysis": response_text |
| 70 | + }) |
| 71 | + |
| 72 | + # Update the state dictionary with the results |
| 73 | + state['answer'] = results |
| 74 | + return state |
0 commit comments