feat: Enhance OpenRouter API interaction and error handling
- Increased the maximum token limit in the `call_openrouter` function from 1500 to 4096 to allow for more extensive responses. - Implemented robust error handling for API requests, including timeout and request errors, with detailed HTTP exceptions for better debugging. - Improved JSON response handling to ensure valid data is returned, with specific error messages for missing content in the response. - Enhanced the overall reliability of the OpenRouter API integration, providing clearer feedback for users in case of issues. These changes improve the user experience by ensuring more comprehensive responses and clearer error reporting during API interactions.
This commit is contained in:
1 parent
90a27846ca
commit
4b6e1bed11
3 files changed
+377
-37
No files matched your search
+47
-14
@@ -937,27 +937,60 @@ def export_placeholder_catalog_zip(
|
||||
|
||||
# ── KI-Assisted Prompt Engineering ───────────────────────────────────────────
|
||||
|
||||
async def call_openrouter(prompt: str, max_tokens: int = 1500) -> str:
|
||||
async def call_openrouter(prompt: str, max_tokens: int = 4096) -> str:
|
||||
"""Call OpenRouter API to get AI response."""
|
||||
if not OPENROUTER_KEY:
|
||||
raise HTTPException(status_code=500, detail="OpenRouter API key not configured")
|
||||
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
"https://openrouter.ai/api/v1/chat/completions",
|
||||
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
|
||||
json={
|
||||
"model": OPENROUTER_MODEL,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"max_tokens": max_tokens
|
||||
},
|
||||
timeout=60.0
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
resp = await client.post(
|
||||
"https://openrouter.ai/api/v1/chat/completions",
|
||||
headers={"Authorization": f"Bearer {OPENROUTER_KEY}"},
|
||||
json={
|
||||
"model": OPENROUTER_MODEL,
|
||||
"messages": [{"role": "user", "content": prompt}],
|
||||
"max_tokens": max_tokens
|
||||
},
|
||||
timeout=120.0
|
||||
)
|
||||
except httpx.TimeoutException as e:
|
||||
raise HTTPException(status_code=504, detail=f"OpenRouter-Zeitüberschreitung: {e}") from e
|
||||
except httpx.RequestError as e:
|
||||
raise HTTPException(status_code=502, detail=f"OpenRouter-Verbindungsfehler: {e}") from e
|
||||
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(
|
||||
status_code=resp.status_code,
|
||||
detail=f"OpenRouter API error ({resp.status_code}): {resp.text[:2000]}",
|
||||
)
|
||||
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(status_code=resp.status_code, detail=f"OpenRouter API error: {resp.text}")
|
||||
try:
|
||||
data = resp.json()
|
||||
except json.JSONDecodeError:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"OpenRouter lieferte kein JSON: {resp.text[:800]}",
|
||||
)
|
||||
|
||||
return resp.json()['choices'][0]['message']['content'].strip()
|
||||
choices = data.get("choices") or []
|
||||
if not choices:
|
||||
err_snip = json.dumps(data.get("error") or data, ensure_ascii=False)[:1200]
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail=f"OpenRouter ohne choices in der Antwort: {err_snip}",
|
||||
)
|
||||
|
||||
message = choices[0].get("message") or {}
|
||||
content = message.get("content")
|
||||
if content is None:
|
||||
raise HTTPException(
|
||||
status_code=502,
|
||||
detail="OpenRouter-Antwort ohne message.content (z. B. Tool-Calls oder abweichendes Schema).",
|
||||
)
|
||||
if not isinstance(content, str):
|
||||
content = str(content)
|
||||
return content.strip()
|
||||
|
||||
|
||||
def collect_example_data(profile_id: str, data_categories: list[str]) -> dict:
|
||||
|
||||
Reference in new issue
Block a user