ChenyuRabbitLove commited on
Commit
49982b5
·
1 Parent(s): ad78edb

feat: add chat completions test endpoint to validate OpenAI integration and improve error handling

Browse files
Files changed (1) hide show
  1. backend/app/main.py +40 -4
backend/app/main.py CHANGED
@@ -77,18 +77,18 @@ async def test_openai():
77
  """Test OpenAI connection without making actual API calls"""
78
  try:
79
  from .core.config import settings
80
-
81
  if not settings.OPENAI_API_KEY:
82
  return {"status": "error", "message": "OPENAI_API_KEY not configured"}
83
-
84
  api_key_preview = (
85
  settings.OPENAI_API_KEY[:10] + "..."
86
  if len(settings.OPENAI_API_KEY) > 10
87
  else "Too short"
88
  )
89
-
90
  return {
91
- "status": "ok",
92
  "message": "OpenAI API key is configured",
93
  "api_key_preview": api_key_preview,
94
  "environment": (
@@ -98,6 +98,42 @@ async def test_openai():
98
  except Exception as e:
99
  return {"status": "error", "message": f"OpenAI configuration error: {str(e)}"}
100
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
 
102
  # Include API router
103
  app.include_router(api_router, prefix=settings.API_V1_STR)
 
77
  """Test OpenAI connection without making actual API calls"""
78
  try:
79
  from .core.config import settings
80
+
81
  if not settings.OPENAI_API_KEY:
82
  return {"status": "error", "message": "OPENAI_API_KEY not configured"}
83
+
84
  api_key_preview = (
85
  settings.OPENAI_API_KEY[:10] + "..."
86
  if len(settings.OPENAI_API_KEY) > 10
87
  else "Too short"
88
  )
89
+
90
  return {
91
+ "status": "ok",
92
  "message": "OpenAI API key is configured",
93
  "api_key_preview": api_key_preview,
94
  "environment": (
 
98
  except Exception as e:
99
  return {"status": "error", "message": f"OpenAI configuration error: {str(e)}"}
100
 
101
+ # Test chat completions endpoint
102
+ @app.get("/api/test-chat")
103
+ async def test_chat():
104
+ """Test if OpenAI chat completions work on Hugging Face"""
105
+ try:
106
+ from .core.config import settings
107
+ from openai import OpenAI
108
+
109
+ if not settings.OPENAI_API_KEY:
110
+ return {"status": "error", "message": "OPENAI_API_KEY not configured"}
111
+
112
+ client = OpenAI(api_key=settings.OPENAI_API_KEY, timeout=30.0)
113
+
114
+ # Test a simple chat completion
115
+ response = client.chat.completions.create(
116
+ model="gpt-3.5-turbo",
117
+ messages=[
118
+ {"role": "user", "content": "Say 'Hello from Hugging Face!' in exactly those words."}
119
+ ],
120
+ max_tokens=20
121
+ )
122
+
123
+ return {
124
+ "status": "success",
125
+ "message": "Chat completions work!",
126
+ "response": response.choices[0].message.content,
127
+ "model": response.model
128
+ }
129
+
130
+ except Exception as e:
131
+ return {
132
+ "status": "error",
133
+ "message": f"Chat completion failed: {str(e)}",
134
+ "error_type": type(e).__name__
135
+ }
136
+
137
 
138
  # Include API router
139
  app.include_router(api_router, prefix=settings.API_V1_STR)