Commit 6759cac

benny-dou <60535774+benny-dou@users.noreply.github.com>
2026-05-11 10:36:37
fix(ai): fix openai response context retrieval and caching
1 parent 7b31448
Changed files (2)
src/ai/texts/contexts.py
@@ -139,7 +139,7 @@ async def get_openai_response_contexts(client: Client, message: Message, openai_
         cache_day = openai_params["cache_day"]
         key_hash = hashlib.sha256(api_key.encode()).hexdigest()
         tid = get_thread_id(msg)
-        resp = await head_cf_r2(f"TTL/{cache_day}d/OpenAI/{model_id}/{key_hash}/{msg.chat.id}/{msg.id}{'/' + str(tid) if tid else ''}")
+        resp = await head_cf_r2(f"TTL/{cache_day}d/OpenAI/{msg.chat.id}/{msg.id}{'/' + str(tid) if tid else ''}/{model_id}/{key_hash}")
         return glom(resp, "Metadata.response_id", default="") or ""
 
     previous_response_id = ""
@@ -165,6 +165,7 @@ async def single_openai_response_context(client: Client, message: Message, opena
     """
     info = parse_msg(message, silent=True)
     role = "assistant" if BOT_TIPS in info["text"] else "user"
+    text_type = "input_text" if role == "user" else "output_text"
 
     if info["mtype"] not in ["text", "photo", "audio", "voice", "video", "document", "web_page"]:
         return {}
@@ -207,7 +208,7 @@ async def single_openai_response_context(client: Client, message: Message, opena
                     fpath: str = await client.download_media(msg, media_path)  # type: ignore
                     contexts.append(
                         {
-                            "type": "input_text",
+                            "type": text_type,
                             "text": f"[filename]: {info['file_name']}\n[file content]:\n{read_text(fpath).strip()}",
                         }
                     )
@@ -217,7 +218,7 @@ async def single_openai_response_context(client: Client, message: Message, opena
                     Path(fpath).unlink(missing_ok=True)
                     contexts.append(
                         {
-                            "type": "input_text",
+                            "type": text_type,
                             "text": f"[filename]: {info['file_name']}\n[file content]:\n{text.strip()}",
                         }
                     )
@@ -230,11 +231,14 @@ async def single_openai_response_context(client: Client, message: Message, opena
             else:
                 texts = f"<quote>{info['quote_text']}</quote>\n{clean_texts}"
             texts = texts.removeprefix("<quote></quote>\n")  # remove quote mark if no quote_text
-            contexts.append({"type": "input_text", "text": texts})
+            contexts.append({"type": text_type, "text": texts})
         except Exception as e:
             logger.warning(f"Download media from message failed: {e}")
             continue
-    return {"role": role, "content": contexts} if contexts else {}
+    if not contexts:
+        return {}
+    extra = {"status": "completed"} if role == "assistant" else {}
+    return {"role": role, "type": "message", "content": contexts, **extra}
 
 
 async def get_openai_file_id(client: Client, message: Message, openai_params: dict, mtype: str) -> str:
src/ai/texts/openai_response.py
@@ -123,7 +123,7 @@ async def openai_responses_api(
                     key_hash = hashlib.sha256(api_key.encode()).hexdigest()
                     tid = get_thread_id(sent_msg)
                     await set_cf_r2(
-                        f"TTL/{day}d/OpenAI/{model_id}/{key_hash}/{sent_msg.chat.id}/{sent_msg.id}{'/' + str(tid) if tid else ''}",
+                        f"TTL/{day}d/OpenAI/{sent_msg.chat.id}/{sent_msg.id}{'/' + str(tid) if tid else ''}/{model_id}/{key_hash}",
                         data=resp["full_response"],
                         metadata={"response_id": resp["response_id"]},
                         silent=silent,