GitHub Action commited on
Commit
1b21038
·
1 Parent(s): 7519849

Sync ling-space changes from GitHub commit 9773e54

Browse files
app.py CHANGED
@@ -5,7 +5,7 @@ from datetime import datetime
5
  import pandas as pd
6
  from i18n import get_text
7
  from model_handler import ModelHandler
8
- from tab_chat import create_chat_tab
9
  from tab_chat import update_language as update_chat_language
10
  from tab_code import create_code_tab
11
  from tab_code import update_language as update_code_language
@@ -20,75 +20,6 @@ logging.basicConfig(
20
  )
21
  logger = logging.getLogger(__name__)
22
 
23
-
24
- def get_history_df_from_app(history):
25
- if not history:
26
- return pd.DataFrame(
27
- {"ID": pd.Series(dtype="str"), "对话": pd.Series(dtype="str")}
28
- )
29
- df = pd.DataFrame(history)
30
- if "id" in df.columns and "title" in df.columns:
31
- return df[["id", "title"]].rename(columns={"id": "ID", "对话": "对话"})
32
- return pd.DataFrame({"ID": pd.Series(dtype="str"), "对话": pd.Series(dtype="str")})
33
-
34
-
35
- def on_app_load(request: gr.Request, history, conv_id, current_lang_state):
36
- """
37
- Handles the application's initial state on load.
38
- - Determines language from URL parameter.
39
- - Loads conversation history or creates a new one.
40
- """
41
- # --- Language Detection ---
42
- query_params = dict(request.query_params)
43
- url_lang = query_params.get("lang")
44
-
45
- updated_lang = current_lang_state # Start with the default
46
- if url_lang and url_lang in ["en", "zh"]:
47
- updated_lang = url_lang
48
-
49
- # --- History Loading Logic ---
50
- if not history:
51
- # First time ever, create a new conversation
52
- conv_id = str(uuid.uuid4())
53
- new_convo_title = get_text("chat_new_conversation_title", updated_lang)
54
- new_convo = {
55
- "id": conv_id,
56
- "title": new_convo_title,
57
- "messages": [],
58
- "timestamp": datetime.now().isoformat(),
59
- }
60
- history = [new_convo]
61
- return (
62
- conv_id,
63
- history,
64
- gr.update(value=get_history_df_from_app(history)),
65
- [],
66
- updated_lang,
67
- )
68
-
69
- if conv_id and any(c["id"] == conv_id for c in history):
70
- # Valid last session, load it
71
- for convo in history:
72
- if convo["id"] == conv_id:
73
- return (
74
- conv_id,
75
- history,
76
- gr.update(value=get_history_df_from_app(history)),
77
- convo["messages"],
78
- updated_lang,
79
- )
80
-
81
- # Fallback to most recent conversation
82
- most_recent_convo = history[0]
83
- return (
84
- most_recent_convo["id"],
85
- history,
86
- gr.update(value=get_history_df_from_app(history)),
87
- most_recent_convo["messages"],
88
- updated_lang,
89
- )
90
-
91
-
92
  CSS = """
93
 
94
  #chatbot {
@@ -161,7 +92,7 @@ if __name__ == "__main__":
161
 
162
  chat_tab.select(
163
  fn=None,
164
- js="() => {window.dispatchEvent(new CustomEvent('tabSelect.chat')); console.log('this'); return null;}",
165
  )
166
 
167
  # --- Code Tab ---
 
5
  import pandas as pd
6
  from i18n import get_text
7
  from model_handler import ModelHandler
8
+ from tab_chat import create_chat_tab, get_history_df, on_app_load
9
  from tab_chat import update_language as update_chat_language
10
  from tab_code import create_code_tab
11
  from tab_code import update_language as update_code_language
 
20
  )
21
  logger = logging.getLogger(__name__)
22
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
  CSS = """
24
 
25
  #chatbot {
 
92
 
93
  chat_tab.select(
94
  fn=None,
95
+ js="() => {window.dispatchEvent(new CustomEvent('tabSelect.chat')); return null;}",
96
  )
97
 
98
  # --- Code Tab ---
config.py CHANGED
@@ -7,6 +7,7 @@ API keys, and system prompts for different functionalities.
7
 
8
  import os
9
  from dotenv import load_dotenv
 
10
 
11
  # Load environment variables from .secrets file
12
  load_dotenv(dotenv_path='.secrets')
@@ -38,50 +39,51 @@ RING_MINI_2_0 = "ring-mini-2.0"
38
 
39
 
40
  CHAT_MODEL_SPECS = {
41
- LING_MINI_2_0: {
42
- "provider": "openai_compatible",
43
- "model_id": "inclusionai/ling-mini-2.0",
44
- "display_name": "🦉 Ling-mini-2.0",
45
- "description": "轻量级对话模型,专为消费级硬件的高效运行而优化,是移动端或本地化部署场景的理想选择。",
46
- "url": "https://huggingface.co/inclusionai"
47
- },
48
  LING_1T: {
49
  "provider": "openai_compatible",
50
  "model_id": "inclusionai/ling-1t",
51
  "display_name": "🦉 Ling-1T",
52
- "description": "万亿参数的大型语言模型,专为需要极致性能和高流畅度的复杂自然语言理解与生成任务而设计。",
53
- "url": "https://huggingface.co/inclusionai"
54
- },
55
- LING_FLASH_2_0: {
56
- "provider": "openai_compatible",
57
- "model_id": "inclusionai/ling-flash-2.0",
58
- "display_name": "🦉 Ling-flash-2.0",
59
- "description": "高性能十亿参数模型,针对需要高速响应和复杂指令遵循的场景进行了优化。",
60
- "url": "https://huggingface.co/inclusionai"
61
  },
62
  RING_1T: {
63
  "provider": "openai_compatible",
64
  "model_id": "inclusionai/ring-1t",
65
  "display_name": "💍️ Ring-1T",
66
- "description": "全新的万亿参数推理模型,具备强大的代码生成和工具使用能力。",
67
- "url": "https://huggingface.co/inclusionai"
 
 
 
 
 
 
 
68
  },
69
  RING_FLASH_2_0: {
70
  "provider": "openai_compatible",
71
  "model_id": "inclusionai/ring-flash-2.0",
72
  "display_name": "💍️ Ring-flash-2.0",
73
- "description": "十亿参数推理模型,在性能与成本之间取得了良好的平衡,适用于需要逐步思考或代码生成的通用任务。",
74
- "url": "https://huggingface.co/inclusionai"
 
 
 
 
 
 
 
75
  },
76
  RING_MINI_2_0: {
77
  "provider": "openai_compatible",
78
  "model_id": "inclusionai/ring-mini-2.0",
79
  "display_name": "💍️ Ring-mini-2.0",
80
- "description": "一款专为资源受限环境设计的量化且极其高效的推理模型,满足严格的速度和效率要求(如边缘计算)。",
81
- "url": "https://huggingface.co/inclusionai"
82
  }
83
  }
84
 
 
85
  # --- Code Framework Specifications ---
86
 
87
  # Constants for easy referencing of code frameworks
@@ -140,4 +142,4 @@ def get_model_display_name(model_constant: str) -> str:
140
  Retrieves the display name for a given model constant.
141
  This is what's shown in the UI.
142
  """
143
- return CHAT_MODEL_SPECS.get(model_constant, {}).get("display_name", model_constant)
 
7
 
8
  import os
9
  from dotenv import load_dotenv
10
+ from i18n.model_config import model_descriptions
11
 
12
  # Load environment variables from .secrets file
13
  load_dotenv(dotenv_path='.secrets')
 
39
 
40
 
41
  CHAT_MODEL_SPECS = {
 
 
 
 
 
 
 
42
  LING_1T: {
43
  "provider": "openai_compatible",
44
  "model_id": "inclusionai/ling-1t",
45
  "display_name": "🦉 Ling-1T",
46
+ "description": model_descriptions["ling-1t-desc"],
47
+ "url": "https://huggingface.co/inclusionAI/Ling-1T"
 
 
 
 
 
 
 
48
  },
49
  RING_1T: {
50
  "provider": "openai_compatible",
51
  "model_id": "inclusionai/ring-1t",
52
  "display_name": "💍️ Ring-1T",
53
+ "description": model_descriptions["ring-1t-desc"],
54
+ "url": "https://huggingface.co/inclusionAI/Ring-1T"
55
+ },
56
+ LING_FLASH_2_0: {
57
+ "provider": "openai_compatible",
58
+ "model_id": "inclusionai/ling-flash-2.0",
59
+ "display_name": "🦉 Ling-flash-2.0",
60
+ "description": model_descriptions["ling-flash-2.0-desc"],
61
+ "url": "https://huggingface.co/inclusionAI/Ling-flash-2.0"
62
  },
63
  RING_FLASH_2_0: {
64
  "provider": "openai_compatible",
65
  "model_id": "inclusionai/ring-flash-2.0",
66
  "display_name": "💍️ Ring-flash-2.0",
67
+ "description": model_descriptions["ring-flash-2.0-desc"],
68
+ "url": "https://huggingface.co/inclusionAI/Ring-flash-2.0"
69
+ },
70
+ LING_MINI_2_0: {
71
+ "provider": "openai_compatible",
72
+ "model_id": "inclusionai/ling-mini-2.0",
73
+ "display_name": "🦉 Ling-mini-2.0",
74
+ "description": model_descriptions["ling-mini-2.0-desc"],
75
+ "url": "https://huggingface.co/inclusionAI/Ling-mini-2.0"
76
  },
77
  RING_MINI_2_0: {
78
  "provider": "openai_compatible",
79
  "model_id": "inclusionai/ring-mini-2.0",
80
  "display_name": "💍️ Ring-mini-2.0",
81
+ "description": model_descriptions["ring-mini-2.0-desc"],
82
+ "url": "https://huggingface.co/inclusionAI/Ring-mini-2.0"
83
  }
84
  }
85
 
86
+
87
  # --- Code Framework Specifications ---
88
 
89
  # Constants for easy referencing of code frameworks
 
142
  Retrieves the display name for a given model constant.
143
  This is what's shown in the UI.
144
  """
145
+ return CHAT_MODEL_SPECS.get(model_constant, {}).get("display_name", model_constant)
i18n/common.py CHANGED
@@ -21,6 +21,10 @@ ui_translations = {
21
  "new_conversation_title": {
22
  "en": "(New Conversation)",
23
  "zh": "(新对话)"
 
 
 
 
24
  }
25
  }
26
 
 
21
  "new_conversation_title": {
22
  "en": "(New Conversation)",
23
  "zh": "(新对话)"
24
+ },
25
+ "model_selector_label": {
26
+ "en": "Select Model",
27
+ "zh": "模型选择"
28
  }
29
  }
30
 
i18n/model_config.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ling-space/i18n/model_config.py
2
+
3
+ # Constants for easy referencing of models (these are still needed for config.py's CHAT_MODEL_SPECS keys)
4
+ LING_MINI_2_0 = "ling-mini-2.0"
5
+ LING_1T = "ling-1t"
6
+ LING_FLASH_2_0 = "ling-flash-2.0"
7
+ RING_1T = "ring-1t"
8
+ RING_FLASH_2_0 = "ring-flash-2.0"
9
+ RING_MINI_2_0 = "ring-mini-2.0"
10
+
11
+ model_descriptions = {
12
+ "ling-1t-desc": {
13
+ "zh": "万亿参数的旗舰级非“思考”模型,为通用复杂推理任务和人机协同智能而设计。擅长高效推理、代码生成、软件开发、竞赛级数学等。",
14
+ "en": "A trillion-parameter flagship non-\"thinking\" model designed for general-purpose complex reasoning and collaborative human-AI intelligence. Excels in efficient reasoning, code generation, software development, and competition-level mathematics."
15
+ },
16
+ "ring-1t-desc": {
17
+ "zh": "万亿参数的“思考”模型,专为复杂推理任务深度优化。在数学竞赛、代码生成、逻辑推理、医疗保健和创意写作等领域表现出色。",
18
+ "en": "A trillion-parameter \"thinking\" model, deeply optimized for complex reasoning tasks. It shows strong performance in math competitions, code generation, logical reasoning, healthcare, and creative writing."
19
+ },
20
+ "ling-flash-2.0-desc": {
21
+ "zh": "高性能通用语言模型,专注于推理和创意应用。在复杂推理、代码生成、前端开发和创意任务方面表现出色。",
22
+ "en": "A general-purpose language model focusing on reasoning and creative applications. It is strong in complex reasoning, code generation, frontend development, and creative tasks."
23
+ },
24
+ "ring-flash-2.0-desc": {
25
+ "zh": "高性能“思考”模型,为复杂推理深度优化。在数学竞赛、代码生成、逻辑推理、科学和医学推理及创意写作方面表现领先。",
26
+ "en": "A high-performance \"thinking\" model, deeply optimized for complex reasoning. It exhibits leading performance in math competitions, code generation, logical reasoning, scientific and medical reasoning, and creative writing."
27
+ },
28
+ "ling-mini-2.0-desc": {
29
+ "zh": "紧凑而强大的 MoE 模型,是 MoE 研究和小型 LLM 应用的理想起点。在编码、数学和知识密集型任务中表现出强大的通用和专业推理能力。",
30
+ "en": "A compact yet powerful MoE-based large language model, ideal for MoE research and small-size LLM applications. It demonstrates strong general and professional reasoning in coding, mathematics, and knowledge-intensive tasks."
31
+ },
32
+ "ring-mini-2.0-desc": {
33
+ "zh": "为推理而优化的高性能、面向推理的 MoE 模型。提供全面的推理能力,尤其擅长逻辑推理、代码生成和数学任务。",
34
+ "en": "A high-performance, inference-oriented MoE model optimized for reasoning. It offers comprehensive reasoning capabilities, particularly excelling in logical reasoning, code generation, and mathematical tasks."
35
+ }
36
+ }
i18n/tab_chat.py CHANGED
@@ -15,6 +15,10 @@ ui_translations = {
15
  "en": "History",
16
  "zh": "对话记录"
17
  },
 
 
 
 
18
  "chat_chatbot_placeholder": {
19
  "en": "Enter message...",
20
  "zh": "输入消息..."
 
15
  "en": "History",
16
  "zh": "对话记录"
17
  },
18
+ "chat_history_summary_header": {
19
+ "en": "Summary",
20
+ "zh": "内容摘要"
21
+ },
22
  "chat_chatbot_placeholder": {
23
  "en": "Enter message...",
24
  "zh": "输入消息..."
model_handler.py CHANGED
@@ -1,7 +1,7 @@
1
  from abc import ABC, abstractmethod
2
  import httpx
3
  import json
4
- from config import CHAT_MODEL_SPECS, OPEN_AI_KEY, OPEN_AI_ENTRYPOINT, OPEN_AI_PROVIDER, get_model_id
5
 
6
  class ModelProvider(ABC):
7
  """
 
1
  from abc import ABC, abstractmethod
2
  import httpx
3
  import json
4
+ from config import CHAT_MODEL_SPECS, OPEN_AI_KEY, OPEN_AI_ENTRYPOINT, OPEN_AI_PROVIDER
5
 
6
  class ModelProvider(ABC):
7
  """
static/app.html CHANGED
@@ -77,11 +77,12 @@
77
  // use toastify
78
  window.Toastify({
79
  text: args.join(' '),
80
- duration: 3000,
81
- gravity: "top",
82
  position: "right",
83
  style: {
84
- background: "green"
 
85
  }
86
  }).showToast();
87
  console.info("TOAST_INFO", ...args);
 
77
  // use toastify
78
  window.Toastify({
79
  text: args.join(' '),
80
+ duration: 2000,
81
+ gravity: "bottom",
82
  position: "right",
83
  style: {
84
+ background: "green",
85
+ fontSize: "0.8em"
86
  }
87
  }).showToast();
88
  console.info("TOAST_INFO", ...args);
tab_chat.py CHANGED
@@ -2,22 +2,136 @@ import gradio as gr
2
  import uuid
3
  from datetime import datetime
4
  import pandas as pd
 
5
  from model_handler import ModelHandler
6
  from config import CHAT_MODEL_SPECS, LING_1T
7
  from recommand_config import RECOMMENDED_INPUTS
8
  from ui_components.model_selector import create_model_selector
9
  from i18n import get_text
10
 
11
- def get_history_df(history):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
  if not history:
13
  # Provide explicit column names for an empty DataFrame
14
- return pd.DataFrame({'ID': pd.Series(dtype='str'), '对话': pd.Series(dtype='str')})
 
15
  df = pd.DataFrame(history)
 
16
  # Ensure columns exist before renaming
17
  if 'id' in df.columns and 'title' in df.columns:
18
- return df[['id', 'title']].rename(columns={'id': 'ID', '对话': '对话'})
 
 
 
19
  else:
20
- return pd.DataFrame({'ID': pd.Series(dtype='str'), '对话': pd.Series(dtype='str')})
21
 
22
 
23
  def create_chat_tab(initial_lang: str, current_lang_state: gr.State):
@@ -31,37 +145,50 @@ def create_chat_tab(initial_lang: str, current_lang_state: gr.State):
31
  current_convo = next((c for c in history if c["id"] == current_conv_id), None) if history else None
32
 
33
  if current_convo and not current_convo.get("messages", []):
34
- return current_conv_id, history, [], gr.update(value=get_history_df(history))
35
 
36
  conv_id = str(uuid.uuid4())
37
  new_convo_title = get_text('chat_new_conversation_title', lang)
38
  new_convo = {
39
  "id": conv_id, "title": new_convo_title,
40
- "messages": [], "timestamp": datetime.now().isoformat()
 
 
 
41
  }
42
  updated_history = [new_convo] + (history or [])
43
- return conv_id, updated_history, [], gr.update(value=get_history_df(updated_history))
44
 
45
  def load_conversation_from_df(df: pd.DataFrame, evt: gr.SelectData, history, lang):
46
  if evt.index is None or len(df) == 0:
47
- return None, []
 
48
  selected_id = df.iloc[evt.index[0]]['ID']
49
- for convo in history:
50
- if convo["id"] == selected_id:
51
- return selected_id, convo["messages"]
 
 
 
 
 
 
 
 
 
52
  new_id, _, new_msgs, _ = handle_new_chat(history, None, lang)
53
- return new_id, new_msgs
54
 
55
  with gr.Row(equal_height=False, elem_id="indicator-chat-tab"):
56
  with gr.Column(scale=1):
57
  new_chat_btn = gr.Button(get_text('chat_new_chat_button', initial_lang))
58
  history_df = gr.DataFrame(
59
- value=get_history_df(conversation_store.value),
60
  headers=["ID", get_text('chat_history_dataframe_header', initial_lang)],
61
  datatype=["str", "str"],
62
  interactive=False,
63
  visible=True,
64
- column_widths=["0%", "99%"]
65
  )
66
 
67
  with gr.Column(scale=4):
@@ -81,7 +208,9 @@ def create_chat_tab(initial_lang: str, current_lang_state: gr.State):
81
  with gr.Column(scale=1):
82
  model_dropdown, model_description_markdown = create_model_selector(
83
  model_specs=CHAT_MODEL_SPECS,
84
- default_model_constant=LING_1T
 
 
85
  )
86
 
87
  system_prompt_textbox = gr.Textbox(label=get_text('chat_system_prompt_label', initial_lang), lines=5, placeholder=get_text('chat_system_prompt_placeholder', initial_lang))
@@ -114,21 +243,28 @@ def create_chat_tab(initial_lang: str, current_lang_state: gr.State):
114
  for history_update in response_generator:
115
  yield history_update
116
 
117
- def on_chat_stream_complete(conv_id, history, final_chat_history, lang):
118
  current_convo = next((c for c in history if c["id"] == conv_id), None)
119
  if not current_convo:
120
  return history, gr.update()
121
 
122
- new_convo_title = get_text('chat_new_conversation_title', lang)
123
- if len(final_chat_history) > len(current_convo["messages"]) and current_convo["title"] == new_convo_title:
124
- user_message = final_chat_history[-2]["content"] if len(final_chat_history) > 1 else final_chat_history[0]["content"]
125
- current_convo["title"] = user_message[:50]
 
 
 
 
 
 
 
126
 
127
  current_convo["messages"] = final_chat_history
128
  current_convo["timestamp"] = datetime.now().isoformat()
129
 
130
  history = sorted([c for c in history if c["id"] != conv_id] + [current_convo], key=lambda x: x["timestamp"], reverse=True)
131
- return history, gr.update(value=get_history_df(history))
132
 
133
  # Store all components that need i18n updates
134
  components = {
@@ -149,7 +285,7 @@ def create_chat_tab(initial_lang: str, current_lang_state: gr.State):
149
  }
150
 
151
  # Wire event handlers
152
- recommended_dataset.select(on_select_recommendation, inputs=[conversation_store, current_conversation_id, current_lang_state], outputs=[current_conversation_id, conversation_store, model_dropdown, system_prompt_textbox, temperature_slider, textbox, history_df, chatbot], show_progress="none")
153
 
154
  submit_btn.click(
155
  chat_stream,
@@ -157,7 +293,7 @@ def create_chat_tab(initial_lang: str, current_lang_state: gr.State):
157
  [chatbot]
158
  ).then(
159
  on_chat_stream_complete,
160
- [current_conversation_id, conversation_store, chatbot, current_lang_state],
161
  [conversation_store, history_df]
162
  )
163
  textbox.submit(
@@ -166,12 +302,12 @@ def create_chat_tab(initial_lang: str, current_lang_state: gr.State):
166
  [chatbot]
167
  ).then(
168
  on_chat_stream_complete,
169
- [current_conversation_id, conversation_store, chatbot, current_lang_state],
170
  [conversation_store, history_df]
171
  )
172
 
173
  new_chat_btn.click(handle_new_chat, inputs=[conversation_store, current_conversation_id, current_lang_state], outputs=[current_conversation_id, conversation_store, chatbot, history_df])
174
- history_df.select(load_conversation_from_df, inputs=[history_df, conversation_store, current_lang_state], outputs=[current_conversation_id, chatbot])
175
 
176
  return components
177
 
 
2
  import uuid
3
  from datetime import datetime
4
  import pandas as pd
5
+ import re
6
  from model_handler import ModelHandler
7
  from config import CHAT_MODEL_SPECS, LING_1T
8
  from recommand_config import RECOMMENDED_INPUTS
9
  from ui_components.model_selector import create_model_selector
10
  from i18n import get_text
11
 
12
+ def on_app_load(request: gr.Request, history, conv_id, current_lang_state):
13
+ """
14
+ Handles the application's initial state on load.
15
+ - Determines language from URL parameter.
16
+ - Loads conversation history or creates a new one.
17
+ """
18
+ # --- Language Detection ---
19
+ query_params = dict(request.query_params)
20
+ url_lang = query_params.get("lang")
21
+
22
+ updated_lang = current_lang_state # Start with the default
23
+ if url_lang and url_lang in ["en", "zh"]:
24
+ updated_lang = url_lang
25
+
26
+ # --- History Loading Logic ---
27
+ if not history:
28
+ # First time ever, create a new conversation
29
+ conv_id = str(uuid.uuid4())
30
+ new_convo_title = get_text("chat_new_conversation_title", updated_lang)
31
+ new_convo = {
32
+ "id": conv_id,
33
+ "title": new_convo_title,
34
+ "messages": [],
35
+ "timestamp": datetime.now().isoformat(),
36
+ "system_prompt": "",
37
+ "model": CHAT_MODEL_SPECS[LING_1T]["display_name"],
38
+ "temperature": 0.7
39
+ }
40
+ history = [new_convo]
41
+ return (
42
+ conv_id,
43
+ history,
44
+ gr.update(value=get_history_df(history, updated_lang)),
45
+ [],
46
+ updated_lang,
47
+ )
48
+
49
+ if conv_id and any(c["id"] == conv_id for c in history):
50
+ # Valid last session, load it
51
+ for convo in history:
52
+ if convo["id"] == conv_id:
53
+ return (
54
+ conv_id,
55
+ history,
56
+ gr.update(value=get_history_df(history, updated_lang)),
57
+ convo["messages"],
58
+ updated_lang,
59
+ )
60
+
61
+ # Fallback to most recent conversation
62
+ most_recent_convo = history[0]
63
+ return (
64
+ most_recent_convo["id"],
65
+ history,
66
+ gr.update(value=get_history_df(history, updated_lang)),
67
+ most_recent_convo["messages"],
68
+ updated_lang,
69
+ )
70
+
71
+
72
+ def generate_conversation_title(messages, system_prompt):
73
+ """
74
+ Generates a conversation title based on a heuristic, defensively handling
75
+ multiple possible message formats.
76
+ 1. Tries to use the first user query.
77
+ 2. Falls back to the system prompt.
78
+ 3. Falls back to the current time.
79
+ """
80
+ first_query = None
81
+
82
+ # Rule 1: Try to extract the first user query from various possible formats
83
+ if messages:
84
+ first_message = messages[0]
85
+ # Case 1: List[List[str]] -> [['user', 'assistant'], ...]
86
+ if isinstance(first_message, (list, tuple)) and len(first_message) > 0:
87
+ first_query = first_message[0]
88
+ # Case 2: List[Dict] (OpenAI format or others)
89
+ elif isinstance(first_message, dict):
90
+ if first_message.get("role") == "user":
91
+ first_query = first_message.get("content")
92
+ elif "text" in first_message: # Fallback for other observed formats
93
+ first_query = first_message["text"]
94
+
95
+ if first_query and isinstance(first_query, str):
96
+ # Split by common Chinese and English punctuation and whitespace
97
+ delimiters = r"[,。?!,?!.\s]+"
98
+ segments = re.split(delimiters, first_query)
99
+
100
+ title = ""
101
+ for seg in segments:
102
+ if seg:
103
+ title += seg
104
+ if len(title) > 3:
105
+ return title[:50] # Limit title length
106
+ if title:
107
+ return title[:50]
108
+
109
+ # Rule 2: Use the system prompt
110
+ if system_prompt:
111
+ return system_prompt[:32]
112
+
113
+ # Rule 3: Use the current time
114
+ return datetime.now().strftime("%H:%M")
115
+
116
+
117
+ def get_history_df(history, lang: str):
118
+ """
119
+ Generates a language-aware DataFrame for the conversation history.
120
+ """
121
  if not history:
122
  # Provide explicit column names for an empty DataFrame
123
+ return pd.DataFrame({'ID': pd.Series(dtype='str'), get_text('chat_history_dataframe_header', lang): pd.Series(dtype='str')})
124
+
125
  df = pd.DataFrame(history)
126
+
127
  # Ensure columns exist before renaming
128
  if 'id' in df.columns and 'title' in df.columns:
129
+ header_text = get_text('chat_history_dataframe_header', lang)
130
+ # Ensure title is a string
131
+ df['title'] = df['title'].astype(str)
132
+ return df[['id', 'title']].rename(columns={'id': 'ID', 'title': header_text})
133
  else:
134
+ return pd.DataFrame({'ID': pd.Series(dtype='str'), get_text('chat_history_dataframe_header', lang): pd.Series(dtype='str')})
135
 
136
 
137
  def create_chat_tab(initial_lang: str, current_lang_state: gr.State):
 
145
  current_convo = next((c for c in history if c["id"] == current_conv_id), None) if history else None
146
 
147
  if current_convo and not current_convo.get("messages", []):
148
+ return current_conv_id, history, [], gr.update(value=get_history_df(history, lang))
149
 
150
  conv_id = str(uuid.uuid4())
151
  new_convo_title = get_text('chat_new_conversation_title', lang)
152
  new_convo = {
153
  "id": conv_id, "title": new_convo_title,
154
+ "messages": [], "timestamp": datetime.now().isoformat(),
155
+ "system_prompt": "",
156
+ "model": CHAT_MODEL_SPECS[LING_1T]["display_name"],
157
+ "temperature": 0.7
158
  }
159
  updated_history = [new_convo] + (history or [])
160
+ return conv_id, updated_history, [], gr.update(value=get_history_df(updated_history, lang))
161
 
162
  def load_conversation_from_df(df: pd.DataFrame, evt: gr.SelectData, history, lang):
163
  if evt.index is None or len(df) == 0:
164
+ return None, [], "", CHAT_MODEL_SPECS[LING_1T]["display_name"], 0.7, ""
165
+
166
  selected_id = df.iloc[evt.index[0]]['ID']
167
+ convo = next((c for c in history if c["id"] == selected_id), None)
168
+
169
+ if convo:
170
+ # Use .get() to provide defaults for old conversations
171
+ system_prompt = convo.get("system_prompt", "")
172
+ model = convo.get("model", CHAT_MODEL_SPECS[LING_1T]["display_name"])
173
+ temperature = convo.get("temperature", 0.7)
174
+
175
+ # Return updates for all components
176
+ return selected_id, convo["messages"], system_prompt, model, temperature, ""
177
+
178
+ # Fallback to creating a new chat if something goes wrong
179
  new_id, _, new_msgs, _ = handle_new_chat(history, None, lang)
180
+ return new_id, new_msgs, "", CHAT_MODEL_SPECS[LING_1T]["display_name"], 0.7, ""
181
 
182
  with gr.Row(equal_height=False, elem_id="indicator-chat-tab"):
183
  with gr.Column(scale=1):
184
  new_chat_btn = gr.Button(get_text('chat_new_chat_button', initial_lang))
185
  history_df = gr.DataFrame(
186
+ value=get_history_df(conversation_store.value, initial_lang),
187
  headers=["ID", get_text('chat_history_dataframe_header', initial_lang)],
188
  datatype=["str", "str"],
189
  interactive=False,
190
  visible=True,
191
+ column_widths=["0%", "100%"]
192
  )
193
 
194
  with gr.Column(scale=4):
 
208
  with gr.Column(scale=1):
209
  model_dropdown, model_description_markdown = create_model_selector(
210
  model_specs=CHAT_MODEL_SPECS,
211
+ default_model_constant=LING_1T,
212
+ lang_state=current_lang_state,
213
+ initial_lang=initial_lang
214
  )
215
 
216
  system_prompt_textbox = gr.Textbox(label=get_text('chat_system_prompt_label', initial_lang), lines=5, placeholder=get_text('chat_system_prompt_placeholder', initial_lang))
 
243
  for history_update in response_generator:
244
  yield history_update
245
 
246
+ def on_chat_stream_complete(conv_id, history, final_chat_history, system_prompt, model_display_name, temperature, lang):
247
  current_convo = next((c for c in history if c["id"] == conv_id), None)
248
  if not current_convo:
249
  return history, gr.update()
250
 
251
+ # Check if this is the first turn of a new conversation
252
+ new_convo_title_default = get_text('chat_new_conversation_title', lang)
253
+ is_new_conversation = current_convo["title"] == new_convo_title_default
254
+
255
+ # If it's a new conversation and we have messages, generate a title and save metadata
256
+ if is_new_conversation and len(final_chat_history) > len(current_convo.get("messages", [])):
257
+ current_convo["system_prompt"] = system_prompt
258
+ current_convo["model"] = model_display_name
259
+ current_convo["temperature"] = temperature
260
+ new_title = generate_conversation_title(final_chat_history, system_prompt)
261
+ current_convo["title"] = new_title
262
 
263
  current_convo["messages"] = final_chat_history
264
  current_convo["timestamp"] = datetime.now().isoformat()
265
 
266
  history = sorted([c for c in history if c["id"] != conv_id] + [current_convo], key=lambda x: x["timestamp"], reverse=True)
267
+ return history, gr.update(value=get_history_df(history, lang))
268
 
269
  # Store all components that need i18n updates
270
  components = {
 
285
  }
286
 
287
  # Wire event handlers
288
+ recommended_dataset.select(on_select_recommendation, inputs=[conversation_store, current_conversation_id, current_lang_state], outputs=[current_conversation_id, conversation_store, model_dropdown, system_prompt_textbox, temperature_slider, textbox, history_df, chatbot], show_progress="hidden")
289
 
290
  submit_btn.click(
291
  chat_stream,
 
293
  [chatbot]
294
  ).then(
295
  on_chat_stream_complete,
296
+ [current_conversation_id, conversation_store, chatbot, system_prompt_textbox, model_dropdown, temperature_slider, current_lang_state],
297
  [conversation_store, history_df]
298
  )
299
  textbox.submit(
 
302
  [chatbot]
303
  ).then(
304
  on_chat_stream_complete,
305
+ [current_conversation_id, conversation_store, chatbot, system_prompt_textbox, model_dropdown, temperature_slider, current_lang_state],
306
  [conversation_store, history_df]
307
  )
308
 
309
  new_chat_btn.click(handle_new_chat, inputs=[conversation_store, current_conversation_id, current_lang_state], outputs=[current_conversation_id, conversation_store, chatbot, history_df])
310
+ history_df.select(load_conversation_from_df, inputs=[history_df, conversation_store, current_lang_state], outputs=[current_conversation_id, chatbot, system_prompt_textbox, model_dropdown, temperature_slider, textbox])
311
 
312
  return components
313
 
tab_code.py CHANGED
@@ -108,7 +108,9 @@ def create_code_tab(initial_lang: str, current_lang_state: gr.State):
108
  )
109
  model_choice_dropdown, model_description_markdown = create_model_selector(
110
  model_specs=CHAT_MODEL_SPECS,
111
- default_model_constant=LING_1T
 
 
112
  )
113
  prompt_input = gr.Textbox(lines=5, placeholder=get_text('code_prompt_placeholder', initial_lang), label=get_text('code_prompt_label', initial_lang))
114
  overall_style_input = gr.Textbox(label=get_text('code_overall_style_label', initial_lang), placeholder=get_text('code_overall_style_placeholder', initial_lang), lines=2)
@@ -207,7 +209,9 @@ def create_code_tab(initial_lang: str, current_lang_state: gr.State):
207
  "fullscreen_button": fullscreen_button, "preview_output": preview_output,
208
  "source_code_tab": source_code_tab, "source_code_header": source_code_header,
209
  "code_output": code_output, "refresh_button": refresh_button,
210
- "log_chatbot": log_chatbot, "js_error_channel": js_error_channel
 
 
211
  }
212
 
213
  def update_language(lang: str, components: dict):
 
108
  )
109
  model_choice_dropdown, model_description_markdown = create_model_selector(
110
  model_specs=CHAT_MODEL_SPECS,
111
+ default_model_constant=LING_1T,
112
+ lang_state=current_lang_state,
113
+ initial_lang=initial_lang
114
  )
115
  prompt_input = gr.Textbox(lines=5, placeholder=get_text('code_prompt_placeholder', initial_lang), label=get_text('code_prompt_label', initial_lang))
116
  overall_style_input = gr.Textbox(label=get_text('code_overall_style_label', initial_lang), placeholder=get_text('code_overall_style_placeholder', initial_lang), lines=2)
 
209
  "fullscreen_button": fullscreen_button, "preview_output": preview_output,
210
  "source_code_tab": source_code_tab, "source_code_header": source_code_header,
211
  "code_output": code_output, "refresh_button": refresh_button,
212
+ "log_chatbot": log_chatbot, "js_error_channel": js_error_channel,
213
+ "model_choice_dropdown": model_choice_dropdown,
214
+ "model_description_markdown": model_description_markdown
215
  }
216
 
217
  def update_language(lang: str, components: dict):
ui_components/model_selector.py CHANGED
@@ -1,12 +1,15 @@
1
  import gradio as gr
 
2
 
3
- def create_model_selector(model_specs, default_model_constant):
4
  """
5
- Creates a reusable Gradio model selector component.
6
 
7
  Args:
8
  model_specs (dict): A dictionary containing the specifications for each model.
9
  default_model_constant (str): The key for the default model in the model_specs dictionary.
 
 
10
 
11
  Returns:
12
  tuple: A tuple containing the model dropdown and the model description markdown components.
@@ -14,27 +17,53 @@ def create_model_selector(model_specs, default_model_constant):
14
  display_names = [d["display_name"] for d in model_specs.values()]
15
  default_display_name = model_specs[default_model_constant]["display_name"]
16
 
17
-
18
  model_dropdown = gr.Dropdown(
19
  choices=display_names,
20
- label="模型选择",
21
  value=default_display_name,
22
  interactive=True
23
  )
24
 
25
- def get_model_description(model_display_name):
 
26
  for model_spec in model_specs.values():
27
  if model_spec["display_name"] == model_display_name:
28
- return model_spec["description"]
29
- return ""
 
 
 
 
 
 
 
30
 
31
- model_description_markdown = gr.Markdown(get_model_description(default_display_name),
32
- container=True)
 
33
 
 
34
  model_dropdown.change(
35
- fn=get_model_description,
36
- inputs=[model_dropdown],
37
- outputs=[model_description_markdown]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  )
39
 
40
- return model_dropdown, model_description_markdown
 
1
  import gradio as gr
2
+ from i18n import get_text
3
 
4
+ def create_model_selector(model_specs, default_model_constant, lang_state, initial_lang):
5
  """
6
+ Creates a reusable Gradio model selector component that is language-aware.
7
 
8
  Args:
9
  model_specs (dict): A dictionary containing the specifications for each model.
10
  default_model_constant (str): The key for the default model in the model_specs dictionary.
11
+ lang_state (gr.State): The Gradio state object holding the current language.
12
+ initial_lang (str): The initial language to set up the component.
13
 
14
  Returns:
15
  tuple: A tuple containing the model dropdown and the model description markdown components.
 
17
  display_names = [d["display_name"] for d in model_specs.values()]
18
  default_display_name = model_specs[default_model_constant]["display_name"]
19
 
 
20
  model_dropdown = gr.Dropdown(
21
  choices=display_names,
22
+ label=get_text("model_selector_label", initial_lang),
23
  value=default_display_name,
24
  interactive=True
25
  )
26
 
27
+ def get_model_description(model_display_name, lang):
28
+ """Fetches the description for a given model in the specified language."""
29
  for model_spec in model_specs.values():
30
  if model_spec["display_name"] == model_display_name:
31
+ # Safely access the description dictionary
32
+ description_dict = model_spec.get("description", {})
33
+ return description_dict.get(lang, "Description not available.")
34
+ return "Model not found."
35
+
36
+ model_description_markdown = gr.Markdown(
37
+ get_model_description(default_display_name, initial_lang),
38
+ container=True
39
+ )
40
 
41
+ # Handler to update the description based on dropdown and language state
42
+ def update_description(model_name, lang):
43
+ return get_model_description(model_name, lang)
44
 
45
+ # Event listener for when the model selection changes
46
  model_dropdown.change(
47
+ fn=update_description,
48
+ inputs=[model_dropdown, lang_state],
49
+ outputs=[model_description_markdown],
50
+ show_progress="hidden"
51
+ )
52
+
53
+ # Event listener for when the language changes
54
+ lang_state.change(
55
+ fn=update_description,
56
+ inputs=[model_dropdown, lang_state],
57
+ outputs=[model_description_markdown],
58
+ show_progress="hidden"
59
+ )
60
+
61
+ # Also need to update the label on language change
62
+ lang_state.change(
63
+ fn=lambda lang: gr.update(label=get_text("model_selector_label", lang)),
64
+ inputs=[lang_state],
65
+ outputs=[model_dropdown],
66
+ show_progress="hidden"
67
  )
68
 
69
+ return model_dropdown, model_description_markdown