File size: 2,318 Bytes
a611e89
1c047d5
a611e89
 
 
 
 
 
 
 
 
 
 
 
1c047d5
a611e89
1c047d5
a611e89
 
 
 
 
 
 
 
1c047d5
a611e89
 
 
 
 
 
 
 
 
 
 
 
1c047d5
a611e89
 
 
1c047d5
a611e89
 
 
1c047d5
a611e89
 
 
 
 
 
 
 
1c047d5
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
from __future__ import annotations
import os, json, httpx

OPENAI_BASE = os.environ.get("OPENAI_BASE", "https://api.openai.com/v1")
OPENAI_MODEL = os.environ.get("OPENAI_MODEL", "gpt-4o-mini")
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")

HEADERS = {
    "Authorization": f"Bearer {OPENAI_API_KEY}" if OPENAI_API_KEY else "",
    "Content-Type": "application/json",
}

async def openai_chat(messages, temperature: float = 0.7, max_tokens: int = 300) -> str:
    if not OPENAI_API_KEY:
        raise RuntimeError("OPENAI_API_KEY is not set.")
    url = f"{OPENAI_BASE}/chat/completions"
    payload = {"model": OPENAI_MODEL, "messages": messages, "temperature": float(temperature), "max_tokens": int(max_tokens)}
    async with httpx.AsyncClient(timeout=60) as client:
        r = await client.post(url, headers=HEADERS, json=payload)
        r.raise_for_status()
        data = r.json()
        return data["choices"][0]["message"]["content"].strip()

async def openai_chat_json(messages, temperature: float = 0.2, max_tokens: int = 1200) -> dict:
    if not OPENAI_API_KEY:
        raise RuntimeError("OPENAI_API_KEY is not set.")
    url = f"{OPENAI_BASE}/chat/completions"
    payload = {
        "model": OPENAI_MODEL,
        "messages": messages,
        "temperature": float(temperature),
        "max_tokens": int(max_tokens),
        "response_format": {"type": "json_object"},
    }
    async with httpx.AsyncClient(timeout=60) as client:
        r = await client.post(url, headers=HEADERS, json=payload)
        r.raise_for_status()
        data = r.json()
        return json.loads(data["choices"][0]["message"]["content"].strip())

def openai_judge(system: str, user: str) -> dict:
    if not OPENAI_API_KEY:
        raise RuntimeError("OPENAI_API_KEY is not set.")
    url = f"{OPENAI_BASE}/chat/completions"
    payload = {
        "model": OPENAI_MODEL,
        "messages": [{"role": "system", "content": system}, {"role": "user", "content": user}],
        "response_format": {"type": "json_object"},
        "temperature": 0.0,
        "max_tokens": 400,
    }
    with httpx.Client(timeout=60) as client:
        r = client.post(url, headers=HEADERS, json=payload)
        r.raise_for_status()
        data = r.json()
        return json.loads(data["choices"][0]["message"]["content"].strip())