sharathmajjigi commited on
Commit
3aadf61
Β·
1 Parent(s): 46d6d84

feat: add logs

Browse files
Files changed (1) hide show
  1. app.py +112 -17
app.py CHANGED
@@ -122,41 +122,136 @@ app.add_middleware(
122
  allow_headers=["*"],
123
  )
124
 
125
- # CRITICAL: Add the missing endpoint that Agent-S expects
126
  @app.post("/v1/ground/chat/completions")
127
  async def chat_completions(request: Request):
128
  """
129
  Chat completions endpoint that Agent-S expects
130
  """
131
  try:
132
- # Parse the request body
133
- body = await request.json()
134
-
135
- # Extract image and prompt from the request
136
- # Agent-S might send data in different formats
137
- if "data" in body and len(body["data"]) >= 2:
138
- image = body["data"][0] # First element is image
139
- prompt = body["data"][1] # Second element is prompt
140
- elif "image" in body and "prompt" in body:
141
- image = body["image"]
142
- prompt = body["prompt"]
143
- else:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
144
  return JSONResponse(
145
  status_code=400,
146
- content={"error": "Invalid request format", "status": "failed"}
147
  )
148
 
 
 
149
  # Process the request
150
- result = process_grounding(image, prompt)
 
151
 
152
- return JSONResponse(content=result)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
  except Exception as e:
 
 
 
 
 
155
  return JSONResponse(
156
  status_code=500,
157
  content={"error": f"Internal server error: {str(e)}", "status": "failed"}
158
  )
159
-
160
  # Keep existing endpoints for compatibility
161
  @app.post("/v1/ground")
162
  async def agent_s_grounding(request: Request):
 
122
  allow_headers=["*"],
123
  )
124
 
125
+ # Add this to your current /v1/ground/chat/completions endpoint
126
  @app.post("/v1/ground/chat/completions")
127
  async def chat_completions(request: Request):
128
  """
129
  Chat completions endpoint that Agent-S expects
130
  """
131
  try:
132
+ print("=" * 60)
133
+ print("οΏ½οΏ½ DEBUG: New request received")
134
+ print("=" * 60)
135
+
136
+ # DEBUG: Log the raw request
137
+ body = await request.body()
138
+ print(f"οΏ½οΏ½ RAW REQUEST BODY (bytes): {body}")
139
+ print(f"οΏ½οΏ½ RAW REQUEST BODY (string): {body.decode('utf-8', errors='ignore')}")
140
+
141
+ # DEBUG: Log the headers
142
+ headers = dict(request.headers)
143
+ print(f"πŸ“‹ REQUEST HEADERS:")
144
+ for key, value in headers.items():
145
+ print(f" {key}: {value}")
146
+
147
+ # DEBUG: Log the request method and URL
148
+ print(f"🌐 REQUEST METHOD: {request.method}")
149
+ print(f"🌐 REQUEST URL: {request.url}")
150
+
151
+ # DEBUG: Try to parse as JSON
152
+ try:
153
+ json_body = await request.json()
154
+ print(f"βœ… PARSED JSON SUCCESSFULLY:")
155
+ print(f" {json.dumps(json_body, indent=2)}")
156
+
157
+ # DEBUG: Analyze the JSON structure
158
+ if isinstance(json_body, dict):
159
+ print(f"πŸ” JSON KEYS: {list(json_body.keys())}")
160
+
161
+ if "messages" in json_body:
162
+ messages = json_body["messages"]
163
+ print(f"πŸ’¬ MESSAGES COUNT: {len(messages)}")
164
+ for i, msg in enumerate(messages):
165
+ print(f" Message {i}: role='{msg.get('role')}', content='{msg.get('content', '')[:100]}...'")
166
+
167
+ if "model" in json_body:
168
+ print(f"πŸ€– MODEL: {json_body['model']}")
169
+
170
+ if "temperature" in json_body:
171
+ print(f"🌑️ TEMPERATURE: {json_body['temperature']}")
172
+
173
+ except Exception as parse_error:
174
+ print(f"❌ JSON PARSE ERROR: {parse_error}")
175
+ print(f"❌ ERROR TYPE: {type(parse_error).__name__}")
176
+ print(f"❌ ERROR DETAILS: {str(parse_error)}")
177
+
178
+ # Try to get more info about the parsing error
179
+ try:
180
+ # Try to read the body again
181
+ await request.body() # Reset the body stream
182
+ raw_text = await request.body()
183
+ print(f"πŸ“ RAW TEXT (second attempt): {raw_text.decode('utf-8', errors='ignore')}")
184
+ except Exception as e2:
185
+ print(f"❌ SECOND ATTEMPT ERROR: {e2}")
186
+
187
+ return JSONResponse(
188
+ status_code=400,
189
+ content={"error": f"Invalid JSON: {str(parse_error)}", "status": "failed"}
190
+ )
191
+
192
+ print("=" * 60)
193
+ print("βœ… REQUEST PARSED SUCCESSFULLY - CONTINUING...")
194
+ print("=" * 60)
195
+
196
+ # Continue with your existing logic...
197
+ # Extract the user message from the chat format
198
+ user_message = None
199
+ if "messages" in json_body:
200
+ for message in json_body["messages"]:
201
+ if message.get("role") == "user":
202
+ user_message = message.get("content")
203
+ break
204
+
205
+ if not user_message:
206
+ print(f"❌ NO USER MESSAGE FOUND")
207
  return JSONResponse(
208
  status_code=400,
209
+ content={"error": "No user message found in request", "status": "failed"}
210
  )
211
 
212
+ print(f"πŸ“ USER MESSAGE EXTRACTED: {user_message}")
213
+
214
  # Process the request
215
+ result = process_grounding("mock_image", user_message)
216
+ print(f"🎯 GROUNDING RESULT: {result}")
217
 
218
+ # Format response in the expected chat completions format
219
+ response = {
220
+ "id": "chatcmpl-123",
221
+ "object": "chat.completion",
222
+ "created": 1677652288,
223
+ "model": json_body.get("model", "ui-tars-1.5-7b"),
224
+ "choices": [
225
+ {
226
+ "index": 0,
227
+ "message": {
228
+ "role": "assistant",
229
+ "content": json.dumps(result)
230
+ },
231
+ "finish_reason": "stop"
232
+ }
233
+ ],
234
+ "usage": {
235
+ "prompt_tokens": 10,
236
+ "completion_tokens": 20,
237
+ "total_tokens": 30
238
+ }
239
+ }
240
+
241
+ print(f"πŸ“€ SENDING RESPONSE: {json.dumps(response, indent=2)}")
242
+ return JSONResponse(content=response)
243
 
244
  except Exception as e:
245
+ print(f"❌ UNEXPECTED ERROR: {str(e)}")
246
+ print(f"❌ ERROR TYPE: {type(e).__name__}")
247
+ import traceback
248
+ print(f"❌ TRACEBACK: {traceback.format_exc()}")
249
+
250
  return JSONResponse(
251
  status_code=500,
252
  content={"error": f"Internal server error: {str(e)}", "status": "failed"}
253
  )
254
+
255
  # Keep existing endpoints for compatibility
256
  @app.post("/v1/ground")
257
  async def agent_s_grounding(request: Request):