|
| 1 | +import os |
| 2 | +from collections import defaultdict |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +from dotenv import load_dotenv |
| 6 | +from google import genai |
| 7 | +from google.genai import types |
| 8 | + |
| 9 | +from rlm.clients.base_lm import BaseLM |
| 10 | +from rlm.core.types import ModelUsageSummary, UsageSummary |
| 11 | + |
| 12 | +load_dotenv() |
| 13 | + |
| 14 | +DEFAULT_GEMINI_API_KEY = os.getenv("GEMINI_API_KEY") |
| 15 | + |
| 16 | + |
| 17 | +class GeminiClient(BaseLM): |
| 18 | + """ |
| 19 | + LM Client for running models with the Google Gemini API. |
| 20 | + Uses the official google-genai SDK. |
| 21 | + """ |
| 22 | + |
| 23 | + def __init__( |
| 24 | + self, |
| 25 | + api_key: str | None = None, |
| 26 | + model_name: str | None = "gemini-2.5-flash", |
| 27 | + **kwargs, |
| 28 | + ): |
| 29 | + super().__init__(model_name=model_name, **kwargs) |
| 30 | + |
| 31 | + if api_key is None: |
| 32 | + api_key = DEFAULT_GEMINI_API_KEY |
| 33 | + |
| 34 | + if api_key is None: |
| 35 | + raise ValueError( |
| 36 | + "Gemini API key is required. Set GEMINI_API_KEY env var or pass api_key." |
| 37 | + ) |
| 38 | + |
| 39 | + self.client = genai.Client(api_key=api_key) |
| 40 | + self.model_name = model_name |
| 41 | + |
| 42 | + # Per-model usage tracking |
| 43 | + self.model_call_counts: dict[str, int] = defaultdict(int) |
| 44 | + self.model_input_tokens: dict[str, int] = defaultdict(int) |
| 45 | + self.model_output_tokens: dict[str, int] = defaultdict(int) |
| 46 | + self.model_total_tokens: dict[str, int] = defaultdict(int) |
| 47 | + |
| 48 | + # Last call tracking |
| 49 | + self.last_prompt_tokens = 0 |
| 50 | + self.last_completion_tokens = 0 |
| 51 | + |
| 52 | + def completion(self, prompt: str | list[dict[str, Any]], model: str | None = None) -> str: |
| 53 | + contents, system_instruction = self._prepare_contents(prompt) |
| 54 | + |
| 55 | + model = model or self.model_name |
| 56 | + if not model: |
| 57 | + raise ValueError("Model name is required for Gemini client.") |
| 58 | + |
| 59 | + config = None |
| 60 | + if system_instruction: |
| 61 | + config = types.GenerateContentConfig(system_instruction=system_instruction) |
| 62 | + |
| 63 | + response = self.client.models.generate_content( |
| 64 | + model=model, |
| 65 | + contents=contents, |
| 66 | + config=config, |
| 67 | + ) |
| 68 | + |
| 69 | + self._track_cost(response, model) |
| 70 | + return response.text |
| 71 | + |
| 72 | + async def acompletion( |
| 73 | + self, prompt: str | list[dict[str, Any]], model: str | None = None |
| 74 | + ) -> str: |
| 75 | + contents, system_instruction = self._prepare_contents(prompt) |
| 76 | + |
| 77 | + model = model or self.model_name |
| 78 | + if not model: |
| 79 | + raise ValueError("Model name is required for Gemini client.") |
| 80 | + |
| 81 | + config = None |
| 82 | + if system_instruction: |
| 83 | + config = types.GenerateContentConfig(system_instruction=system_instruction) |
| 84 | + |
| 85 | + # google-genai SDK supports async via aio interface |
| 86 | + response = await self.client.aio.models.generate_content( |
| 87 | + model=model, |
| 88 | + contents=contents, |
| 89 | + config=config, |
| 90 | + ) |
| 91 | + |
| 92 | + self._track_cost(response, model) |
| 93 | + return response.text |
| 94 | + |
| 95 | + def _prepare_contents( |
| 96 | + self, prompt: str | list[dict[str, Any]] |
| 97 | + ) -> tuple[list[types.Content] | str, str | None]: |
| 98 | + """Prepare contents and extract system instruction for Gemini API.""" |
| 99 | + system_instruction = None |
| 100 | + |
| 101 | + if isinstance(prompt, str): |
| 102 | + return prompt, None |
| 103 | + |
| 104 | + if isinstance(prompt, list) and all(isinstance(item, dict) for item in prompt): |
| 105 | + # Convert OpenAI-style messages to Gemini format |
| 106 | + contents = [] |
| 107 | + for msg in prompt: |
| 108 | + role = msg.get("role") |
| 109 | + content = msg.get("content", "") |
| 110 | + |
| 111 | + if role == "system": |
| 112 | + # Gemini handles system instruction separately |
| 113 | + system_instruction = content |
| 114 | + elif role == "user": |
| 115 | + contents.append(types.Content(role="user", parts=[types.Part(text=content)])) |
| 116 | + elif role == "assistant": |
| 117 | + # Gemini uses "model" instead of "assistant" |
| 118 | + contents.append(types.Content(role="model", parts=[types.Part(text=content)])) |
| 119 | + else: |
| 120 | + # Default to user role for unknown roles |
| 121 | + contents.append(types.Content(role="user", parts=[types.Part(text=content)])) |
| 122 | + |
| 123 | + return contents, system_instruction |
| 124 | + |
| 125 | + raise ValueError(f"Invalid prompt type: {type(prompt)}") |
| 126 | + |
| 127 | + def _track_cost(self, response: types.GenerateContentResponse, model: str): |
| 128 | + self.model_call_counts[model] += 1 |
| 129 | + |
| 130 | + # Extract token usage from response |
| 131 | + usage = response.usage_metadata |
| 132 | + if usage: |
| 133 | + input_tokens = usage.prompt_token_count or 0 |
| 134 | + output_tokens = usage.candidates_token_count or 0 |
| 135 | + |
| 136 | + self.model_input_tokens[model] += input_tokens |
| 137 | + self.model_output_tokens[model] += output_tokens |
| 138 | + self.model_total_tokens[model] += input_tokens + output_tokens |
| 139 | + |
| 140 | + # Track last call for handler to read |
| 141 | + self.last_prompt_tokens = input_tokens |
| 142 | + self.last_completion_tokens = output_tokens |
| 143 | + else: |
| 144 | + self.last_prompt_tokens = 0 |
| 145 | + self.last_completion_tokens = 0 |
| 146 | + |
| 147 | + def get_usage_summary(self) -> UsageSummary: |
| 148 | + model_summaries = {} |
| 149 | + for model in self.model_call_counts: |
| 150 | + model_summaries[model] = ModelUsageSummary( |
| 151 | + total_calls=self.model_call_counts[model], |
| 152 | + total_input_tokens=self.model_input_tokens[model], |
| 153 | + total_output_tokens=self.model_output_tokens[model], |
| 154 | + ) |
| 155 | + return UsageSummary(model_usage_summaries=model_summaries) |
| 156 | + |
| 157 | + def get_last_usage(self) -> ModelUsageSummary: |
| 158 | + return ModelUsageSummary( |
| 159 | + total_calls=1, |
| 160 | + total_input_tokens=self.last_prompt_tokens, |
| 161 | + total_output_tokens=self.last_completion_tokens, |
| 162 | + ) |
0 commit comments