| 82 | return generation |
| 83 | |
| 84 | def create_llm_chain_google(prompt_template: str, llm, history: Optional[str] = None) -> str: |
| 85 | url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent" |
| 86 | |
| 87 | headers = { |
| 88 | "Content-Type": "application/json" |
| 89 | } |
| 90 | |
| 91 | # If history exists, include it in the prompt |
| 92 | full_prompt = f"{history}\n{prompt_template}, you reply in json file" if history else prompt_template |
| 93 | |
| 94 | data = { |
| 95 | "contents": [{ |
| 96 | "parts": [{"text": full_prompt}] |
| 97 | }] |
| 98 | } |
| 99 | |
| 100 | params = { |
| 101 | "key": "your google key" |
| 102 | } |
| 103 | |
| 104 | try: |
| 105 | response = requests.post(url, headers=headers, json=data, params=params) |
| 106 | response.raise_for_status() |
| 107 | |
| 108 | json_response = response.json() |
| 109 | |
| 110 | # Extract the text from candidates[0].content.parts[0].text |
| 111 | if (json_response.get("candidates") and |
| 112 | len(json_response["candidates"]) > 0 and |
| 113 | json_response["candidates"][0].get("content") and |
| 114 | json_response["candidates"][0]["content"].get("parts") and |
| 115 | len(json_response["candidates"][0]["content"]["parts"]) > 0): |
| 116 | |
| 117 | output = json_response["candidates"][0]["content"]["parts"][0]["text"] |
| 118 | else: |
| 119 | raise ValueError("Unexpected response structure from Gemini API") |
| 120 | |
| 121 | output = str(output) |
| 122 | output = output[7:-3] |
| 123 | output = json.dumps({"output": output}) |
| 124 | logger("printing:") |
| 125 | logger(output) |
| 126 | |
| 127 | return output |
| 128 | |
| 129 | except requests.exceptions.RequestException as e: |
| 130 | raise Exception(f"API request failed: {str(e)}") |
| 131 | except ValueError as e: |
| 132 | raise Exception(f"Error processing response: {str(e)}") |