File size: 2,887 Bytes
f837c69
 
109f376
 
bd2a75a
e16c6ed
109f376
 
e16c6ed
bd2a75a
6005177
109f376
bd2a75a
e16c6ed
 
109f376
 
 
 
bd2a75a
109f376
 
 
 
 
 
 
 
e16c6ed
 
b52c266
109f376
b52c266
 
109f376
b52c266
 
109f376
 
 
 
 
 
 
 
 
 
 
 
 
e16c6ed
109f376
 
 
 
 
e16c6ed
 
 
 
109f376
e16c6ed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109f376
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""Initialize and export a GenAI client using the provided Google API key."""

from __future__ import annotations

import os
import time
from typing import Any

import httpx
from dotenv import load_dotenv
from google import genai
from google.api_core.exceptions import GoogleAPIError

from .output_schema import Presentation

# --------------------------------------------------------------------------- #
#  Globals
# --------------------------------------------------------------------------- #

load_dotenv()
GOOGLE_API_KEY: str | None = os.getenv("GOOGLE_API_KEY")

# A singleton Gemini client that the rest of the project can import.
client: genai.Client = genai.Client(api_key=GOOGLE_API_KEY)

# --------------------------------------------------------------------------- #
#  Public helpers
# --------------------------------------------------------------------------- #


def generate_with_retry(
    genai_client: genai.Client,
    model_name: str,
    prompt: str,
    *,
    max_retries: int = 3,
    retry_delay: int = 2,
) -> Any:
    """Generate content using the specified model with retry logic for transient errors.

    Args:
        client (genai.Client): The GenAI client instance.
        model_name (str): The name of the model to use for content generation.
        prompt (str): The prompt to send to the model.
        max_retries (int): Maximum number of retry attempts for transient errors.
        retry_delay (int): Delay between retries in seconds.

    Returns:
        Any
        The response returned by ``genai_client.generate()``.

    Raises:
        httpx.RemoteProtocolError: If the server disconnects unexpectedly.
        httpx.HTTPError: For other HTTP-related errors.
        GoogleAPIError: For errors specific to the Google API.
    """
    answer = None

    for attempt in range(1, max_retries + 1):
        try:
            answer = genai_client.models.generate_content(
                model=model_name,
                contents=prompt,
                config={
                    "response_mime_type": "application/json",
                    "response_schema": Presentation,
                },
            )
            return answer

        except httpx.RemoteProtocolError as e:
            print(f"[Attempt {attempt}] Server disconnected: {e}")
            if attempt < max_retries:
                time.sleep(retry_delay)
            else:
                raise  # re-raise if out of retries

        except httpx.HTTPError as e:
            print(f"[Attempt {attempt}] HTTP error: {e}")
            raise  # you might not want to retry on all HTTP errors

        except GoogleAPIError as e:
            print(f"Google API error: {e}")
            raise

        except Exception as e:
            print(f"Unexpected error: {e}")
            raise
    raise RuntimeError("generate_with_retry exhausted retries without returning")