| 8 | |
| 9 | |
| 10 | class Gemini: |
| 11 | def __init__(self, model_name, api_key, context): |
| 12 | self.model_name = model_name |
| 13 | self.api_key = api_key |
| 14 | self.context = context |
| 15 | self.client = genai.Client(api_key=api_key) |
| 16 | |
| 17 | if api_key: |
| 18 | os.environ['GEMINI_API_KEY'] = api_key |
| 19 | |
| 20 | def get_instructions_for_objective(self, original_user_request: str, step_num: int = 0) -> dict[str, Any]: |
| 21 | safety_settings = [ |
| 22 | types.SafetySetting(category=category.value, threshold="BLOCK_NONE") |
| 23 | for category in types.HarmCategory |
| 24 | if category.value != 'HARM_CATEGORY_UNSPECIFIED' |
| 25 | ] |
| 26 | message_content = self.format_user_request_for_llm(original_user_request, step_num) |
| 27 | |
| 28 | llm_response = self.client.models.generate_content( |
| 29 | model=self.model_name, |
| 30 | contents=message_content, |
| 31 | config=types.GenerateContentConfig(safety_settings=safety_settings), |
| 32 | ) |
| 33 | json_instructions: dict[str, Any] = self.convert_llm_response_to_json_instructions(llm_response) |
| 34 | return json_instructions |
| 35 | |
| 36 | def format_user_request_for_llm(self, original_user_request, step_num) -> list[Any]: |
| 37 | base64_img: str = Screen().get_screenshot_in_base64() |
| 38 | |
| 39 | request_data: str = json.dumps({ |
| 40 | "original_user_request": original_user_request, |
| 41 | "step_num": step_num, |
| 42 | }) |
| 43 | |
| 44 | message_content = [ |
| 45 | {"text": self.context + request_data + "\n\nHere is a screenshot of the user's screen:"}, |
| 46 | {"inline_data": { |
| 47 | "mime_type": "image/jpeg", |
| 48 | "data": base64_img, |
| 49 | }}, |
| 50 | ] |
| 51 | return message_content |
| 52 | |
| 53 | def convert_llm_response_to_json_instructions(self, llm_response) -> dict[str, Any]: |
| 54 | llm_response_data = llm_response.text.strip() |
| 55 | |
| 56 | start_index = llm_response_data.find("{") |
| 57 | end_index = llm_response_data.rfind("}") |
| 58 | |
| 59 | try: |
| 60 | json_response = json.loads(llm_response_data[start_index:end_index + 1].strip()) |
| 61 | except Exception as e: |
| 62 | print(f"Error while parsing JSON response - {e}") |
| 63 | json_response = {} |
| 64 | |
| 65 | return json_response |
| 66 | |
| 67 | def cleanup(self): |