feat(ai): integrate GeminiCliAdapter into ai_client

This commit is contained in:
2026-02-25 14:02:06 -05:00
parent 211000c926
commit b762a80482
5 changed files with 280 additions and 1 deletions

62
gemini_cli_adapter.py Normal file
View File

@@ -0,0 +1,62 @@
import subprocess
import json
import sys
class GeminiCliAdapter:
def __init__(self, binary_path="gemini"):
self.binary_path = binary_path
self.last_usage = None
self.session_id = None
def send(self, message):
"""
Sends a message to the Gemini CLI and processes the streaming JSON output.
"""
command = [self.binary_path, 'run', message, '--output-format', 'stream-json']
if self.session_id:
command.extend(['--resume', self.session_id])
accumulated_text = ""
# Using subprocess.Popen as requested
process = subprocess.Popen(
command,
stdout=subprocess.PIPE,
text=True
)
try:
# Read stdout line by line
for line in process.stdout:
line = line.strip()
if not line:
continue
try:
data = json.loads(line)
msg_type = data.get("type")
if msg_type == "message":
# Append message text to results
accumulated_text += data.get("text", "")
elif msg_type == "result":
# Capture final usage and session persistence
self.last_usage = data.get("usage")
self.session_id = data.get("session_id")
elif msg_type in ("status", "tool_use"):
# Log status/tool_use to stderr for debugging
sys.stderr.write(f"GeminiCliAdapter [{msg_type}]: {line}\n")
sys.stderr.flush()
except json.JSONDecodeError:
# Skip lines that are not valid JSON
continue
process.wait()
except Exception as e:
process.kill()
raise e
return accumulated_text