gac 1.0.0__py3-none-any.whl → 1.1.0__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.

Potentially problematic release.


This version of gac might be problematic. Click here for more details.

gac/ai_providers.py DELETED
@@ -1,404 +0,0 @@
1
- """Direct HTTP API calls to AI providers using httpx.
2
-
3
- This module provides functions for making direct HTTP API calls to various AI providers.
4
- Each provider has its own function to generate commit messages using only httpx.
5
- """
6
-
7
- import logging
8
- import os
9
- import time
10
-
11
- import httpx
12
- from halo import Halo
13
-
14
- from gac.constants import EnvDefaults
15
- from gac.errors import AIError
16
-
17
- logger = logging.getLogger(__name__)
18
-
19
-
20
- def _classify_error(error_str: str) -> str:
21
- """Classify error types based on error message content."""
22
- error_str = error_str.lower()
23
-
24
- if (
25
- "api key" in error_str
26
- or "unauthorized" in error_str
27
- or "authentication" in error_str
28
- or "invalid api key" in error_str
29
- ):
30
- return "authentication"
31
- elif "timeout" in error_str or "timed out" in error_str or "request timeout" in error_str:
32
- return "timeout"
33
- elif "rate limit" in error_str or "too many requests" in error_str or "rate limit exceeded" in error_str:
34
- return "rate_limit"
35
- elif "connect" in error_str or "network" in error_str or "network connection failed" in error_str:
36
- return "connection"
37
- elif "model" in error_str or "not found" in error_str or "model not found" in error_str:
38
- return "model"
39
- else:
40
- return "unknown"
41
-
42
-
43
- def anthropic_generate(
44
- model: str,
45
- prompt: str | tuple[str, str],
46
- temperature: float = EnvDefaults.TEMPERATURE,
47
- max_tokens: int = EnvDefaults.MAX_OUTPUT_TOKENS,
48
- max_retries: int = EnvDefaults.MAX_RETRIES,
49
- quiet: bool = False,
50
- ) -> str:
51
- """Generate commit message using Anthropic API with retry logic.
52
-
53
- Args:
54
- model: The model name (e.g., 'claude-3-5-haiku-latest', 'claude-3-opus-latest')
55
- prompt: Either a string prompt or tuple of (system_prompt, user_prompt)
56
- temperature: Controls randomness (0.0-1.0)
57
- max_tokens: Maximum tokens in the response
58
- max_retries: Number of retry attempts if generation fails
59
- quiet: If True, suppress progress indicators
60
-
61
- Returns:
62
- A formatted commit message string
63
-
64
- Raises:
65
- AIError: If generation fails after max_retries attempts
66
- """
67
- api_key = os.getenv("ANTHROPIC_API_KEY")
68
- if not api_key:
69
- raise AIError.model_error("ANTHROPIC_API_KEY environment variable not set")
70
-
71
- # Handle both old (string) and new (tuple) prompt formats
72
- if isinstance(prompt, tuple):
73
- system_prompt, user_prompt = prompt
74
- messages = [{"role": "user", "content": user_prompt}]
75
- payload = {
76
- "model": model,
77
- "messages": messages,
78
- "system": system_prompt,
79
- "temperature": temperature,
80
- "max_tokens": max_tokens,
81
- }
82
- else:
83
- # Backward compatibility: treat string as user prompt
84
- messages = [{"role": "user", "content": prompt}]
85
- payload = {
86
- "model": model,
87
- "messages": messages,
88
- "temperature": temperature,
89
- "max_tokens": max_tokens,
90
- }
91
-
92
- headers = {
93
- "Content-Type": "application/json",
94
- "x-api-key": api_key,
95
- "anthropic-version": "2023-06-01",
96
- }
97
-
98
- return _make_request_with_retry(
99
- url="https://api.anthropic.com/v1/messages",
100
- headers=headers,
101
- payload=payload,
102
- provider_name=f"Anthropic {model}",
103
- max_retries=max_retries,
104
- quiet=quiet,
105
- response_parser=lambda r: r["content"][0]["text"],
106
- )
107
-
108
-
109
- def cerebras_generate(
110
- model: str,
111
- prompt: str | tuple[str, str],
112
- temperature: float = EnvDefaults.TEMPERATURE,
113
- max_tokens: int = EnvDefaults.MAX_OUTPUT_TOKENS,
114
- max_retries: int = EnvDefaults.MAX_RETRIES,
115
- quiet: bool = False,
116
- ) -> str:
117
- """Generate commit message using Cerebras API with retry logic.
118
-
119
- Args:
120
- model: The model name (e.g., 'llama3.1-8b', 'llama3.1-70b')
121
- prompt: Either a string prompt or tuple of (system_prompt, user_prompt)
122
- temperature: Controls randomness (0.0-1.0)
123
- max_tokens: Maximum tokens in the response
124
- max_retries: Number of retry attempts if generation fails
125
- quiet: If True, suppress progress indicators
126
-
127
- Returns:
128
- A formatted commit message string
129
-
130
- Raises:
131
- AIError: If generation fails after max_retries attempts
132
- """
133
- api_key = os.getenv("CEREBRAS_API_KEY")
134
- if not api_key:
135
- raise AIError.model_error("CEREBRAS_API_KEY environment variable not set")
136
-
137
- # Handle both old (string) and new (tuple) prompt formats
138
- if isinstance(prompt, tuple):
139
- system_prompt, user_prompt = prompt
140
- messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}]
141
- else:
142
- # Backward compatibility: treat string as user prompt
143
- messages = [{"role": "user", "content": prompt}]
144
-
145
- payload = {
146
- "model": model,
147
- "messages": messages,
148
- "temperature": temperature,
149
- "max_tokens": max_tokens,
150
- }
151
-
152
- headers = {
153
- "Content-Type": "application/json",
154
- "Authorization": f"Bearer {api_key}",
155
- }
156
-
157
- return _make_request_with_retry(
158
- url="https://api.cerebras.ai/v1/chat/completions",
159
- headers=headers,
160
- payload=payload,
161
- provider_name=f"Cerebras {model}",
162
- max_retries=max_retries,
163
- quiet=quiet,
164
- response_parser=lambda r: r["choices"][0]["message"]["content"],
165
- )
166
-
167
-
168
- def groq_generate(
169
- model: str,
170
- prompt: str | tuple[str, str],
171
- temperature: float = EnvDefaults.TEMPERATURE,
172
- max_tokens: int = EnvDefaults.MAX_OUTPUT_TOKENS,
173
- max_retries: int = EnvDefaults.MAX_RETRIES,
174
- quiet: bool = False,
175
- ) -> str:
176
- """Generate commit message using Groq API with retry logic.
177
-
178
- Args:
179
- model: The model name (e.g., 'llama3-8b-8192', 'llama3-70b-8192')
180
- prompt: Either a string prompt or tuple of (system_prompt, user_prompt)
181
- temperature: Controls randomness (0.0-1.0)
182
- max_tokens: Maximum tokens in the response
183
- max_retries: Number of retry attempts if generation fails
184
- quiet: If True, suppress progress indicators
185
-
186
- Returns:
187
- A formatted commit message string
188
-
189
- Raises:
190
- AIError: If generation fails after max_retries attempts
191
- """
192
- api_key = os.getenv("GROQ_API_KEY")
193
- if not api_key:
194
- raise AIError.model_error("GROQ_API_KEY environment variable not set")
195
-
196
- # Handle both old (string) and new (tuple) prompt formats
197
- if isinstance(prompt, tuple):
198
- system_prompt, user_prompt = prompt
199
- messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}]
200
- else:
201
- # Backward compatibility: treat string as user prompt
202
- messages = [{"role": "user", "content": prompt}]
203
-
204
- payload = {
205
- "model": model,
206
- "messages": messages,
207
- "temperature": temperature,
208
- "max_tokens": max_tokens,
209
- }
210
-
211
- headers = {
212
- "Content-Type": "application/json",
213
- "Authorization": f"Bearer {api_key}",
214
- }
215
-
216
- return _make_request_with_retry(
217
- url="https://api.groq.com/openai/v1/chat/completions",
218
- headers=headers,
219
- payload=payload,
220
- provider_name=f"Groq {model}",
221
- max_retries=max_retries,
222
- quiet=quiet,
223
- response_parser=lambda r: r["choices"][0]["message"]["content"],
224
- )
225
-
226
-
227
- def ollama_generate(
228
- model: str,
229
- prompt: str | tuple[str, str],
230
- temperature: float = EnvDefaults.TEMPERATURE,
231
- max_tokens: int = EnvDefaults.MAX_OUTPUT_TOKENS,
232
- max_retries: int = EnvDefaults.MAX_RETRIES,
233
- quiet: bool = False,
234
- ) -> str:
235
- """Generate commit message using Ollama API with retry logic.
236
-
237
- Args:
238
- model: The model name (e.g., 'llama3', 'mistral')
239
- prompt: Either a string prompt or tuple of (system_prompt, user_prompt)
240
- temperature: Controls randomness (0.0-1.0)
241
- max_tokens: Maximum tokens in the response (note: Ollama uses 'num_predict')
242
- max_retries: Number of retry attempts if generation fails
243
- quiet: If True, suppress progress indicators
244
-
245
- Returns:
246
- A formatted commit message string
247
-
248
- Raises:
249
- AIError: If generation fails after max_retries attempts
250
- """
251
- # Handle both old (string) and new (tuple) prompt formats
252
- if isinstance(prompt, tuple):
253
- system_prompt, user_prompt = prompt
254
- messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}]
255
- else:
256
- # Backward compatibility: treat string as user prompt
257
- messages = [{"role": "user", "content": prompt}]
258
-
259
- payload = {
260
- "model": model,
261
- "messages": messages,
262
- "stream": False,
263
- "options": {
264
- "temperature": temperature,
265
- "num_predict": max_tokens,
266
- },
267
- }
268
-
269
- headers = {
270
- "Content-Type": "application/json",
271
- }
272
-
273
- # Ollama typically runs locally on port 11434
274
- ollama_url = os.getenv("OLLAMA_URL", "http://localhost:11434")
275
-
276
- return _make_request_with_retry(
277
- url=f"{ollama_url}/api/chat",
278
- headers=headers,
279
- payload=payload,
280
- provider_name=f"Ollama {model}",
281
- max_retries=max_retries,
282
- quiet=quiet,
283
- response_parser=lambda r: r["message"]["content"],
284
- )
285
-
286
-
287
- def openai_generate(
288
- model: str,
289
- prompt: str | tuple[str, str],
290
- temperature: float = EnvDefaults.TEMPERATURE,
291
- max_tokens: int = EnvDefaults.MAX_OUTPUT_TOKENS,
292
- max_retries: int = EnvDefaults.MAX_RETRIES,
293
- quiet: bool = False,
294
- ) -> str:
295
- """Generate commit message using OpenAI API with retry logic.
296
-
297
- Args:
298
- model: The model name (e.g., 'gpt-4', 'gpt-3.5-turbo')
299
- prompt: Either a string prompt or tuple of (system_prompt, user_prompt)
300
- temperature: Controls randomness (0.0-1.0)
301
- max_tokens: Maximum tokens in the response
302
- max_retries: Number of retry attempts if generation fails
303
- quiet: If True, suppress progress indicators
304
-
305
- Returns:
306
- A formatted commit message string
307
-
308
- Raises:
309
- AIError: If generation fails after max_retries attempts
310
- """
311
- api_key = os.getenv("OPENAI_API_KEY")
312
- if not api_key:
313
- raise AIError.model_error("OPENAI_API_KEY environment variable not set")
314
-
315
- # Handle both old (string) and new (tuple) prompt formats
316
- if isinstance(prompt, tuple):
317
- system_prompt, user_prompt = prompt
318
- messages = [{"role": "system", "content": system_prompt}, {"role": "user", "content": user_prompt}]
319
- else:
320
- # Backward compatibility: treat string as user prompt
321
- messages = [{"role": "user", "content": prompt}]
322
-
323
- payload = {
324
- "model": model,
325
- "messages": messages,
326
- "temperature": temperature,
327
- "max_tokens": max_tokens,
328
- }
329
-
330
- headers = {
331
- "Content-Type": "application/json",
332
- "Authorization": f"Bearer {api_key}",
333
- }
334
-
335
- return _make_request_with_retry(
336
- url="https://api.openai.com/v1/chat/completions",
337
- headers=headers,
338
- payload=payload,
339
- provider_name=f"OpenAI {model}",
340
- max_retries=max_retries,
341
- quiet=quiet,
342
- response_parser=lambda r: r["choices"][0]["message"]["content"],
343
- )
344
-
345
-
346
- def _make_request_with_retry(
347
- url: str,
348
- headers: dict,
349
- payload: dict,
350
- provider_name: str,
351
- max_retries: int,
352
- quiet: bool,
353
- response_parser: callable,
354
- ) -> str:
355
- """Make HTTP request with retry logic and common error handling."""
356
- if quiet:
357
- spinner = None
358
- else:
359
- spinner = Halo(text=f"Generating commit message with {provider_name}...", spinner="dots")
360
- spinner.start()
361
-
362
- last_error = None
363
- retry_count = 0
364
-
365
- while retry_count < max_retries:
366
- try:
367
- logger.debug(f"Trying with {provider_name} (attempt {retry_count + 1}/{max_retries})")
368
-
369
- with httpx.Client(timeout=30.0) as client:
370
- response = client.post(url, headers=headers, json=payload)
371
- response.raise_for_status()
372
-
373
- response_data = response.json()
374
- message = response_parser(response_data)
375
-
376
- if spinner:
377
- spinner.succeed(f"Generated commit message with {provider_name}")
378
-
379
- return message
380
-
381
- except Exception as e:
382
- last_error = e
383
- retry_count += 1
384
-
385
- if retry_count == max_retries:
386
- logger.warning(f"Error generating commit message: {e}. Giving up.")
387
- break
388
-
389
- wait_time = 2**retry_count
390
- logger.warning(f"Error generating commit message: {e}. Retrying in {wait_time}s...")
391
- if spinner:
392
- for i in range(wait_time, 0, -1):
393
- spinner.text = f"Retry {retry_count}/{max_retries} in {i}s..."
394
- time.sleep(1)
395
- else:
396
- time.sleep(wait_time)
397
-
398
- if spinner:
399
- spinner.fail(f"Failed to generate commit message with {provider_name}")
400
-
401
- error_type = _classify_error(str(last_error))
402
- raise AIError(
403
- f"Failed to generate commit message after {max_retries} attempts: {last_error}", error_type=error_type
404
- )
@@ -1,21 +0,0 @@
1
- gac/__init__.py,sha256=T3KAW47ZmvB5AozG_uL92ryBYgp-2LNEztBaxaY3dJE,674
2
- gac/__version__.py,sha256=dFDGI6kSyoMIM0lfv_qWhBcmDf6A-bxqO14NKF-1bbg,66
3
- gac/ai.py,sha256=7rqXXXXNZiQe1vsPNoFU-jnLXfbnTTmnGKUYBZXpCFI,4928
4
- gac/ai_providers.py,sha256=QiVSspn0cauxl7m1Chn6nw1kAO1ByAuPiQqZWyZZCys,13210
5
- gac/cli.py,sha256=eQS8S7v6p0CfN9wtr239ujYGTi9rKl-KV7STX2U-C3w,4581
6
- gac/config.py,sha256=wSgEDjtis7Vk1pv5VPvYmJyD9-tymDS6GiUHjnCMbIM,1486
7
- gac/config_cli.py,sha256=v9nFHZO1RvK9fzHyuUS6SG-BCLHMsdOMDwWamBhVVh4,1608
8
- gac/constants.py,sha256=MAxdASGncfZY1TdKGdhJZ0wvTBEU3gTN6KEdw8n3Bd8,4844
9
- gac/diff_cli.py,sha256=wnVQ9OFGnM0d2Pj9WVjWbo0jxqIuRHVAwmb8wU9Pa3E,5676
10
- gac/errors.py,sha256=3vIRMQ2QF3sP9_rPfXAFuu5ZSjIVX4FxM-FAuiR8N-8,7416
11
- gac/git.py,sha256=MS2m4fv8h4mau1djFG1aje9NXTmkGsjPO9w18LqNGX0,6031
12
- gac/init_cli.py,sha256=aNllguofrcLn0ML9tzLVWFkPbwlAvCM9m7undHhMLEo,1825
13
- gac/main.py,sha256=WI7mxIbL05neQr1VfoopOeZKIonwpwFeZCt_4VFewPY,11987
14
- gac/preprocess.py,sha256=4igtZ9OTHgTpqwlJmbcGaqzmdD0HHCZJwsZ9eG118Gk,15360
15
- gac/prompt.py,sha256=_fv24XU3DZE_S72vcdUYnNkmy-_KXnr1Vlc-9okop7E,17263
16
- gac/utils.py,sha256=W3ladtmsH01MNLdckQYTzYrYbTGEdzCKI36he9C-y_E,3945
17
- gac-1.0.0.dist-info/METADATA,sha256=OOLz0xmLbHsSAgfKa0830-zIGhwT_9VMqlI7b72cV6Y,8351
18
- gac-1.0.0.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
19
- gac-1.0.0.dist-info/entry_points.txt,sha256=tdjN-XMmcWfL92swuRAjT62bFLOAwk9bTMRLGP5Z4aI,36
20
- gac-1.0.0.dist-info/licenses/LICENSE,sha256=vOab37NouL1PNs5BswnPayrMCqaN2sqLfMQfqPDrpZg,1103
21
- gac-1.0.0.dist-info/RECORD,,
File without changes