-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathgemini_client.py
More file actions
181 lines (149 loc) · 6.48 KB
/
Copy pathgemini_client.py
File metadata and controls
181 lines (149 loc) · 6.48 KB
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
"Gemini Client - Interface for routing API calls to Gemini CLI"
import subprocess
import asyncio
from typing import Dict, List, Optional, Union, Any
from dataclasses import dataclass
@dataclass
class GenerationConfig:
temperature: Optional[float] = None
top_p: Optional[float] = None
top_k: Optional[int] = None
candidate_count: Optional[int] = None
max_output_tokens: Optional[int] = None
stop_sequences: Optional[List[str]] = None
class GeminiClient:
"""
Client that interfaces with Gemini CLI for local inference.
Converts Google Generative AI API format to Gemini CLI format and back.
"""
def __init__(self):
self.gemini_command = "gemini"
def _format_contents_for_gemini(self, contents: Union[str, List[Dict], Dict]) -> str:
"""
Format contents into a single prompt for Gemini CLI.
"""
if isinstance(contents, str):
return contents
prompt_parts = []
# Handle single dict (one message) or list of messages
if isinstance(contents, dict):
contents = [contents]
for msg in contents:
role = msg.get("role", "user")
parts = msg.get("parts", [])
content_text = ""
if isinstance(parts, list):
for part in parts:
if isinstance(part, dict):
content_text += part.get("text", "")
elif isinstance(part, str):
content_text += part
elif isinstance(parts, str):
content_text = parts
if role == "user":
prompt_parts.append(f"User: {content_text}")
elif role == "model":
prompt_parts.append(f"Model: {content_text}")
else:
prompt_parts.append(f"{role}: {content_text}")
return "\n\n".join(prompt_parts)
def _call_gemini_cli(self, prompt: str, model: Optional[str] = None) -> str:
"""
Call Gemini CLI with the formatted prompt.
"""
cmd = [self.gemini_command]
# Add model selection if specified
if model:
# Strip 'models/' prefix if present
model_name = model.split('/')[-1] if '/' in model else model
cmd.extend(["--model", model_name])
try:
# Run Gemini CLI, passing the prompt via stdin
result = subprocess.run(
cmd,
input=prompt,
capture_output=True,
text=True,
timeout=120
)
if result.returncode != 0:
error_msg = result.stderr or "Unknown error calling Gemini CLI"
raise Exception(f"Gemini CLI error: {error_msg}")
return result.stdout.strip()
except subprocess.TimeoutExpired:
raise Exception("Gemini CLI timed out after 120 seconds")
except FileNotFoundError:
raise Exception("Gemini CLI not found. Please ensure 'gemini' is installed and in PATH")
except Exception as e:
raise Exception(f"Error calling Gemini: {str(e)}")
async def _call_gemini_cli_async(self, prompt: str, model: Optional[str] = None) -> str:
"""
Call Gemini CLI asynchronously.
"""
cmd = [self.gemini_command]
if model:
model_name = model.split('/')[-1] if '/' in model else model
cmd.extend(["--model", model_name])
try:
proc = await asyncio.create_subprocess_exec(
*cmd,
stdin=asyncio.subprocess.PIPE,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await asyncio.wait_for(
proc.communicate(input=prompt.encode()),
timeout=120
)
if proc.returncode != 0:
error_msg = stderr.decode() if stderr else "Unknown error calling Gemini CLI"
raise Exception(f"Gemini CLI error: {error_msg}")
return stdout.decode().strip()
except asyncio.TimeoutError:
raise Exception("Gemini CLI timed out after 120 seconds")
except FileNotFoundError:
raise Exception("Gemini CLI not found. Please ensure 'gemini' is installed and in PATH")
except Exception as e:
raise Exception(f"Error calling Gemini: {str(e)}")
def generate_content(
self,
model: str,
contents: Union[str, List[Dict]],
generation_config: Optional[GenerationConfig] = None,
stream: bool = False
) -> Any:
"""
Generate content using Gemini CLI.
Returns a simpler object that mimics google.generativeai.types.GenerateContentResponse
"""
if stream:
raise NotImplementedError("Streaming is not yet supported with Gemini CLI routing")
prompt = self._format_contents_for_gemini(contents)
response_text = self._call_gemini_cli(prompt, model)
return self._create_response_object(response_text)
async def generate_content_async(
self,
model: str,
contents: Union[str, List[Dict]],
generation_config: Optional[GenerationConfig] = None,
stream: bool = False
) -> Any:
"""Async version of generate_content."""
if stream:
raise NotImplementedError("Streaming is not yet supported with Gemini CLI routing")
prompt = self._format_contents_for_gemini(contents)
response_text = await self._call_gemini_cli_async(prompt, model)
return self._create_response_object(response_text)
def _create_response_object(self, text: str) -> Any:
"""Creates a response object mimicking the SDK's response."""
# Simple dummy class to mimic the structure
class Candidate:
def __init__(self, text):
self.content = type('Content', (), {'parts': [type('Part', (), {'text': text})()]})()
self.finish_reason = 1 # STOP
class Response:
def __init__(self, text):
self.text = text
self.candidates = [Candidate(text)]
self.parts = [type('Part', (), {'text': text})()]
return Response(text)