|
| 1 | +""" |
| 2 | +GenerateAnswerFromImageNode Module |
| 3 | +""" |
| 4 | +import base64 |
| 5 | +import asyncio |
| 6 | +from typing import List, Optional |
| 7 | +import aiohttp |
| 8 | +from .base_node import BaseNode |
| 9 | +from ..utils.logging import get_logger |
| 10 | + |
| 11 | +class GenerateAnswerFromImageNode(BaseNode): |
| 12 | + """ |
| 13 | + GenerateAnswerFromImageNode analyzes images from the state dictionary using the OpenAI API |
| 14 | + and updates the state with the consolidated answers. |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__( |
| 18 | + self, |
| 19 | + input: str, |
| 20 | + output: List[str], |
| 21 | + node_config: Optional[dict] = None, |
| 22 | + node_name: str = "GenerateAnswerFromImageNode", |
| 23 | + ): |
| 24 | + super().__init__(node_name, "node", input, output, 2, node_config) |
| 25 | + |
| 26 | + async def process_image(self, session, api_key, image_data, user_prompt): |
| 27 | + """ |
| 28 | + async process image |
| 29 | + """ |
| 30 | + base64_image = base64.b64encode(image_data).decode('utf-8') |
| 31 | + |
| 32 | + headers = { |
| 33 | + "Content-Type": "application/json", |
| 34 | + "Authorization": f"Bearer {api_key}" |
| 35 | + } |
| 36 | + |
| 37 | + payload = { |
| 38 | + "model": self.node_config["config"]["llm"]["model"], |
| 39 | + "messages": [ |
| 40 | + { |
| 41 | + "role": "user", |
| 42 | + "content": [ |
| 43 | + { |
| 44 | + "type": "text", |
| 45 | + "text": user_prompt |
| 46 | + }, |
| 47 | + { |
| 48 | + "type": "image_url", |
| 49 | + "image_url": { |
| 50 | + "url": f"data:image/jpeg;base64,{base64_image}" |
| 51 | + } |
| 52 | + } |
| 53 | + ] |
| 54 | + } |
| 55 | + ], |
| 56 | + "max_tokens": 300 |
| 57 | + } |
| 58 | + |
| 59 | + async with session.post("https://api.openai.com/v1/chat/completions", |
| 60 | + headers=headers, json=payload) as response: |
| 61 | + result = await response.json() |
| 62 | + return result.get('choices', [{}])[0].get('message', {}).get('content', 'No response') |
| 63 | + |
| 64 | + async def execute_async(self, state: dict) -> dict: |
| 65 | + """ |
| 66 | + Processes images from the state, generates answers, |
| 67 | + consolidates the results, and updates the state asynchronously. |
| 68 | + """ |
| 69 | + self.logger.info(f"--- Executing {self.node_name} Node ---") |
| 70 | + |
| 71 | + images = state.get('screenshots', []) |
| 72 | + analyses = [] |
| 73 | + |
| 74 | + supported_models = ("gpt-4o", "gpt-4o-mini", "gpt-4-turbo") |
| 75 | + |
| 76 | + if self.node_config["config"]["llm"]["model"] not in supported_models: |
| 77 | + raise ValueError(f"""Model '{self.node_config['config']['llm']['model']}' |
| 78 | + is not supported. Supported models are: |
| 79 | + {', '.join(supported_models)}.""") |
| 80 | + |
| 81 | + api_key = self.node_config.get("config", {}).get("llm", {}).get("api_key", "") |
| 82 | + |
| 83 | + async with aiohttp.ClientSession() as session: |
| 84 | + tasks = [ |
| 85 | + self.process_image(session, api_key, image_data, |
| 86 | + state.get("user_prompt", "Extract information from the image")) |
| 87 | + for image_data in images |
| 88 | + ] |
| 89 | + |
| 90 | + analyses = await asyncio.gather(*tasks) |
| 91 | + |
| 92 | + consolidated_analysis = " ".join(analyses) |
| 93 | + |
| 94 | + state['answer'] = { |
| 95 | + "consolidated_analysis": consolidated_analysis |
| 96 | + } |
| 97 | + |
| 98 | + return state |
| 99 | + |
| 100 | + def execute(self, state: dict) -> dict: |
| 101 | + """ |
| 102 | + Wrapper to run the asynchronous execute_async function in a synchronous context. |
| 103 | + """ |
| 104 | + try: |
| 105 | + eventloop = asyncio.get_event_loop() |
| 106 | + except RuntimeError: |
| 107 | + eventloop = None |
| 108 | + |
| 109 | + if eventloop and eventloop.is_running(): |
| 110 | + task = eventloop.create_task(self.execute_async(state)) |
| 111 | + state = eventloop.run_until_complete(asyncio.gather(task))[0] |
| 112 | + else: |
| 113 | + state = asyncio.run(self.execute_async(state)) |
| 114 | + |
| 115 | + return state |
0 commit comments