Skip to content

Commit

Permalink
更新.devcontainer.json和页面文件***
Browse files Browse the repository at this point in the history
***更新.devcontainer.json文件以使用Python 3镜像。更新页面文件以修复路径问题和改进用户界面。
  • Loading branch information
jamiesun committed Feb 22, 2024
1 parent b90210c commit cfb5d1f
Show file tree
Hide file tree
Showing 7 changed files with 190 additions and 127 deletions.
Binary file added .DS_Store
Binary file not shown.
33 changes: 0 additions & 33 deletions .devcontainer/devcontainer.json

This file was deleted.

69 changes: 50 additions & 19 deletions apps/chatbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,32 @@
from libs.llms import openai_streaming
from libs.session import PageSessionState

sys.path.append(os.path.abspath('..'))
sys.path.append(os.path.abspath(".."))
load_dotenv()

depth_list = ["Middle School", "Highschool", "College Prep", "Undergraduate",
"Graduate", "Master's", "Doctoral Candidate", "Postdoc", "Ph.D"]

command_list = ["", "/plan", "/start", "/continue", "/test choice", "/test program",
"/result", "/help", "/config 中文"]
depth_list = [
"Middle School",
"Highschool",
"College Prep",
"Undergraduate",
"Graduate",
"Master's",
"Doctoral Candidate",
"Postdoc",
"Ph.D",
]

command_list = [
"",
"/plan",
"/start",
"/continue",
"/test choice",
"/test program",
"/result",
"/help",
"/config 中文",
]


def get_chatbot_page(botname, knowledge_name, mr_ranedeer=False, show_libs=False):
Expand Down Expand Up @@ -48,7 +66,9 @@ def on_input_prompt(iprompt: str):
return
page_state.chat_prompt = iprompt
start_chat_streaming()
page_state.add_chat_msg("messages", {"role": "user", "content": page_state.chat_prompt})
page_state.add_chat_msg(
"messages", {"role": "user", "content": page_state.chat_prompt}
)
with st.chat_message("user"):
st.write(page_state.chat_prompt)

Expand All @@ -73,24 +93,30 @@ def on_input_prompt(iprompt: str):

stop_action = st.sidebar.empty()
if not page_state.streaming_end:
stop_action.button('停止输出', on_click=end_chat_streaming, help="点击此按钮停止流式输出")
stop_action.button("停止输出", on_click=end_chat_streaming, help="点击此按钮停止流式输出")

# 用户输入响应,如果上一条消息不是助手的消息,且上一条用户消息还没有处理完毕
if (page_state.messages
and page_state.messages[-1]["role"] != "assistant"
and not page_state.last_user_msg_processed):
if (
page_state.messages
and page_state.messages[-1]["role"] != "assistant"
and not page_state.last_user_msg_processed
):
with st.chat_message("assistant"):
with st.spinner("Thinking..."):
# 检索知识库
kmsg = search_knowledge(knowledge_name, page_state.chat_prompt)
if kmsg != "" and show_libs:
st.expander("📚 知识库检索结果", expanded=False).markdown(kmsg)
sysmsg = get_system_message(botname, kmsg, depth=page_state.mr_ranedeer_depth)
sysmsg = get_system_message(
botname, kmsg, depth=page_state.mr_ranedeer_depth
)
response = openai_streaming(sysmsg, page_state.messages[-10:])
# 流式输出
placeholder = st.empty()
full_response = ''
page_state.add_chat_msg("messages", {"role": "assistant", "content": ""})
full_response = ""
page_state.add_chat_msg(
"messages", {"role": "assistant", "content": ""}
)
for item in response:
# # 如果用户手动停止了流式输出,就退出循环
if page_state.streaming_end:
Expand All @@ -99,15 +125,20 @@ def on_input_prompt(iprompt: str):
if text is not None:
full_response += text
placeholder.markdown(full_response)
page_state.update_last_msg("messages", {"role": "assistant", "content": full_response})
page_state.update_last_msg(
"messages", {"role": "assistant", "content": full_response}
)
placeholder.markdown(full_response)

stop_action.empty()
end_chat_streaming()

st.sidebar.download_button('导出对话历史',
data=json.dumps(page_state.messages, ensure_ascii=False),
file_name="chat_history.json", mime="application/json")
st.sidebar.download_button(
"导出对话历史",
data=json.dumps(page_state.messages, ensure_ascii=False),
file_name="chat_history.json",
mime="application/json",
)

if st.sidebar.button('清除对话历史'):
if st.sidebar.button("清除对话历史"):
page_state.messages = []
94 changes: 68 additions & 26 deletions libs/mindmap.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,23 @@


class MindmapItem(BaseModel):
title: str = Field(..., title="Mindmap Title as root node,required", description="Mindmap Title, Root node",
example="Python 学习")
structure: Dict[str, List[str]] = Field(...,
title="Mindmap Structure data, required",
description="Mindmap Structure data, "
"The title value must be included in the structure's keys",
example={
"Python 学习": ["基础知识", "高级主题"],
"基础知识": ["变量", "数据类型", "控制流"],
"高级主题": ["面向对象", "装饰器", "迭代器"]
})
title: str = Field(
...,
title="Mindmap Title as root node,required",
description="Mindmap Title, Root node",
example="Python 学习",
)
structure: Dict[str, List[str]] = Field(
...,
title="Mindmap Structure data, required",
description="Mindmap Structure data, "
"The title value must be included in the structure's keys",
example={
"Python 学习": ["基础知识", "高级主题"],
"基础知识": ["变量", "数据类型", "控制流"],
"高级主题": ["面向对象", "装饰器", "迭代器"],
},
)


def generate_light_color(pcolor: str):
Expand All @@ -28,7 +34,7 @@ def generate_light_color(pcolor: str):
g = int(g + 0.65 * (255 - g))
b = int(b + 0.65 * (255 - b))

return '#%02x%02x%02x' % (r, g, b)
return "#%02x%02x%02x" % (r, g, b)


def generate_random_dark_color():
Expand All @@ -39,36 +45,72 @@ def generate_random_dark_color():
r = random.randint(0, 100)
g = random.randint(0, 100)
b = random.randint(0, 100)
return f'#{r:02x}{g:02x}{b:02x}'
return f"#{r:02x}{g:02x}{b:02x}"


# 改进的思维导图构建函数
def build_mind_map(graph, node, parent, structure, level=0, parent_color=None):
# 根据层级设置样式
if level == 0: # 根节点
node_color = generate_random_dark_color()
graph.node(node, style='filled', color=node_color, fontsize="21", fontname='Noto Sans',
fontcolor='white',
shape='ellipse', peripheries="2", label=node)
graph.node(
node,
style="filled",
color=node_color,
fontsize="21",
fontname="Noto Sans",
fontcolor="white",
shape="ellipse",
peripheries="2",
label=node,
)
elif level == 1: # 第二层节点
node_color = generate_random_dark_color()
graph.node(node, style='filled', color=node_color, fontsize="18", fontname='Noto Sans',
fontcolor='white',
shape='egg', peripheries="2", label=node)
graph.node(
node,
style="filled",
color=node_color,
fontsize="18",
fontname="Noto Sans",
fontcolor="white",
shape="egg",
peripheries="2",
label=node,
)
elif level == 2: # 第三层节点
node_color = generate_light_color(parent_color)
graph.node(node, style='filled', color=node_color, fontsize="16", shape='Mrecord', fontname='Noto Sans',
label=node)
graph.node(
node,
style="filled",
color=node_color,
fontsize="16",
shape="Mrecord",
fontname="Noto Sans",
label=node,
)
else: # 其他层级
node_color = generate_light_color(parent_color)
graph.node(node, style='filled', color=node_color, fontsize="14", shape='Mrecord', fontname='Noto Sans',
label=node)
graph.node(
node,
style="filled",
color=node_color,
fontsize="14",
shape="Mrecord",
fontname="Noto Sans",
label=node,
)

# 连接节点
if parent:
graph.edge(parent, node, penwidth='3.0', arrowhead="diamond", color=node_color)
graph.edge(parent, node, penwidth="3.0", arrowhead="diamond", color=node_color)

# 递归构建子节点
for child in structure.get(node, []):
build_mind_map(graph, child, node, structure, level=level + 1,
parent_color=node_color if level == 1 else parent_color)
build_mind_map(
graph,
child,
node,
structure,
level=level + 1,
parent_color=node_color if level == 1 else parent_color,
)
52 changes: 29 additions & 23 deletions pages/02_💥方程式杀手.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,20 +20,23 @@
@st.cache_data
def get_inference(equation_str, solution_str):
try:
messages = [{
"role": "system",
"content": "请你充当一个数学老师, 我会提供给你一个方程式和它的解,"
"你需要提供给我解释这个方程式的求解过程,优化策略如下:\n\n"
"- 你需要分析并解释这个方程式的求解过程\n"
"- 你需要尽量使用简单的语言来解释\n"
"- 请将公式使用$括起来\n\n"
}, {
"role": "user",
"content": f"解释以下方程的求解过程,让我们一步一步分析:\n\n"
f"方程: {equation_str}\n\n"
f"解: {solution_str}\n\n"
f"解释:"
}]
messages = [
{
"role": "system",
"content": "请你充当一个数学老师, 我会提供给你一个方程式和它的解,"
"你需要提供给我解释这个方程式的求解过程,优化策略如下:\n\n"
"- 你需要分析并解释这个方程式的求解过程\n"
"- 你需要尽量使用简单的语言来解释\n"
"- 请将公式使用$括起来\n\n",
},
{
"role": "user",
"content": f"解释以下方程的求解过程,让我们一步一步分析:\n\n"
f"方程: {equation_str}\n\n"
f"解: {solution_str}\n\n"
f"解释:",
},
]
print(messages)
response = client.chat.completions.create(
model="gpt-4-1106-preview",
Expand All @@ -46,12 +49,13 @@ def get_inference(equation_str, solution_str):
return result
except Exception as e:
import traceback

traceback.print_exc()
return str(e)


if 'chat_running' not in st.session_state:
st.session_state['chat_running'] = False
if "chat_running" not in st.session_state:
st.session_state["chat_running"] = False


# 设置标题和副标题
Expand All @@ -66,7 +70,9 @@ def get_inference(equation_str, solution_str):
left_expr = lcol.text_input("方程左侧表达式,比如(2 * x^2)", "a*x**2 + b*x")

# 在中间列显示等号,并调整位置
mcol.markdown("<h3 style='text-align: center; margin-top: 20px;'>=</h3>", unsafe_allow_html=True)
mcol.markdown(
"<h3 style='text-align: center; margin-top: 20px;'>=</h3>", unsafe_allow_html=True
)

# 在右侧列创建右侧表达式输入框
right_expr = rcol.text_input("方程右侧表达式", "c")
Expand All @@ -79,7 +85,7 @@ def get_inference(equation_str, solution_str):

# 解析表达式
try:
equation = sp.sympify(left_expr + "-" + right_expr, evaluate=False)
equation = sp.sympify(left_expr + "-" + right_expr, evaluate=False)
except Exception as e:
equation = None
st.error(f"无效的表达式,请检查输入的表达式是否正确, {e}")
Expand All @@ -103,21 +109,21 @@ def get_inference(equation_str, solution_str):
for solution in solutions:
st.latex(sp.latex(solution))

if col3.button("推理", disabled=st.session_state['chat_running']):
if col3.button("推理", disabled=st.session_state["chat_running"]):
# 创建方程式和解的字符串表示
st.session_state['chat_running'] = True
st.session_state["chat_running"] = True
with st.spinner("Thinking..."):
solutions = sp.solve(equation, symbols)
equation_str = f"{left_expr} = {right_expr}"
solution_str = ', '.join([sp.latex(sol) for sol in solutions])
solution_str = ", ".join([sp.latex(sol) for sol in solutions])

# 获取推理结果
result = get_inference(equation_str, solution_str)
st.write("推理结果:")
st.markdown("---")
st.markdown(result)
st.session_state['chat_running'] = False
st.session_state["chat_running"] = False


if st.session_state['chat_running']:
if st.session_state["chat_running"]:
st.write("推理任务正在运行中,请等待...")
Loading

0 comments on commit cfb5d1f

Please sign in to comment.