Spaces:
Sleeping
Sleeping
Update app/openai_client.py
Browse files- app/openai_client.py +23 -6
app/openai_client.py
CHANGED
|
@@ -14,9 +14,7 @@ HEADERS = {
|
|
| 14 |
|
| 15 |
|
| 16 |
async def openai_chat(messages, temperature: float = 0.7, max_tokens: int = 300) -> str:
|
| 17 |
-
"""
|
| 18 |
-
非同期:通常のチャット生成(UIの広告生成で使用)
|
| 19 |
-
"""
|
| 20 |
if not OPENAI_API_KEY:
|
| 21 |
raise RuntimeError("OPENAI_API_KEY is not set in environment variables.")
|
| 22 |
|
|
@@ -34,10 +32,29 @@ async def openai_chat(messages, temperature: float = 0.7, max_tokens: int = 300)
|
|
| 34 |
return data["choices"][0]["message"]["content"].strip()
|
| 35 |
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
def openai_judge(system: str, user: str) -> dict:
|
| 38 |
-
"""
|
| 39 |
-
同期:審査用(JSONフォーマットで判定/修正案を返す)
|
| 40 |
-
"""
|
| 41 |
if not OPENAI_API_KEY:
|
| 42 |
raise RuntimeError("OPENAI_API_KEY is not set in environment variables.")
|
| 43 |
|
|
|
|
| 14 |
|
| 15 |
|
| 16 |
async def openai_chat(messages, temperature: float = 0.7, max_tokens: int = 300) -> str:
|
| 17 |
+
"""自由回答(プレーンテキスト)"""
|
|
|
|
|
|
|
| 18 |
if not OPENAI_API_KEY:
|
| 19 |
raise RuntimeError("OPENAI_API_KEY is not set in environment variables.")
|
| 20 |
|
|
|
|
| 32 |
return data["choices"][0]["message"]["content"].strip()
|
| 33 |
|
| 34 |
|
| 35 |
+
async def openai_chat_json(messages, temperature: float = 0.2, max_tokens: int = 1200) -> dict:
|
| 36 |
+
"""JSONモード(出力は厳密なJSON文字列)"""
|
| 37 |
+
if not OPENAI_API_KEY:
|
| 38 |
+
raise RuntimeError("OPENAI_API_KEY is not set in environment variables.")
|
| 39 |
+
|
| 40 |
+
url = f"{OPENAI_BASE}/chat/completions"
|
| 41 |
+
payload = {
|
| 42 |
+
"model": OPENAI_MODEL,
|
| 43 |
+
"messages": messages,
|
| 44 |
+
"temperature": float(temperature),
|
| 45 |
+
"max_tokens": int(max_tokens),
|
| 46 |
+
"response_format": {"type": "json_object"},
|
| 47 |
+
}
|
| 48 |
+
async with httpx.AsyncClient(timeout=60) as client:
|
| 49 |
+
r = await client.post(url, headers=HEADERS, json=payload)
|
| 50 |
+
r.raise_for_status()
|
| 51 |
+
data = r.json()
|
| 52 |
+
content = data["choices"][0]["message"]["content"].strip()
|
| 53 |
+
return json.loads(content)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
def openai_judge(system: str, user: str) -> dict:
|
| 57 |
+
"""審査用(JSONモード)。同期呼び出し"""
|
|
|
|
|
|
|
| 58 |
if not OPENAI_API_KEY:
|
| 59 |
raise RuntimeError("OPENAI_API_KEY is not set in environment variables.")
|
| 60 |
|