Commit 8e06006

benny-dou <60535774+benny-dou@users.noreply.github.com>
2025-02-20 17:30:00
chore(gpt): use expandable block quotation for reasoning content
1 parent 36e783e
Changed files (2)
src/llm/gpt.py
@@ -1,12 +1,11 @@
 #!/usr/bin/env python
 # -*- coding: utf-8 -*-
-from pathlib import Path
 
 from loguru import logger
 from pyrogram.client import Client
 from pyrogram.types import Message
 
-from config import DOWNLOAD_DIR, ENABLE, GPT, PREFIX, cache
+from config import ENABLE, GPT, PREFIX, cache
 from llm.contexts import get_conversation_contexts, get_conversations
 from llm.models import get_model_config_with_contexts, get_model_type
 from llm.response import merge_tools_response, send_to_gpt
@@ -15,7 +14,6 @@ from messages.parser import parse_msg
 from messages.progress import modify_progress
 from messages.sender import send2tg
 from messages.utils import equal_prefix, startswith_prefix
-from utils import rand_number, save_txt
 
 HELP = f"""🤖**GPT对话**
 `{PREFIX.GPT}` 命令当前模型:
@@ -101,14 +99,13 @@ async def gpt_response(client: Client, message: Message, **kwargs):
         kwargs["progress"] = res[0]
     config = await merge_tools_response(config, **kwargs)
     response = await send_to_gpt(config, **kwargs)
-    media = []
-    if reasoning := response.get("reasoning"):
-        media = [{"document": save_txt(reasoning, f"{DOWNLOAD_DIR}/GPT-Reasoning-{rand_number()}.txt")}]
     if content := response.get("content"):
-        texts = f"🤖**{response['model']}**: ({BOT_TIPS})\n\n{content}"
+        if reasoning := response.get("reasoning"):
+            content = f"{reasoning}\n\n{content}"
+            texts = f"🤖**{response['model']}**: ({BOT_TIPS})\n{content}"
+        else:
+            texts = f"🤖**{response['model']}**: ({BOT_TIPS})\n\n{content}"
         logger.debug(texts)
-        await send2tg(client, message, texts=texts, media=media, **kwargs)
+        await send2tg(client, message, texts=texts, **kwargs)
         await modify_progress(del_status=True, **kwargs)
     llm_cleanup_files(config["completions"]["messages"])
-    if media:
-        Path(media[0]["document"]).unlink(missing_ok=True)
src/llm/response.py
@@ -61,7 +61,7 @@ async def send_to_gpt(config: dict, retry: int = 0, **kwargs) -> dict[str, str]:
         retry: int, number of retries
 
     Returns:
-        {"content": str, "reasoning": str, "model": str, "reasoning_model": str}
+        {"content": str, "reasoning": str, "model": str}
     """
     try:
         openai = AsyncOpenAI(**config["client"])
@@ -79,7 +79,7 @@ async def send_to_gpt(config: dict, retry: int = 0, **kwargs) -> dict[str, str]:
         await modify_progress(text=error, force_update=True, **kwargs)
         if retry < GPT.MAX_RETRY:
             return await send_to_gpt(config, retry=retry + 1, **kwargs)
-    return {"content": "", "reasoning": "", "reasoning_model": ""}
+    return {"content": "", "reasoning": ""}
 
 
 async def parse_error(resp: dict, retry: int, **kwargs) -> dict:
@@ -112,21 +112,27 @@ async def parse_response(config: dict, response: dict) -> dict[str, str]:
     """Parse GPT response.
 
     Returns:
-        {"content": str, "reasoning": str, "model": str, "reasoning_model": str}
+        {"content": str, "reasoning": str, "model": str}
     """
     logger.debug(response)
     choice = glom(response, "choices.0", default={})
     if glom(choice, "message.tool_calls.0", default={}):  # this is a function call response
-        return response | {"content": "", "reasoning": "", "reasoning_model": ""}
+        return response | {"content": "", "reasoning": ""}
     try:
         content = glom(choice, "message.content", default="") or ""
         content = add_search_results_to_response(config.get("search_results", []), content)
+
+        # parse reasoning
         reasoning, content = extract_reasoning(content)  # extract reasoning from content (<think>...</think>)
         if not reasoning:
             reasoning = glom(choice, Coalesce("message.reasoning_content", "message.reasoning"), default="") or ""
+        if reasoning:  # add expandable block quotation mark for reasoning
+            reasoning = reasoning.strip().replace("\n", "\n> ")
+            reasoning = f"**> 🤔{reasoning}"
+
         primary_model = glom(config, "completions.model", default="") or ""
         used_model = glom(response, "model", default="") or ""
-        response = {"content": content.strip(), "model": config["friendly_name"], "reasoning": reasoning.strip(), "reasoning_model": used_model}
+        response = {"content": content.strip(), "model": config["friendly_name"], "reasoning": reasoning.strip()}
         if not (used_model in primary_model or primary_model in used_model):
             # do not use `!=` to compare. (deepseek/deepseek-r1:free != deepseek/deepseek-r1,  gpt-4o != gpt-4o-2024-07-18)
             used_model = beautify_model_name(used_model)