Spaces:
Paused
Paused
Add optional Ollama chat fallback engine
Browse files- ollama_engine.py +114 -0
ollama_engine.py
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
ollama_engine.py — optional external Ollama fallback for LINGO.
|
| 3 |
+
|
| 4 |
+
Use this when Hugging Face provider credits are depleted but you have a local
|
| 5 |
+
machine/server running Ollama behind Cloudflare Tunnel or ngrok.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import logging
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
import httpx
|
| 14 |
+
|
| 15 |
+
from config import Settings
|
| 16 |
+
|
| 17 |
+
logger = logging.getLogger(__name__)
|
| 18 |
+
|
| 19 |
+
SYSTEM_PROMPT = """You are LINGO, a concise AI phone receptionist.
|
| 20 |
+
Speak in short, natural sentences suitable for a live phone call.
|
| 21 |
+
You can answer basic questions, take messages, collect appointment requests,
|
| 22 |
+
and escalate when the caller asks for a human.
|
| 23 |
+
If you do not know a business-specific detail, offer to take a message.
|
| 24 |
+
If escalation is needed, end the reply with [ESCALATE].
|
| 25 |
+
Keep replies under 55 words.
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def enabled(settings: Settings) -> bool:
|
| 30 |
+
return bool(settings.ollama_enabled and settings.ollama_chat_url and settings.ollama_model)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _messages_for_ollama(messages: list[dict[str, Any]], settings: Settings) -> list[dict[str, str]]:
|
| 34 |
+
out: list[dict[str, str]] = [
|
| 35 |
+
{
|
| 36 |
+
"role": "system",
|
| 37 |
+
"content": SYSTEM_PROMPT + f"\nBusiness name: {settings.business_name or 'the business'}.",
|
| 38 |
+
}
|
| 39 |
+
]
|
| 40 |
+
for message in messages[-8:]:
|
| 41 |
+
role = str(message.get("role", "user"))
|
| 42 |
+
content = str(message.get("content", "")).strip()
|
| 43 |
+
if not content:
|
| 44 |
+
continue
|
| 45 |
+
if role not in {"user", "assistant"}:
|
| 46 |
+
continue
|
| 47 |
+
out.append({"role": role, "content": content[:1200]})
|
| 48 |
+
return out
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _headers(settings: Settings) -> dict[str, str]:
|
| 52 |
+
headers = {"Content-Type": "application/json"}
|
| 53 |
+
if settings.ollama_auth_token:
|
| 54 |
+
headers["Authorization"] = f"Bearer {settings.ollama_auth_token}"
|
| 55 |
+
return headers
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
async def chat_completion(
|
| 59 |
+
messages: list[dict[str, Any]],
|
| 60 |
+
http_client: httpx.AsyncClient,
|
| 61 |
+
settings: Settings,
|
| 62 |
+
) -> dict[str, Any]:
|
| 63 |
+
if not enabled(settings):
|
| 64 |
+
return {"ok": False, "source": "ollama", "error": "Ollama fallback disabled or missing config"}
|
| 65 |
+
|
| 66 |
+
payload = {
|
| 67 |
+
"model": settings.ollama_model,
|
| 68 |
+
"messages": _messages_for_ollama(messages, settings),
|
| 69 |
+
"stream": False,
|
| 70 |
+
"options": {
|
| 71 |
+
"temperature": 0.35,
|
| 72 |
+
"num_predict": 120,
|
| 73 |
+
},
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
try:
|
| 77 |
+
response = await http_client.post(
|
| 78 |
+
settings.ollama_chat_url,
|
| 79 |
+
json=payload,
|
| 80 |
+
headers=_headers(settings),
|
| 81 |
+
timeout=float(settings.ollama_timeout_seconds),
|
| 82 |
+
)
|
| 83 |
+
if not response.is_success:
|
| 84 |
+
return {
|
| 85 |
+
"ok": False,
|
| 86 |
+
"source": "ollama",
|
| 87 |
+
"status_code": response.status_code,
|
| 88 |
+
"error": response.text[:500],
|
| 89 |
+
}
|
| 90 |
+
data = response.json()
|
| 91 |
+
content = data.get("message", {}).get("content") or data.get("response") or ""
|
| 92 |
+
content = str(content).strip()
|
| 93 |
+
if not content:
|
| 94 |
+
return {"ok": False, "source": "ollama", "error": "empty Ollama response"}
|
| 95 |
+
return {
|
| 96 |
+
"ok": True,
|
| 97 |
+
"source": "ollama",
|
| 98 |
+
"model": settings.ollama_model,
|
| 99 |
+
"content": content[:700],
|
| 100 |
+
}
|
| 101 |
+
except Exception as exc: # noqa: BLE001
|
| 102 |
+
logger.error("Ollama fallback failed: %s", exc)
|
| 103 |
+
return {"ok": False, "source": "ollama", "exception": str(exc)[:500]}
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def diagnostics(settings: Settings) -> dict[str, Any]:
|
| 107 |
+
return {
|
| 108 |
+
"enabled": enabled(settings),
|
| 109 |
+
"configured": bool(settings.ollama_chat_url),
|
| 110 |
+
"chat_url_set": bool(settings.ollama_chat_url),
|
| 111 |
+
"model": settings.ollama_model,
|
| 112 |
+
"auth_token_set": bool(settings.ollama_auth_token),
|
| 113 |
+
"timeout_seconds": settings.ollama_timeout_seconds,
|
| 114 |
+
}
|