Spaces:
Runtime error
Runtime error
ghbGC
commited on
Commit
·
994ee1b
1
Parent(s):
6cdff2b
update
Browse files- Dockerfile +44 -0
- app.py +195 -0
- weather_query.py +71 -0
Dockerfile
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# 使用官方的Python运行时作为父镜像
|
2 |
+
FROM python:3.10-slim
|
3 |
+
|
4 |
+
# 设置工作目录
|
5 |
+
WORKDIR /app
|
6 |
+
|
7 |
+
# 安装 Conda
|
8 |
+
RUN wget https://repo.anaconda.com/miniconda/Miniconda3-latest-Linux-x86_64.sh -O miniconda.sh \
|
9 |
+
&& bash miniconda.sh -b -p /opt/conda \
|
10 |
+
&& rm miniconda.sh \
|
11 |
+
&& /opt/conda/bin/conda update conda -y \
|
12 |
+
&& /opt/conda/bin/conda clean -tipsy
|
13 |
+
|
14 |
+
# 将 Conda 添加到 PATH
|
15 |
+
ENV PATH="/opt/conda/bin:${PATH}"
|
16 |
+
|
17 |
+
# 创建 Conda 环境
|
18 |
+
RUN conda create -n lagent python=3.10 -y
|
19 |
+
|
20 |
+
# 激活 Conda 环境
|
21 |
+
SHELL ["conda", "run", "-n", "lagent", "/bin/bash", "-c"]
|
22 |
+
|
23 |
+
# 安装 PyTorch 和其他依赖项
|
24 |
+
RUN conda install pytorch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 pytorch-cuda=12.1 -c pytorch -c nvidia -y
|
25 |
+
RUN pip install termcolor==2.4.0 streamlit==1.39.0 class_registry==2.1.2 datasets==3.1.0
|
26 |
+
|
27 |
+
# 克隆代码仓库
|
28 |
+
RUN git clone https://github.com/InternLM/lagent.git
|
29 |
+
WORKDIR /app/lagent
|
30 |
+
RUN git checkout e304e5d
|
31 |
+
RUN pip install -e .
|
32 |
+
WORKDIR /app
|
33 |
+
|
34 |
+
# 安装 griffe
|
35 |
+
RUN pip install griffe==0.48.0
|
36 |
+
|
37 |
+
# 拷贝应用代码到工作目录
|
38 |
+
COPY . /app
|
39 |
+
|
40 |
+
# 暴露端口
|
41 |
+
EXPOSE 8501
|
42 |
+
|
43 |
+
# 运行命令
|
44 |
+
CMD ["streamlit", "run", "app.py"]
|
app.py
ADDED
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import copy
|
2 |
+
import os
|
3 |
+
from typing import List
|
4 |
+
import streamlit as st
|
5 |
+
from lagent.actions import ArxivSearch
|
6 |
+
from lagent.prompts.parsers import PluginParser
|
7 |
+
from lagent.agents.stream import INTERPRETER_CN, META_CN, PLUGIN_CN, AgentForInternLM, get_plugin_prompt
|
8 |
+
from lagent.llms import GPTAPI
|
9 |
+
|
10 |
+
class SessionState:
|
11 |
+
"""管理会话状态的类。"""
|
12 |
+
|
13 |
+
def init_state(self):
|
14 |
+
"""初始化会话状态变量。"""
|
15 |
+
st.session_state['assistant'] = [] # 助手消息历史
|
16 |
+
st.session_state['user'] = [] # 用户消息历史
|
17 |
+
# 初始化插件列表
|
18 |
+
action_list = [
|
19 |
+
ArxivSearch(),
|
20 |
+
]
|
21 |
+
st.session_state['plugin_map'] = {action.name: action for action in action_list}
|
22 |
+
st.session_state['model_map'] = {} # 存储模型实例
|
23 |
+
st.session_state['model_selected'] = None # 当前选定模型
|
24 |
+
st.session_state['plugin_actions'] = set() # 当前激活插件
|
25 |
+
st.session_state['history'] = [] # 聊天历史
|
26 |
+
st.session_state['api_base'] = None # 初始化API base地址
|
27 |
+
|
28 |
+
def clear_state(self):
|
29 |
+
"""清除当前会话状态。"""
|
30 |
+
st.session_state['assistant'] = []
|
31 |
+
st.session_state['user'] = []
|
32 |
+
st.session_state['model_selected'] = None
|
33 |
+
|
34 |
+
|
35 |
+
class StreamlitUI:
|
36 |
+
"""管理 Streamlit 界面的类。"""
|
37 |
+
|
38 |
+
def __init__(self, session_state: SessionState):
|
39 |
+
self.session_state = session_state
|
40 |
+
self.plugin_action = [] # 当前选定的插件
|
41 |
+
# 初始化提示词
|
42 |
+
self.meta_prompt = META_CN
|
43 |
+
self.plugin_prompt = PLUGIN_CN
|
44 |
+
self.init_streamlit()
|
45 |
+
|
46 |
+
def init_streamlit(self):
|
47 |
+
"""初始化 Streamlit 的 UI 设置。"""
|
48 |
+
st.set_page_config(
|
49 |
+
layout='wide',
|
50 |
+
page_title='lagent-web',
|
51 |
+
page_icon='./docs/imgs/lagent_icon.png'
|
52 |
+
)
|
53 |
+
st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')
|
54 |
+
|
55 |
+
def setup_sidebar(self):
|
56 |
+
"""设置侧边栏,选择模型和插件。"""
|
57 |
+
# 模型名称和 API Base 输入框
|
58 |
+
model_name = st.sidebar.text_input('模型名称:', value='internlm2.5-latest')
|
59 |
+
|
60 |
+
# ================================== 硅基流动的API ==================================
|
61 |
+
# 注意,如果采用硅基流动API,模型名称需要更改为:internlm/internlm2_5-7b-chat 或者 internlm/internlm2_5-20b-chat
|
62 |
+
# api_base = st.sidebar.text_input(
|
63 |
+
# 'API Base 地址:', value='https://api.siliconflow.cn/v1/chat/completions'
|
64 |
+
# )
|
65 |
+
# ================================== 浦语官方的API ==================================
|
66 |
+
api_base = st.sidebar.text_input(
|
67 |
+
'API Base 地址:', value='https://internlm-chat.intern-ai.org.cn/puyu/api/v1/chat/completions'
|
68 |
+
)
|
69 |
+
# ==================================================================================
|
70 |
+
# 插件选择
|
71 |
+
plugin_name = st.sidebar.multiselect(
|
72 |
+
'插件选择',
|
73 |
+
options=list(st.session_state['plugin_map'].keys()),
|
74 |
+
default=[],
|
75 |
+
)
|
76 |
+
|
77 |
+
# 根据选择的插件生成插件操作列表
|
78 |
+
self.plugin_action = [st.session_state['plugin_map'][name] for name in plugin_name]
|
79 |
+
|
80 |
+
# 动态生成插件提示
|
81 |
+
if self.plugin_action:
|
82 |
+
self.plugin_prompt = get_plugin_prompt(self.plugin_action)
|
83 |
+
|
84 |
+
# 清空对话按钮
|
85 |
+
if st.sidebar.button('清空对话', key='clear'):
|
86 |
+
self.session_state.clear_state()
|
87 |
+
|
88 |
+
return model_name, api_base, self.plugin_action
|
89 |
+
|
90 |
+
def initialize_chatbot(self, model_name, api_base, plugin_action):
|
91 |
+
"""初始化 GPTAPI 实例作为 chatbot。"""
|
92 |
+
token = os.getenv("token")
|
93 |
+
if not token:
|
94 |
+
st.error("未检测到环境变量 `token`,请设置环境变量,例如 `export token='your_token_here'` 后重新运行 X﹏X")
|
95 |
+
st.stop() # 停止运行应用
|
96 |
+
|
97 |
+
# 创建完整的 meta_prompt,保留原始结构并动态插入侧边栏配置
|
98 |
+
meta_prompt = [
|
99 |
+
{"role": "system", "content": self.meta_prompt, "api_role": "system"},
|
100 |
+
{"role": "user", "content": "", "api_role": "user"},
|
101 |
+
{"role": "assistant", "content": self.plugin_prompt, "api_role": "assistant"},
|
102 |
+
{"role": "environment", "content": "", "api_role": "environment"}
|
103 |
+
]
|
104 |
+
|
105 |
+
api_model = GPTAPI(
|
106 |
+
model_type=model_name,
|
107 |
+
api_base=api_base,
|
108 |
+
key=token, # 从环境变量中获取授权令牌
|
109 |
+
meta_template=meta_prompt,
|
110 |
+
max_new_tokens=512,
|
111 |
+
temperature=0.8,
|
112 |
+
top_p=0.9
|
113 |
+
)
|
114 |
+
return api_model
|
115 |
+
|
116 |
+
def render_user(self, prompt: str):
|
117 |
+
"""渲染用户输入内容。"""
|
118 |
+
with st.chat_message('user'):
|
119 |
+
st.markdown(prompt)
|
120 |
+
|
121 |
+
def render_assistant(self, agent_return):
|
122 |
+
"""渲染助手响应内容。"""
|
123 |
+
with st.chat_message('assistant'):
|
124 |
+
content = getattr(agent_return, "content", str(agent_return))
|
125 |
+
st.markdown(content if isinstance(content, str) else str(content))
|
126 |
+
|
127 |
+
|
128 |
+
def main():
|
129 |
+
"""主函数,运行 Streamlit 应用。"""
|
130 |
+
if 'ui' not in st.session_state:
|
131 |
+
session_state = SessionState()
|
132 |
+
session_state.init_state()
|
133 |
+
st.session_state['ui'] = StreamlitUI(session_state)
|
134 |
+
else:
|
135 |
+
st.set_page_config(
|
136 |
+
layout='wide',
|
137 |
+
page_title='lagent-web',
|
138 |
+
page_icon='./docs/imgs/lagent_icon.png'
|
139 |
+
)
|
140 |
+
st.header(':robot_face: :blue[Lagent] Web Demo ', divider='rainbow')
|
141 |
+
|
142 |
+
# 设置侧边栏并获取模型和插件信息
|
143 |
+
model_name, api_base, plugin_action = st.session_state['ui'].setup_sidebar()
|
144 |
+
plugins = [dict(type=f"lagent.actions.{plugin.__class__.__name__}") for plugin in plugin_action]
|
145 |
+
|
146 |
+
if (
|
147 |
+
'chatbot' not in st.session_state or
|
148 |
+
model_name != st.session_state['chatbot'].model_type or
|
149 |
+
'last_plugin_action' not in st.session_state or
|
150 |
+
plugin_action != st.session_state['last_plugin_action'] or
|
151 |
+
api_base != st.session_state['api_base']
|
152 |
+
):
|
153 |
+
# 更新 Chatbot
|
154 |
+
st.session_state['chatbot'] = st.session_state['ui'].initialize_chatbot(model_name, api_base, plugin_action)
|
155 |
+
st.session_state['last_plugin_action'] = plugin_action # 更新插件状态
|
156 |
+
st.session_state['api_base'] = api_base # 更新 API Base 地址
|
157 |
+
|
158 |
+
# 初始化 AgentForInternLM
|
159 |
+
st.session_state['agent'] = AgentForInternLM(
|
160 |
+
llm=st.session_state['chatbot'],
|
161 |
+
plugins=plugins,
|
162 |
+
output_format=dict(
|
163 |
+
type=PluginParser,
|
164 |
+
template=PLUGIN_CN,
|
165 |
+
prompt=get_plugin_prompt(plugin_action)
|
166 |
+
)
|
167 |
+
)
|
168 |
+
# 清空对话历史
|
169 |
+
st.session_state['session_history'] = []
|
170 |
+
|
171 |
+
if 'agent' not in st.session_state:
|
172 |
+
st.session_state['agent'] = None
|
173 |
+
|
174 |
+
agent = st.session_state['agent']
|
175 |
+
for prompt, agent_return in zip(st.session_state['user'], st.session_state['assistant']):
|
176 |
+
st.session_state['ui'].render_user(prompt)
|
177 |
+
st.session_state['ui'].render_assistant(agent_return)
|
178 |
+
|
179 |
+
# 处理用户输入
|
180 |
+
if user_input := st.chat_input(''):
|
181 |
+
st.session_state['ui'].render_user(user_input)
|
182 |
+
|
183 |
+
# 调用模型时确保侧边栏的系统提示词和插件提示词生效
|
184 |
+
res = agent(user_input, session_id=0)
|
185 |
+
st.session_state['ui'].render_assistant(res)
|
186 |
+
|
187 |
+
# 更新会话状态
|
188 |
+
st.session_state['user'].append(user_input)
|
189 |
+
st.session_state['assistant'].append(copy.deepcopy(res))
|
190 |
+
|
191 |
+
st.session_state['last_status'] = None
|
192 |
+
|
193 |
+
|
194 |
+
if __name__ == '__main__':
|
195 |
+
main()
|
weather_query.py
ADDED
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import requests
|
3 |
+
from lagent.actions.base_action import BaseAction, tool_api
|
4 |
+
from lagent.schema import ActionReturn, ActionStatusCode
|
5 |
+
|
6 |
+
class WeatherQuery(BaseAction):
|
7 |
+
def __init__(self):
|
8 |
+
super().__init__()
|
9 |
+
self.api_key = os.getenv("weather_token")
|
10 |
+
print(self.api_key)
|
11 |
+
if not self.api_key:
|
12 |
+
raise EnvironmentError("未找到环境变量 'token'。请设置你的和风天气 API Key 到 'weather_token' 环境变量中,比如export weather_token='xxx' ")
|
13 |
+
|
14 |
+
@tool_api
|
15 |
+
def run(self, location: str) -> dict:
|
16 |
+
"""
|
17 |
+
查询实时天气信息。
|
18 |
+
|
19 |
+
Args:
|
20 |
+
location (str): 要查询的地点名称、LocationID 或经纬度坐标(如 "101010100" 或 "116.41,39.92")。
|
21 |
+
|
22 |
+
Returns:
|
23 |
+
dict: 包含天气信息的字典
|
24 |
+
* location: 地点名称
|
25 |
+
* weather: 天气状况
|
26 |
+
* temperature: 当前温度
|
27 |
+
* wind_direction: 风向
|
28 |
+
* wind_speed: 风速(公里/小时)
|
29 |
+
* humidity: 相对湿度(%)
|
30 |
+
* report_time: 数据报告时间
|
31 |
+
"""
|
32 |
+
try:
|
33 |
+
# 如果 location 不是坐标格式(例如 "116.41,39.92"),则调用 GeoAPI 获取 LocationID
|
34 |
+
if not ("," in location and location.replace(",", "").replace(".", "").isdigit()):
|
35 |
+
# 使用 GeoAPI 获取 LocationID
|
36 |
+
geo_url = f"https://geoapi.qweather.com/v2/city/lookup?location={location}&key={self.api_key}"
|
37 |
+
geo_response = requests.get(geo_url)
|
38 |
+
geo_data = geo_response.json()
|
39 |
+
|
40 |
+
if geo_data.get("code") != "200" or not geo_data.get("location"):
|
41 |
+
raise Exception(f"GeoAPI 返回错误码:{geo_data.get('code')} 或未找到位置")
|
42 |
+
|
43 |
+
location = geo_data["location"][0]["id"]
|
44 |
+
|
45 |
+
# 构建天气查询的 API 请求 URL
|
46 |
+
weather_url = f"https://devapi.qweather.com/v7/weather/now?location={location}&key={self.api_key}"
|
47 |
+
response = requests.get(weather_url)
|
48 |
+
data = response.json()
|
49 |
+
|
50 |
+
# 检查 API 响应码
|
51 |
+
if data.get("code") != "200":
|
52 |
+
raise Exception(f"Weather API 返回错误码:{data.get('code')}")
|
53 |
+
|
54 |
+
# 解析和组织天气信息
|
55 |
+
weather_info = {
|
56 |
+
"location": location,
|
57 |
+
"weather": data["now"]["text"],
|
58 |
+
"temperature": data["now"]["temp"] + "°C",
|
59 |
+
"wind_direction": data["now"]["windDir"],
|
60 |
+
"wind_speed": data["now"]["windSpeed"] + " km/h",
|
61 |
+
"humidity": data["now"]["humidity"] + "%",
|
62 |
+
"report_time": data["updateTime"]
|
63 |
+
}
|
64 |
+
|
65 |
+
return {"result": weather_info}
|
66 |
+
|
67 |
+
except Exception as exc:
|
68 |
+
return ActionReturn(
|
69 |
+
errmsg=f"WeatherQuery 异常:{exc}",
|
70 |
+
state=ActionStatusCode.HTTP_ERROR
|
71 |
+
)
|