jackkuo commited on
Commit
f7d9ae0
·
1 Parent(s): b24eddb
Files changed (3) hide show
  1. .gradio/flagged/dataset1.csv +3 -0
  2. app.py +74 -40
  3. requirements.txt +1 -1
.gradio/flagged/dataset1.csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ Query,Generated Words,timestamp
2
+ give me some english words,"成功生成 141 个英文单词: ['🚀 开始生成200个英文单词...\n', 'the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'I', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 'at', 'this', 'but', 'his', 'by', 'from', 'they', 'we', 'say', 'her', 'she', 'or', 'an', 'will', 'my', 'one', 'all', 'would', 'there', 'their', 'what', 'so', 'up', 'out', 'if', 'about', 'who', 'get', 'which', 'go', 'me', 'when', 'make', 'can', 'like', 'time', 'no', 'just', 'him', 'know', 'take', 'people', 'into', 'year', 'your', 'good', 'some', 'could', 'them', 'see', 'other', 'than', 'then', 'now', 'look', 'only', 'come', 'its', 'over', 'think', 'also', 'back', 'after', 'use', 'two', 'how', 'our', 'work', 'first', 'well', 'way', 'even', 'new', 'want', 'because', 'any', 'these', 'give', 'day', 'most', 'us', 'very', 'life', 'after', 'call', 'world', 'over', 'still', 'take', 'every', 'through', 'before', 'long', 'where', 'much', 'should', 'well', 'people', 'down', 'own', 'work', 'first', 'good', 'new', 'write', 'our', 'used', 'me', 'man', 'too', 'any', 'day', 'same', 'right', 'look', 'think', 'also', 'around', 'another', 'came', '\n✅ 200个英文单词生成完成!']",2025-08-26 11:09:12.950476
3
+ give me some english words,"成功生成 141 个英文单词: ['🚀 开始生成200个英文单词...\n', 'the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have', 'I', 'it', 'for', 'not', 'on', 'with', 'he', 'as', 'you', 'do', 'at', 'this', 'but', 'his', 'by', 'from', 'they', 'we', 'say', 'her', 'she', 'or', 'an', 'will', 'my', 'one', 'all', 'would', 'there', 'their', 'what', 'so', 'up', 'out', 'if', 'about', 'who', 'get', 'which', 'go', 'me', 'when', 'make', 'can', 'like', 'time', 'no', 'just', 'him', 'know', 'take', 'people', 'into', 'year', 'your', 'good', 'some', 'could', 'them', 'see', 'other', 'than', 'then', 'now', 'look', 'only', 'come', 'its', 'over', 'think', 'also', 'back', 'after', 'use', 'two', 'how', 'our', 'work', 'first', 'well', 'way', 'even', 'new', 'want', 'because', 'any', 'these', 'give', 'day', 'most', 'us', 'very', 'life', 'after', 'call', 'world', 'over', 'still', 'take', 'every', 'through', 'before', 'long', 'where', 'much', 'should', 'well', 'people', 'down', 'own', 'work', 'first', 'good', 'new', 'write', 'our', 'used', 'me', 'man', 'too', 'any', 'day', 'same', 'right', 'look', 'think', 'also', 'around', 'another', 'came', '\n✅ 200个英文单词生成完成!']",2025-08-26 11:09:20.766123
app.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import gradio as gr
2
  import asyncio
3
  import json
@@ -40,37 +41,35 @@ async def generate_words_stream(query: str) -> AsyncGenerator[str, None]:
40
  yield f"\n✅ 200个英文单词生成完成!"
41
 
42
  def generate_words_mcp(query: str = "give me some english words") -> str:
43
- """MCP工具包装函数:流式获取英文单词,返回结果给MCP客户端"""
 
 
 
 
 
 
 
 
44
  try:
45
- # 调用原始函数并收集结果
46
- result = []
47
- # 注意:这里需要处理异步函数
48
- async def collect_tokens():
49
- async for token in generate_words_stream(query):
50
- if token.strip():
51
- result.append(token)
52
- return result
53
-
54
- # 运行异步函数
55
- loop = asyncio.new_event_loop()
56
- asyncio.set_event_loop(loop)
57
- tokens = loop.run_until_complete(collect_tokens())
58
- loop.close()
59
-
60
- # 返回结果给MCP客户端 - 返回全部单词
61
- return f"成功生成 {len(tokens)} 个英文单词: {tokens}"
62
  except Exception as e:
63
  return f"生成单词时出错: {str(e)}"
64
 
65
- async def generate_words_mcp_stream(query: str = "give me some english words") -> AsyncGenerator[str, None]:
66
- """MCP工具:流式返回英文单词"""
67
- try:
68
- async for token in generate_words_stream(query):
69
- if token.strip():
70
- yield token
71
- except Exception as e:
72
- yield f"生成单词时出错: {str(e)}"
 
 
 
73
 
 
74
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
75
  gr.Markdown("# 🧠 English Words Generator")
76
  gr.Markdown("输入你的查询,AI 将为你生成 200 个英文单词(流式输出)")
@@ -94,11 +93,14 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
94
  send_btn = gr.Button("发送", variant="primary", size="lg")
95
  with gr.Column(scale=1):
96
  clear_btn = gr.Button("清空", variant="secondary")
 
 
97
 
98
  def handle_user_input(query, messages):
99
  """添加用户消息"""
100
  if query.strip():
101
- new_messages = messages + [{"role": "user", "content": query}]
 
102
  return "", new_messages
103
  return query, messages
104
 
@@ -106,24 +108,58 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
106
  """清空对话"""
107
  return []
108
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
109
  async def generate_response(messages):
110
  """根据用户最后一条消息流式生成 AI 回复"""
111
- if not messages or messages[-1]["role"] != "user":
112
  yield messages
113
  return
114
 
115
- last_user_msg = messages[-1]["content"]
116
-
117
- # 添加 AI 回复占位符
118
- messages.append({"role": "assistant", "content": "正在生成单词..."})
119
- yield messages
120
 
121
  # 流式拼接回复
122
  full_response = ""
123
  async for token in generate_words_stream(last_user_msg):
124
  if token.strip():
125
  full_response += " " + token
126
- messages[-1] = {"role": "assistant", "content": full_response.strip()}
 
127
  yield messages
128
 
129
  # 用户提交时,先加消息 → 再生成回复
@@ -134,12 +170,10 @@ with gr.Blocks(theme=gr.themes.Soft()) as demo:
134
  .then(generate_response, inputs=chatbot, outputs=chatbot)
135
 
136
  clear_btn.click(clear_chat, outputs=chatbot)
 
 
 
137
 
138
- # 注册MCP工具 - 使用包装函数并正确配置输出
139
- demo.load(generate_words_mcp, inputs=None, outputs=gr.Textbox(label="MCP结果", visible=False))
140
- # 注册流式MCP工具
141
- demo.load(generate_words_mcp_stream, inputs=None, outputs=gr.Textbox(label="流式MCP结果", visible=False))
142
-
143
- # 开启 MCP server
144
  if __name__ == "__main__":
145
  demo.launch(mcp_server=True)
 
1
+
2
  import gradio as gr
3
  import asyncio
4
  import json
 
41
  yield f"\n✅ 200个英文单词生成完成!"
42
 
43
  def generate_words_mcp(query: str = "give me some english words") -> str:
44
+ """
45
+ Generate 200 English words based on a query.
46
+
47
+ Args:
48
+ query (str): The input query for generating words. Default is "give me some english words".
49
+
50
+ Returns:
51
+ str: A message indicating the number of words generated and the complete list of words.
52
+ """
53
  try:
54
+ # 直接返回200个英文单词,简化MCP函数
55
+ words_text = " ".join(ENGLISH_WORDS)
56
+ return f"成功生成 {len(ENGLISH_WORDS)} 个英文单词: {words_text}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
57
  except Exception as e:
58
  return f"生成单词时出错: {str(e)}"
59
 
60
+ def get_word_count(query: str = "count words") -> str:
61
+ """
62
+ Get the count of English words available.
63
+
64
+ Args:
65
+ query (str): The input query. Default is "count words".
66
+
67
+ Returns:
68
+ str: The total number of English words available.
69
+ """
70
+ return f"总共有 {len(ENGLISH_WORDS)} 个英文单词可用"
71
 
72
+ # 创建对话界面
73
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
74
  gr.Markdown("# 🧠 English Words Generator")
75
  gr.Markdown("输入你的查询,AI 将为你生成 200 个英文单词(流式输出)")
 
93
  send_btn = gr.Button("发送", variant="primary", size="lg")
94
  with gr.Column(scale=1):
95
  clear_btn = gr.Button("清空", variant="secondary")
96
+ with gr.Column(scale=1):
97
+ download_btn = gr.Button("下载", variant="secondary")
98
 
99
  def handle_user_input(query, messages):
100
  """添加用户消息"""
101
  if query.strip():
102
+ # 使用正确的格式:[user_message, bot_message]
103
+ new_messages = messages + [[query, None]]
104
  return "", new_messages
105
  return query, messages
106
 
 
108
  """清空对话"""
109
  return []
110
 
111
+ def download_chat(messages):
112
+ """下载对话记录为文本文件"""
113
+ if not messages:
114
+ return None
115
+
116
+ # 生成对话内容
117
+ from datetime import datetime
118
+ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
119
+
120
+ chat_content = "# 英文单词生成对话记录\n\n"
121
+ chat_content += f"导出时间: {current_time}\n"
122
+ chat_content += f"对话条数: {len(messages)}\n\n"
123
+ chat_content += "=" * 50 + "\n\n"
124
+
125
+ for i, message in enumerate(messages, 1):
126
+ if len(message) == 2:
127
+ user_msg, bot_msg = message
128
+ chat_content += f"## 对话 {i}\n\n"
129
+ chat_content += f"**用户**: {user_msg}\n\n"
130
+ if bot_msg:
131
+ chat_content += f"**AI**: {bot_msg}\n\n"
132
+ else:
133
+ chat_content += f"**AI**: 正在生成中...\n\n"
134
+ chat_content += "-" * 30 + "\n\n"
135
+
136
+ # 创建临时文件
137
+ import tempfile
138
+
139
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
140
+
141
+ # 创建临时文件
142
+ temp_file = tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt', prefix='chat_')
143
+ temp_file.write(chat_content)
144
+ temp_file.close()
145
+
146
+ return temp_file.name
147
+
148
  async def generate_response(messages):
149
  """根据用户最后一条消息流式生成 AI 回复"""
150
+ if not messages or not messages[-1] or len(messages[-1]) != 2:
151
  yield messages
152
  return
153
 
154
+ last_user_msg = messages[-1][0] # 获取用户消息
 
 
 
 
155
 
156
  # 流式拼接回复
157
  full_response = ""
158
  async for token in generate_words_stream(last_user_msg):
159
  if token.strip():
160
  full_response += " " + token
161
+ # 更新最后一条消息的bot回复部分
162
+ messages[-1][1] = full_response.strip()
163
  yield messages
164
 
165
  # 用户提交时,先加消息 → 再生成回复
 
170
  .then(generate_response, inputs=chatbot, outputs=chatbot)
171
 
172
  clear_btn.click(clear_chat, outputs=chatbot)
173
+
174
+ # 下载按钮事件
175
+ download_btn.click(download_chat, inputs=chatbot, outputs=gr.File(label="下载对话记录"))
176
 
177
+ # 启动应用
 
 
 
 
 
178
  if __name__ == "__main__":
179
  demo.launch(mcp_server=True)
requirements.txt CHANGED
@@ -1 +1 @@
1
- gradio[mcp]>=4.44.1
 
1
+ gradio[mcp]>=4.43.1