8000 feat: add Ollama, vLLM, SGLang support with auto-detect and cloud fal… by meena1905 · Pull Request #7 · vominh1919/oss-copilot · GitHub
[go: up one dir, main page]

Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
129 changes: 125 additions & 4 deletions oss_copilot/utils/ai.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@ def generate_fix_with_ai(
api_key = ai_config.get("api_key", "")
base_url = ai_config.get("base_url", "")

if not api_key:
# API key not required for local providers
if not api_key and provider not in ("ollama", "local", "vllm", "sglang"):
return {
"success": False,
"message": "No AI API key configured. Run: oss-copilot config init",
Expand All @@ -69,7 +70,13 @@ def generate_fix_with_ai(
Generate a fix for this issue. Return ONLY valid JSON."""

try:
if provider == "openai":
if provider in ("ollama", "local"):
return _call_ollama(model, user_message)
elif provider == "vllm":
return _call_vllm(model, base_url or "http://localhost:8000", user_message)
elif provider == "sglang":
return _call_sglang(model, base_url or "http://localhost:30000", user_message)
elif provider == "openai":
return _call_openai(api_key, model, base_url, user_message)
elif provider == "anthropic":
return _call_anthropic(api_key, model, user_message)
Expand Down Expand Up @@ -120,6 +127,113 @@ def _call_anthropic(api_key: str, model: str, user_message: str) -> dict:
return _parse_ai_response(content)


def _call_ollama(model: str | None, user_message: str) -> dict:
"""Call local Ollama models with auto-detection."""
try:
import ollama
except ImportError:
return {"success": False, "message": "pip install ollama"}

# Auto-detect available local models
try:
available = [m.model for m in ollama.list().models]
except Exception:
return {"success": False, "message": "Ollama not running. Start with: ollama serve"}

if not available:
return {"success": False, "message": "No local models found. Run: ollama pull phi3"}

# Use specified model or first available
selected = model if model in available else available[0]

response = ollama.chat(
model=selected,
messages=[
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message},
],
)

content = response.message.content
return _parse_ai_response(content)


def _call_vllm(model: str | None, base_url: str, user_message: str) -> dict:
"""Call vLLM server (OpenAI-compatible API at localhost:8000 by default)."""
import httpx

# Auto-detect available models from vLLM if none specified
if not model:
try:
resp = httpx.get(f"{base_url.rstrip('/')}/v1/models", timeout=5)
models = resp.json().get("data", [])
model = models[0]["id"] if models else None
except Exception:
pass

if not model:
return {"success": False, "message": "No model specified and could not auto-detect from vLLM server."}

url = f"{base_url.rstrip('/')}/v1/chat/completions"
try:
resp = httpx.post(
url,
headers={"Content-Type": "application/json"},
json={
"model": model,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message},
],
"temperature": 0.3,
"max_tokens": 2000,
},
timeout=120,
)
content = resp.json()["choices"][0]["message"]["content"]
return _parse_ai_response(content)
except Exception as e:
return {"success": False, "message": f"vLLM call failed: {e}. Is vLLM running at {base_url}?"}


def _call_sglang(model: str | None, base_url: str, user_message: str) -> dict:
"""Call SGLang server (OpenAI-compatible API at localhost:30000 by default)."""
import httpx

# Auto-detect available models from SGLang if none specified
if not model:
try:
resp = httpx.get(f"{base_url.rstrip('/')}/v1/models", timeout=5)
models = resp.json().get("data", [])
model = models[0]["id"] if models else None
except Exception:
pass

if not model:
return {"success": False, "message": "No model specified and could not auto-detect from SGLang server."}

url = f"{base_url.rstrip('/')}/v1/chat/completions"
try:
resp = httpx.post(
url,
headers={"Content-Type": "application/json"},
json={
"model": model,
"messages": [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": user_message},
],
"temperature": 0.3,
"max_tokens": 2000,
},
timeout=120,
)
content = resp.json()["choices"][0]["message"]["content"]
return _parse_ai_response(content)
except Exception as e:
return {"success": False, "message": f"SGLang call failed: {e}. Is SGLang running at {base_url}?"}


def _call_openai_compatible(api_key: str, model: str, base_url: str, user_message: str) -> dict:
"""Call OpenAI-compatible API."""
import httpx
Expand Down Expand Up @@ -147,15 +261,22 @@ def _call_openai_compatible(api_key: str, model: str, base_url: str, user_messag

def _parse_ai_response(content: str) -> dict[str, Any]:
"""Parse AI response, handling markdown code blocks."""
# Strip markdown code blocks
text = content.strip()
if text.startswith("```"):
lines = text.split("\n")
# Remove first and last lines (```json ... ```)
text = "\n".join(lines[1:-1]) if len(lines) > 2 else text

try:
result = json.loads(text)
return result
except json.JSONDecodeError:
return {"success": False, "message": f"Could not parse AI response: {text[:200]}"}


def get_available_local_models() -> list[str]:
"""Return list of locally available Ollama models."""
try:
import ollama
return [m.model for m in ollama.list().models]
except Exception:
return []
Loading
0