CB commited on
Commit
ff4797c
·
verified ·
1 Parent(s): d5c14ed

Update streamlit_app.py

Browse files
Files changed (1) hide show
  1. streamlit_app.py +43 -44
streamlit_app.py CHANGED
@@ -13,7 +13,7 @@ from dotenv import load_dotenv
13
 
14
  load_dotenv()
15
 
16
- # Try SDK import
17
  HAS_GENAI = False
18
  genai = None
19
  upload_file = None
@@ -275,7 +275,6 @@ def get_runtime_api_key():
275
  return key
276
  return os.getenv("GOOGLE_API_KEY", "").strip() or None
277
 
278
- # --- Compatibility layer: SDK-first, HTTP fallback using /v1/responses ---
279
  def _messages_to_prompt(messages):
280
  if not messages:
281
  return ""
@@ -296,6 +295,7 @@ def _http_generate_responses(api_key: str, model: str, prompt: str, max_tokens:
296
  }
297
  r = requests.post(url, json=payload, headers=headers, timeout=30)
298
  if r.status_code != 200:
 
299
  raise RuntimeError(f"HTTP {r.status_code}: {r.text}")
300
  return r.json()
301
 
@@ -314,7 +314,7 @@ def responses_generate(model, messages, files, max_output_tokens, api_key):
314
  return responses_obj.generate(**sdk_kwargs)
315
  except Exception:
316
  pass
317
- # HTTP fallback (Responses API)
318
  prompt = _messages_to_prompt(messages)
319
  return _http_generate_responses(api_key, model, prompt, max_output_tokens)
320
 
@@ -333,56 +333,55 @@ def call_responses_once(model_used, system_msg, user_msg, fname, max_tokens):
333
  def extract_text_from_response(response):
334
  if response is None:
335
  return None
336
- # dict-style
337
  if isinstance(response, dict):
338
- # Responses v1: look for "output" or "candidates" or "outputText"
339
- if "output" in response and isinstance(response["output"], list):
340
- pieces = []
341
- for item in response["output"]:
342
- if isinstance(item, dict):
343
- # new Responses API nested content sometimes in "content" list with dicts
344
- if "content" in item and isinstance(item["content"], list):
345
- for c in item["content"]:
346
- if isinstance(c, dict) and "text" in c:
347
- pieces.append(c["text"])
348
- else:
349
- c = item.get("content") or item.get("text")
350
- if isinstance(c, str):
351
- pieces.append(c)
352
- if pieces:
353
- return "\n\n".join(pieces)
354
- # older style candidates
355
- if "candidates" in response and isinstance(response["candidates"], list) and response["candidates"]:
356
  cand = response["candidates"][0]
357
  if isinstance(cand, dict):
358
- return cand.get("content") or cand.get("text") or response.get("text")
359
- if "outputText" in response and isinstance(response["outputText"], str):
360
- return response["outputText"]
361
- if "text" in response and isinstance(response["text"], str):
362
- return response["text"]
363
- # fallback: stringified body
364
- return json.dumps(response)[:16000]
365
- # object-style (SDK)
366
  try:
367
  outputs = getattr(response, "output", None) or getattr(response, "candidates", None)
368
  if outputs:
369
- pieces = []
370
  for item in outputs:
371
- txt = None
372
  if hasattr(item, "content"):
373
- txt = getattr(item, "content")
374
- if isinstance(txt, list):
375
- # SDK content lists may contain dicts with 'text'
376
- for c in txt:
377
- if isinstance(c, dict) and "text" in c:
378
- pieces.append(c["text"])
379
- elif isinstance(txt, str):
380
- pieces.append(txt)
381
- txt = txt or getattr(item, "text", None)
 
382
  if isinstance(txt, str):
383
- pieces.append(txt)
384
- if pieces:
385
- return "\n\n".join(pieces)
386
  txt = getattr(response, "text", None) or getattr(response, "output_text", None)
387
  if txt:
388
  return txt
 
13
 
14
  load_dotenv()
15
 
16
+ # Try to import SDK
17
  HAS_GENAI = False
18
  genai = None
19
  upload_file = None
 
275
  return key
276
  return os.getenv("GOOGLE_API_KEY", "").strip() or None
277
 
 
278
  def _messages_to_prompt(messages):
279
  if not messages:
280
  return ""
 
295
  }
296
  r = requests.post(url, json=payload, headers=headers, timeout=30)
297
  if r.status_code != 200:
298
+ # include body for debugging
299
  raise RuntimeError(f"HTTP {r.status_code}: {r.text}")
300
  return r.json()
301
 
 
314
  return responses_obj.generate(**sdk_kwargs)
315
  except Exception:
316
  pass
317
+ # HTTP fallback (Responses v1)
318
  prompt = _messages_to_prompt(messages)
319
  return _http_generate_responses(api_key, model, prompt, max_output_tokens)
320
 
 
333
  def extract_text_from_response(response):
334
  if response is None:
335
  return None
 
336
  if isinstance(response, dict):
337
+ # new Responses v1 shape: "output" -> list of items, each may contain "content" list with {"text":...}
338
+ out = []
339
+ for item in response.get("output", []) or []:
340
+ if isinstance(item, dict):
341
+ # content list
342
+ for c in item.get("content", []) or []:
343
+ if isinstance(c, dict) and "text" in c:
344
+ out.append(c["text"])
345
+ # fallback short text fields
346
+ if "text" in item and isinstance(item["text"], str):
347
+ out.append(item["text"])
348
+ if "content" in item and isinstance(item["content"], str):
349
+ out.append(item["content"])
350
+ if out:
351
+ return "\n\n".join(out)
352
+ # older candidates style
353
+ if "candidates" in response and response["candidates"]:
 
354
  cand = response["candidates"][0]
355
  if isinstance(cand, dict):
356
+ return cand.get("content") or cand.get("text")
357
+ # fallback simple fields
358
+ if "outputText" in response:
359
+ return response.get("outputText")
360
+ if "text" in response:
361
+ return response.get("text")
362
+ return None
363
+ # SDK object style
364
  try:
365
  outputs = getattr(response, "output", None) or getattr(response, "candidates", None)
366
  if outputs:
367
+ parts = []
368
  for item in outputs:
369
+ # SDK item may be object or dict-like
370
  if hasattr(item, "content"):
371
+ c = getattr(item, "content")
372
+ if isinstance(c, list):
373
+ for e in c:
374
+ if isinstance(e, dict) and "text" in e:
375
+ parts.append(e["text"])
376
+ elif isinstance(e, str):
377
+ parts.append(e)
378
+ elif isinstance(c, str):
379
+ parts.append(c)
380
+ txt = getattr(item, "text", None)
381
  if isinstance(txt, str):
382
+ parts.append(txt)
383
+ if parts:
384
+ return "\n\n".join(parts)
385
  txt = getattr(response, "text", None) or getattr(response, "output_text", None)
386
  if txt:
387
  return txt