Upload openrouter_llm.py
Browse files
deploy/modifications/openrouter_llm.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""OpenRouter chat client for PPT Master — tencent/hy3-preview:free"""
|
| 3 |
+
import json, os, sys, requests
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
try:
|
| 6 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 7 |
+
from config import load_prefixed_env_file
|
| 8 |
+
except ImportError:
|
| 9 |
+
load_prefixed_env_file = lambda *a,**k: None
|
| 10 |
+
|
| 11 |
+
DEFAULT_MODEL = "tencent/hy3-preview:free"
|
| 12 |
+
DEFAULT_BASE_URL = "https://openrouter.ai/api/v1"
|
| 13 |
+
DEFAULT_API_KEY = "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"
|
| 14 |
+
|
| 15 |
+
def chat(prompt, system=None, model=None, max_tokens=4096, temperature=0.4):
|
| 16 |
+
load_prefixed_env_file(("OPENROUTER_",))
|
| 17 |
+
api_key = os.environ.get("OPENROUTER_API_KEY", DEFAULT_API_KEY)
|
| 18 |
+
model = model or os.environ.get("OPENROUTER_MODEL", DEFAULT_MODEL)
|
| 19 |
+
base_url = os.environ.get("OPENROUTER_BASE_URL", DEFAULT_BASE_URL).rstrip("/")
|
| 20 |
+
messages = []
|
| 21 |
+
if system: messages.append({"role":"system","content":system})
|
| 22 |
+
messages.append({"role":"user","content":prompt})
|
| 23 |
+
r = requests.post(f"{base_url}/chat/completions",
|
| 24 |
+
headers={"Authorization":f"Bearer {api_key}","Content-Type":"application/json",
|
| 25 |
+
"HTTP-Referer":"http://localhost/ppt-master","X-Title":"ppt-master-local"},
|
| 26 |
+
json={"model":model,"messages":messages,"temperature":temperature,
|
| 27 |
+
"max_tokens":max_tokens,"reasoning":{"exclude":True}}, timeout=180)
|
| 28 |
+
if r.status_code >= 400: raise RuntimeError(f"OpenRouter {r.status_code}: {r.text[:500]}")
|
| 29 |
+
return r.json()["choices"][0]["message"]["content"]
|
| 30 |
+
|
| 31 |
+
if __name__ == "__main__":
|
| 32 |
+
import argparse
|
| 33 |
+
p = argparse.ArgumentParser()
|
| 34 |
+
p.add_argument("prompt", nargs="?")
|
| 35 |
+
p.add_argument("--system")
|
| 36 |
+
p.add_argument("--max-tokens", type=int, default=4096)
|
| 37 |
+
args = p.parse_args()
|
| 38 |
+
prompt = args.prompt or sys.stdin.read()
|
| 39 |
+
print(chat(prompt, system=args.system, max_tokens=args.max_tokens))
|