ccs-llmconnector 1.0.3__py3-none-any.whl → 1.0.5__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,224 +1,296 @@
1
- """Thin wrapper around the Google Gemini API via the google-genai SDK."""
2
-
3
- from __future__ import annotations
4
-
5
- import base64
6
- import mimetypes
7
- from pathlib import Path
8
- import logging
9
- from typing import Optional, Sequence, Union
10
- from urllib.error import URLError
11
- from urllib.request import urlopen
12
-
13
- from google import genai
14
- from google.genai import types
15
-
16
- ImageInput = Union[str, Path]
17
- logger = logging.getLogger(__name__)
18
-
19
-
20
- class GeminiClient:
21
- """Convenience wrapper around the Google Gemini SDK."""
22
-
23
- def generate_response(
24
- self,
25
- *,
26
- api_key: str,
27
- prompt: str,
28
- model: str,
29
- max_tokens: int = 32000,
30
- reasoning_effort: Optional[str] = None,
31
- images: Optional[Sequence[ImageInput]] = None,
32
- ) -> str:
33
- """Generate a response from the specified Gemini model.
34
-
35
- Args:
36
- api_key: API key used to authenticate with the Gemini API.
37
- prompt: Natural-language instruction or query for the model.
38
- model: Identifier of the Gemini model to target (for example, ``"gemini-2.5-flash"``).
39
- max_tokens: Cap for tokens across the entire exchange, defaults to 32000.
40
- reasoning_effort: Included for API parity; currently unused by the Gemini SDK.
41
- images: Optional collection of image references (local paths, URLs, or data URLs).
42
-
43
- Returns:
44
- The text output produced by the model.
45
-
46
- Raises:
47
- ValueError: If required arguments are missing or the request payload is empty.
48
- URLError: If an image URL cannot be retrieved.
49
- google.genai.errors.APIError: If the underlying Gemini request fails.
50
- """
51
- if not api_key:
52
- raise ValueError("api_key must be provided.")
53
- if not prompt and not images:
54
- raise ValueError("At least one of prompt or images must be provided.")
55
- if not model:
56
- raise ValueError("model must be provided.")
57
-
58
- parts: list[types.Part] = []
59
- if prompt:
60
- parts.append(types.Part.from_text(text=prompt))
61
-
62
- if images:
63
- for image in images:
64
- parts.append(self._to_image_part(image))
65
-
66
- if not parts:
67
- raise ValueError("No content provided for response generation.")
68
-
69
- content = types.Content(role="user", parts=parts)
70
-
71
- config = types.GenerateContentConfig(max_output_tokens=max_tokens)
72
- # reasoning_effort is accepted for compatibility but not currently applied because the
73
- # Gemini SDK does not expose an equivalent configuration parameter.
74
-
75
- client = genai.Client(api_key=api_key)
76
- try:
77
- try:
78
- response = client.models.generate_content(
79
- model=model,
80
- contents=[content],
81
- config=config,
82
- )
83
- except Exception as exc:
84
- logger.exception("Gemini generate_content failed: %s", exc)
85
- raise
86
- finally:
87
- closer = getattr(client, "close", None)
88
- if callable(closer):
89
- try:
90
- closer()
91
- except Exception:
92
- pass
93
-
94
- if response.text:
95
- result_text = response.text
96
- logger.info(
97
- "Gemini generate_content succeeded: model=%s images=%d text_len=%d",
98
- model,
99
- len(images or []),
100
- len(result_text or ""),
101
- )
102
- return result_text
103
-
104
- candidate_texts: list[str] = []
105
- for candidate in getattr(response, "candidates", []) or []:
106
- content_obj = getattr(candidate, "content", None)
107
- if not content_obj:
108
- continue
109
- for part in getattr(content_obj, "parts", []) or []:
110
- text = getattr(part, "text", None)
111
- if text:
112
- candidate_texts.append(text)
113
-
114
- if candidate_texts:
115
- result_text = "\n".join(candidate_texts)
116
- logger.info(
117
- "Gemini generate_content succeeded (candidates): model=%s images=%d text_len=%d",
118
- model,
119
- len(images or []),
120
- len(result_text or ""),
121
- )
122
- return result_text
123
-
124
- # Treat successful calls without textual content as a successful, empty response
125
- # rather than raising. This aligns with callers that handle empty outputs gracefully.
126
- logger.info(
127
- "Gemini generate_content succeeded with no text: model=%s images=%d",
128
- model,
129
- len(images or []),
130
- )
131
- return ""
132
-
133
- def list_models(self, *, api_key: str) -> list[dict[str, Optional[str]]]:
134
- """Return the models available to the authenticated Gemini account."""
135
- if not api_key:
136
- raise ValueError("api_key must be provided.")
137
-
138
- models: list[dict[str, Optional[str]]] = []
139
- client = genai.Client(api_key=api_key)
140
- try:
141
- try:
142
- iterator = client.models.list()
143
- except Exception as exc:
144
- logger.exception("Gemini list models failed: %s", exc)
145
- raise
146
- for model in iterator:
147
- model_id = getattr(model, "name", None)
148
- if model_id is None and isinstance(model, dict):
149
- model_id = model.get("name")
150
- if not model_id:
151
- continue
152
-
153
- # Normalize IDs like "models/<id>" -> "<id>"
154
- if isinstance(model_id, str) and model_id.startswith("models/"):
155
- model_id = model_id.split("/", 1)[1]
156
-
157
- display_name = getattr(model, "display_name", None)
158
- if display_name is None and isinstance(model, dict):
159
- display_name = model.get("display_name")
160
-
161
- models.append({"id": model_id, "display_name": display_name})
162
- finally:
163
- closer = getattr(client, "close", None)
164
- if callable(closer):
165
- try:
166
- closer()
167
- except Exception:
168
- pass
169
-
170
- logger.info("Gemini list_models succeeded: count=%d", len(models))
171
- return models
172
-
173
- @staticmethod
174
- def _to_image_part(image: ImageInput) -> types.Part:
175
- """Convert an image reference into a Gemini SDK part."""
176
- if isinstance(image, Path):
177
- return _part_from_path(image)
178
-
179
- if image.startswith("data:"):
180
- return _part_from_data_url(image)
181
-
182
- if image.startswith(("http://", "https://")):
183
- return _part_from_url(image)
184
-
185
- return _part_from_path(Path(image))
186
-
187
-
188
- def _part_from_path(path: Path) -> types.Part:
189
- """Create an image part from a local filesystem path."""
190
- expanded = path.expanduser()
191
- data = expanded.read_bytes()
192
- mime_type = mimetypes.guess_type(expanded.name)[0] or "application/octet-stream"
193
- return types.Part.from_bytes(data=data, mime_type=mime_type)
194
-
195
-
196
- def _part_from_url(url: str) -> types.Part:
197
- """Create an image part by downloading content from a URL."""
198
- with urlopen(url) as response:
199
- data = response.read()
200
- mime_type = response.info().get_content_type()
201
-
202
- if not mime_type or mime_type == "application/octet-stream":
203
- mime_type = mimetypes.guess_type(url)[0] or "application/octet-stream"
204
-
205
- return types.Part.from_bytes(data=data, mime_type=mime_type)
206
-
207
-
208
- def _part_from_data_url(data_url: str) -> types.Part:
209
- """Create an image part from a data URL."""
210
- header, encoded = data_url.split(",", 1)
211
- metadata = header[len("data:") :]
212
- mime_type = "application/octet-stream"
213
-
214
- if ";" in metadata:
215
- mime_type, _, metadata = metadata.partition(";")
216
- elif metadata:
217
- mime_type = metadata
218
-
219
- if "base64" in metadata:
220
- data = base64.b64decode(encoded)
221
- else:
222
- data = encoded.encode("utf-8")
223
-
224
- return types.Part.from_bytes(data=data, mime_type=mime_type or "application/octet-stream")
1
+ """Thin wrapper around the Google Gemini API via the google-genai SDK."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import base64
6
+ import mimetypes
7
+ from pathlib import Path
8
+ import logging
9
+ from typing import Optional, Sequence, Union
10
+ from urllib.error import URLError
11
+ from urllib.request import urlopen
12
+
13
+ from google import genai
14
+ from google.genai import types
15
+
16
+ ImageInput = Union[str, Path]
17
+ logger = logging.getLogger(__name__)
18
+
19
+
20
+ class GeminiClient:
21
+ """Convenience wrapper around the Google Gemini SDK."""
22
+
23
+ def generate_response(
24
+ self,
25
+ *,
26
+ api_key: str,
27
+ prompt: str,
28
+ model: str,
29
+ max_tokens: int = 32000,
30
+ reasoning_effort: Optional[str] = None,
31
+ images: Optional[Sequence[ImageInput]] = None,
32
+ ) -> str:
33
+ """Generate a response from the specified Gemini model.
34
+
35
+ Args:
36
+ api_key: API key used to authenticate with the Gemini API.
37
+ prompt: Natural-language instruction or query for the model.
38
+ model: Identifier of the Gemini model to target (for example, ``"gemini-2.5-flash"``).
39
+ max_tokens: Cap for tokens across the entire exchange, defaults to 32000.
40
+ reasoning_effort: Included for API parity; currently unused by the Gemini SDK.
41
+ images: Optional collection of image references (local paths, URLs, or data URLs).
42
+
43
+ Returns:
44
+ The text output produced by the model.
45
+
46
+ Raises:
47
+ ValueError: If required arguments are missing or the request payload is empty.
48
+ URLError: If an image URL cannot be retrieved.
49
+ google.genai.errors.APIError: If the underlying Gemini request fails.
50
+ """
51
+ if not api_key:
52
+ raise ValueError("api_key must be provided.")
53
+ if not prompt and not images:
54
+ raise ValueError("At least one of prompt or images must be provided.")
55
+ if not model:
56
+ raise ValueError("model must be provided.")
57
+
58
+ parts: list[types.Part] = []
59
+ if prompt:
60
+ parts.append(types.Part.from_text(text=prompt))
61
+
62
+ if images:
63
+ for image in images:
64
+ parts.append(self._to_image_part(image))
65
+
66
+ if not parts:
67
+ raise ValueError("No content provided for response generation.")
68
+
69
+ content = types.Content(role="user", parts=parts)
70
+
71
+ config = types.GenerateContentConfig(max_output_tokens=max_tokens)
72
+ # reasoning_effort is accepted for compatibility but not currently applied because the
73
+ # Gemini SDK does not expose an equivalent configuration parameter.
74
+
75
+ client = genai.Client(api_key=api_key)
76
+ try:
77
+ try:
78
+ response = client.models.generate_content(
79
+ model=model,
80
+ contents=[content],
81
+ config=config,
82
+ )
83
+ except Exception as exc:
84
+ logger.exception("Gemini generate_content failed: %s", exc)
85
+ raise
86
+ finally:
87
+ closer = getattr(client, "close", None)
88
+ if callable(closer):
89
+ try:
90
+ closer()
91
+ except Exception:
92
+ pass
93
+
94
+ if response.text:
95
+ result_text = response.text
96
+ logger.info(
97
+ "Gemini generate_content succeeded: model=%s images=%d text_len=%d",
98
+ model,
99
+ len(images or []),
100
+ len(result_text or ""),
101
+ )
102
+ return result_text
103
+
104
+ candidate_texts: list[str] = []
105
+ for candidate in getattr(response, "candidates", []) or []:
106
+ content_obj = getattr(candidate, "content", None)
107
+ if not content_obj:
108
+ continue
109
+ for part in getattr(content_obj, "parts", []) or []:
110
+ text = getattr(part, "text", None)
111
+ if text:
112
+ candidate_texts.append(text)
113
+
114
+ if candidate_texts:
115
+ result_text = "\n".join(candidate_texts)
116
+ logger.info(
117
+ "Gemini generate_content succeeded (candidates): model=%s images=%d text_len=%d",
118
+ model,
119
+ len(images or []),
120
+ len(result_text or ""),
121
+ )
122
+ return result_text
123
+
124
+ # Treat successful calls without textual content as a successful, empty response
125
+ # rather than raising. This aligns with callers that handle empty outputs gracefully.
126
+ logger.info(
127
+ "Gemini generate_content succeeded with no text: model=%s images=%d",
128
+ model,
129
+ len(images or []),
130
+ )
131
+ return ""
132
+
133
+ def generate_image(
134
+ self,
135
+ *,
136
+ api_key: str,
137
+ prompt: str,
138
+ model: str,
139
+ image_size: str = "2K",
140
+ image: Optional[ImageInput] = None,
141
+ ) -> bytes:
142
+ """Generate an image using Gemini 3 Pro Image.
143
+
144
+ Args:
145
+ api_key: API key used to authenticate with the Gemini API.
146
+ prompt: Text prompt for image generation.
147
+ model: Identifier of the Gemini model to target (e.g., "gemini-3-pro-image-preview").
148
+ image_size: Size of the generated image (e.g., "2K", "4K"). Defaults to "2K".
149
+ image: Optional input image for editing tasks.
150
+
151
+ Returns:
152
+ The generated image data as bytes.
153
+
154
+ Raises:
155
+ ValueError: If required arguments are missing or no image is returned.
156
+ google.genai.errors.APIError: If the underlying Gemini request fails.
157
+ """
158
+ if not api_key:
159
+ raise ValueError("api_key must be provided.")
160
+ if not prompt:
161
+ raise ValueError("prompt must be provided.")
162
+ if not model:
163
+ raise ValueError("model must be provided.")
164
+
165
+ client = genai.Client(api_key=api_key)
166
+
167
+ config = types.GenerateContentConfig(
168
+ tools=[{"google_search": {}}],
169
+ image_config=types.ImageConfig(
170
+ image_size=image_size
171
+ )
172
+ )
173
+
174
+ contents = [prompt]
175
+ if image:
176
+ contents.append(self._to_image_part(image))
177
+
178
+ try:
179
+ try:
180
+ response = client.models.generate_content(
181
+ model=model,
182
+ contents=contents,
183
+ config=config,
184
+ )
185
+ except Exception as exc:
186
+ logger.exception("Gemini generate_image failed: %s", exc)
187
+ raise
188
+ finally:
189
+ closer = getattr(client, "close", None)
190
+ if callable(closer):
191
+ try:
192
+ closer()
193
+ except Exception:
194
+ pass
195
+
196
+ if not response.parts:
197
+ raise ValueError("No content returned from Gemini.")
198
+
199
+ for part in response.parts:
200
+ if part.inline_data:
201
+ return part.inline_data.data
202
+
203
+ raise ValueError("No image data found in response.")
204
+
205
+ def list_models(self, *, api_key: str) -> list[dict[str, Optional[str]]]:
206
+ """Return the models available to the authenticated Gemini account."""
207
+ if not api_key:
208
+ raise ValueError("api_key must be provided.")
209
+
210
+ models: list[dict[str, Optional[str]]] = []
211
+ client = genai.Client(api_key=api_key)
212
+ try:
213
+ try:
214
+ iterator = client.models.list()
215
+ except Exception as exc:
216
+ logger.exception("Gemini list models failed: %s", exc)
217
+ raise
218
+ for model in iterator:
219
+ model_id = getattr(model, "name", None)
220
+ if model_id is None and isinstance(model, dict):
221
+ model_id = model.get("name")
222
+ if not model_id:
223
+ continue
224
+
225
+ # Normalize IDs like "models/<id>" -> "<id>"
226
+ if isinstance(model_id, str) and model_id.startswith("models/"):
227
+ model_id = model_id.split("/", 1)[1]
228
+
229
+ display_name = getattr(model, "display_name", None)
230
+ if display_name is None and isinstance(model, dict):
231
+ display_name = model.get("display_name")
232
+
233
+ models.append({"id": model_id, "display_name": display_name})
234
+ finally:
235
+ closer = getattr(client, "close", None)
236
+ if callable(closer):
237
+ try:
238
+ closer()
239
+ except Exception:
240
+ pass
241
+
242
+ logger.info("Gemini list_models succeeded: count=%d", len(models))
243
+ return models
244
+
245
+ @staticmethod
246
+ def _to_image_part(image: ImageInput) -> types.Part:
247
+ """Convert an image reference into a Gemini SDK part."""
248
+ if isinstance(image, Path):
249
+ return _part_from_path(image)
250
+
251
+ if image.startswith("data:"):
252
+ return _part_from_data_url(image)
253
+
254
+ if image.startswith(("http://", "https://")):
255
+ return _part_from_url(image)
256
+
257
+ return _part_from_path(Path(image))
258
+
259
+
260
+ def _part_from_path(path: Path) -> types.Part:
261
+ """Create an image part from a local filesystem path."""
262
+ expanded = path.expanduser()
263
+ data = expanded.read_bytes()
264
+ mime_type = mimetypes.guess_type(expanded.name)[0] or "application/octet-stream"
265
+ return types.Part.from_bytes(data=data, mime_type=mime_type)
266
+
267
+
268
+ def _part_from_url(url: str) -> types.Part:
269
+ """Create an image part by downloading content from a URL."""
270
+ with urlopen(url) as response:
271
+ data = response.read()
272
+ mime_type = response.info().get_content_type()
273
+
274
+ if not mime_type or mime_type == "application/octet-stream":
275
+ mime_type = mimetypes.guess_type(url)[0] or "application/octet-stream"
276
+
277
+ return types.Part.from_bytes(data=data, mime_type=mime_type)
278
+
279
+
280
+ def _part_from_data_url(data_url: str) -> types.Part:
281
+ """Create an image part from a data URL."""
282
+ header, encoded = data_url.split(",", 1)
283
+ metadata = header[len("data:") :]
284
+ mime_type = "application/octet-stream"
285
+
286
+ if ";" in metadata:
287
+ mime_type, _, metadata = metadata.partition(";")
288
+ elif metadata:
289
+ mime_type = metadata
290
+
291
+ if "base64" in metadata:
292
+ data = base64.b64decode(encoded)
293
+ else:
294
+ data = encoded.encode("utf-8")
295
+
296
+ return types.Part.from_bytes(data=data, mime_type=mime_type or "application/octet-stream")