chat_service.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. import ollama
  2. import psycopg2
  3. import json
  4. import uuid
  5. import datetime
  6. from llm_model.query import query
  7. from psycopg2.extras import DictCursor
  8. from app.utils.pinyin_utils import replace_word
  9. from app.common.word import target_word
  10. from app.common.res import res_success, res_error
  11. from app.utils.log_utils import logger
  12. chat_history = "用户:你好,我是智能助手,请问有什么可以帮助您?\\n智能助手:好的,请问您有什么需求?"
  13. sys_xuanzhi = """请扮演文本提取工具,根据输入和聊天上下文信息,基于以下因子选择、选址范围和用地类型提取这句话中的关键信息,提取到的结果请严格以json格式字符串输出并保障寄送格式正确无误,
  14. 选址范围 = ['抱坡区','天涯区','崖州区','海棠区','吉阳区' ],
  15. 因子选择 = ["高程","坡度","永久基本农田","城镇开发边界内","生态保护红线","文化保护区","自然保护地","风景名胜区","国有使用权","河道管理线","水库","公益林","火葬场","垃圾处理场","污水处理场","高压线","变电站","古树","城市道路","主要出入口","文化活动设施","体育运动场所","排水","供水","燃气","电力","电信","十五分钟社区生活圈邻里中心","社区服务设施","零售商业场所","医疗卫生设施","幼儿园服务半径","小学服务半径","为老服务设施"],
  16. 用地类型 = ['园地','耕地','林地','草地','湿地','公共卫生用地','老年人社会福利用地','儿童社会福利用地','残疾人社会福利用地','其他社会福利用地','零售商业用地','批发市场用地','餐饮用地','旅馆用地','公用设施营业网点用地','娱乐用地','康体用地','一类工业用地','二类工业用地','广播电视设施用地','环卫用地','消防用地','干渠','水工设施用地','其他公用设施用地','公园绿地','防护绿地','广场用地','军事设施用地','使领馆用地','宗教用地','文物古迹用地','监教场所用地','殡葬用地','其他特殊用地','河流水面','湖泊水面','水库水面','坑塘水面','沟渠','冰川及常年积雪','渔业基础设施用海','增养殖用海','捕捞海域','工业用海','盐田用海','固体矿产用海','油气用海','可再生能源用海','海底电缆管道用海','港口用海','农业设施建设用地','工矿用地','畜禽养殖设施建设用地','水产养殖设施建设用地','城镇住宅用地','特殊用地','居住用地','绿地与开敞空间用地','水田','水浇地','旱地','果园','茶园','橡胶园','其他园地','乔木林地','竹林地','城镇社区服务设施用地','农村宅基地','农村社区服务设施用地','机关团体用地','科研用地','文化用地','教育用地','体育用地','医疗卫生用地','社会福利用地','商业用地','商务金融用地','二类农村宅基地','图书与展览用地','文化活动用地','高等教育用地','中等职业教育用地','体育训练用地','其他交通设施用地','供水用地','排水用地','供电用地','供燃气用地','供热用地','通信用地','邮政用地','医院用地','基层医疗卫生设施用地','田间道','盐碱地','沙地','裸土地','裸岩石砾地','村道用地','村庄内部道路用地','公共管理与公共服务用地','仓储用地','交通运输用地','公用设施用地','交通运输用海','航运用海','路桥隧道用海','风景旅游用海','文体休闲娱乐用海','军事用海','其他特殊用海','空闲地','田坎','港口码头用地','管道运输用地','城市轨道交通用地','城镇道路用地','交通场站用地','一类城镇住宅用地','二类城镇住宅用地','三类城镇住宅用地','一类农村宅基地','商业服务业用地','三类工业用地','一类物流仓储用地','二类物流仓储用地','三类物流仓储用地','盐田','对外交通场站用地','公共交通场站用地','社会停车场用地','中小学用地','幼儿园用地','其他教育用地','体育场馆用地','灌木林地','其他林地','天然牧草地','人工牧草地','其他草地','森林沼泽','灌丛沼泽','沼泽草地','其他沼泽地','沿海滩涂','内陆滩涂','红树林地','乡村道路用地','种植设施建设用地','娱乐康体用地','其他商业服务业用地','工业用地','采矿用地','物流仓储用地','储备库用地','铁路用地','公路用地','机场用地'],
  17. landType是用地类型
  18. districtName是选址范围
  19. area是用地大小,单位统一转换为亩
  20. factors是因子选择
  21. 其他公里、千米的单位转换为米
  22. 输出json格式数据如下:
  23. {
  24.     "districtName": "抱坡区",
  25. "landType": "居住用地",
  26.     "area": {
  27.         "min": 30,
  28.         "max": 50
  29.     },
  30.     "factors": [
  31.         {
  32.             "type": "医疗卫生设施",
  33.             "condition": "lt",
  34.             "value": "500"
  35.         },
  36.         {
  37.             "type": "永久基本农田",
  38.             "condition": "not_intersect"
  39.         },
  40.         {
  41.             "type": "火葬场",
  42.             "condition": "gt",
  43.             "value": "1000"
  44.         },
  45. {
  46.             "type": "幼儿园服务半径",
  47.             "condition": "lt",
  48.             "value": "1000"
  49.         },
  50. {
  51.             "type": "小学服务半径",
  52.             "condition": "lt",
  53.             "value": "1000"
  54.         },
  55.     ]
  56. }
  57. json中"condition"的值为"gt"、"lt"、"get"、"let"、"between","not_intersect"、"intersect"、"not_contain"、"contain"、"between"
  58. """
  59. sys_question = """请扮演问答工具,对用户输入信息进行回答,请严格以markdown格式输出并保障寄送格式正确无误"""
  60. # 连接数据库
  61. conn = psycopg2.connect(
  62. dbname="real3d",
  63. user="postgres",
  64. password="postgis",
  65. # host="192.168.100.30",
  66. host="192.168.60.2",
  67. port="5432"
  68. )
  69. # 清除聊天记录
  70. def clear_chat_history():
  71. global chat_history
  72. chat_history = ""
  73. return chat_history
  74. def create_chat(msg,type):
  75. # msg = data['msg']
  76. # type = data['type']
  77. if type == 'selectLand':
  78. #同音字替换
  79. msg = replace_word(msg, target_word)
  80. words_to_replace1 = ["爆破", "爆坡","鲍坡"]
  81. for word in words_to_replace1:
  82. msg = msg.replace(word, "抱坡")
  83. print(msg)
  84. # 调用大模型解析
  85. # 这里调用大模型,并返回解析结果
  86. res = update_chat_history(msg)
  87. #未找到相关数据提示
  88. prompt = "根据提供的信息,用户的表述不够清晰明确,请重新描述您的需求。"
  89. addtress = ['抱坡区', '天涯区', '崖州区', '海棠区', '吉阳区']
  90. land = ['园地', '耕地', '林地', '草地', '湿地', '公共卫生用地', '老年人社会福利用地', '儿童社会福利用地', '残疾人社会福利用地', '其他社会福利用地', '零售商业用地', '批发市场用地', '餐饮用地', '旅馆用地', '公用设施营业网点用地', '娱乐用地', '康体用地', '一类工业用地', '二类工业用地', '广播电视设施用地', '环卫用地', '消防用地', '干渠', '水工设施用地', '其他公用设施用地', '公园绿地', '防护绿地', '广场用地', '军事设施用地', '使领馆用地', '宗教用地', '文物古迹用地', '监教场所用地', '殡葬用地', '其他特殊用地', '河流水面', '湖泊水面', '水库水面', '坑塘水面', '沟渠', '冰川及常年积雪', '渔业基础设施用海', '增养殖用海', '捕捞海域', '工业用海', '盐田用海', '固体矿产用海', '油气用海', '可再生能源用海', '海底电缆管道用海', '港口用海', '农业设施建设用地', '工矿用地', '畜禽养殖设施建设用地', '水产养殖设施建设用地', '城镇住宅用地', '特殊用地', '居住用地', '绿地与开敞空间用地', '水田', '水浇地', '旱地', '果园', '茶园', '橡胶园', '其他园地', '乔木林地', '竹林地', '城镇社区服务设施用地', '农村宅基地', '农村社区服务设施用地', '机关团体用地', '科研用地', '文化用地', '教育用地', '体育用地', '医疗卫生用地', '社会福利用地', '商业用地', '商务金融用地', '二类农村宅基地', '图书与展览用地',
  91. '文化活动用地', '高等教育用地', '中等职业教育用地', '体育训练用地', '其他交通设施用地', '供水用地', '排水用地', '供电用地', '供燃气用地', '供热用地', '通信用地', '邮政用地', '医院用地', '基层医疗卫生设施用地', '田间道', '盐碱地', '沙地', '裸土地', '裸岩石砾地', '村道用地', '村庄内部道路用地', '公共管理与公共服务用地', '仓储用地', '交通运输用地', '公用设施用地', '交通运输用海', '航运用海', '路桥隧道用海', '风景旅游用海', '文体休闲娱乐用海', '军事用海', '其他特殊用海', '空闲地', '田坎', '港口码头用地', '管道运输用地', '城市轨道交通用地', '城镇道路用地', '交通场站用地', '一类城镇住宅用地', '二类城镇住宅用地', '三类城镇住宅用地', '一类农村宅基地', '商业服务业用地', '三类工业用地', '一类物流仓储用地', '二类物流仓储用地', '三类物流仓储用地', '盐田', '对外交通场站用地', '公共交通场站用地', '社会停车场用地', '中小学用地', '幼儿园用地', '其他教育用地', '体育场馆用地', '灌木林地', '其他林地', '天然牧草地', '人工牧草地', '其他草地', '森林沼泽', '灌丛沼泽', '沼泽草地', '其他沼泽地', '沿海滩涂', '内陆滩涂', '红树林地', '乡村道路用地', '种植设施建设用地', '娱乐康体用地', '其他商业服务业用地', '工业用地', '采矿用地', '物流仓储用地', '储备库用地', '铁路用地', '公路用地', '机场用地']
  92. json_res = res.replace("json", "")
  93. json_res = json_res.replace("```", "")
  94. if json_res != "未找到相关数据":
  95. try:
  96. json_res = json.loads(json_res)
  97. districtName = json_res["districtName"]
  98. landType = json_res["landType"]
  99. # if landType != "未找到相关数据" and landType != "" and districtName != "未找到相关数据"and districtName != "":
  100. if landType in land and districtName in addtress:
  101. json_res = jsonResToDict(json_res)
  102. # print(json_res)
  103. else:
  104. json_res = prompt
  105. json_res = res_error(json_res, "selectLand","error")
  106. except:
  107. json_res = prompt
  108. json_res = res_error(json_res, "selectLand","error")
  109. else:
  110. json_res = prompt
  111. json_res = res_error(json_res, "selectLand","error")
  112. return json_res
  113. elif type == 'answer':
  114. # json_res = route_query(msg)
  115. # json_res = jsonResToDict_questions(json_res)
  116. # print(json_res) # 打印生成的回复
  117. json_res = update_chat_history_simple(msg)
  118. json_res = res_success(json_res, "answer", "success")
  119. print(json_res) # 打印生成的回复
  120. return json_res
  121. # 智能选址
  122. def update_chat_history(user_message):
  123. global chat_history # 使用全局变量以便更新
  124. prompt = chat_history + "\\n用户:" + user_message
  125. # 生成回复,并加入聊天上下文
  126. res = ollama.generate(
  127. model="qwen2.5:7b",
  128. stream=False,
  129. system=sys_xuanzhi,
  130. prompt=prompt,
  131. options={"temperature": 0, "num_ctx": 32000, },
  132. keep_alive=-1
  133. )
  134. # 获取机器人回复
  135. bot_message = res["response"]
  136. # 更新聊天历史
  137. chat_history += "\\n智能助手:" + bot_message
  138. # 返回机器人的回复
  139. return bot_message
  140. # 将大模型解析的结果转换为选址需要的数据格式
  141. def jsonResToDict(json_res):
  142. # 1.查询选址范围信息
  143. districtName = json_res["districtName"]
  144. ewkt = getAiDistrict(districtName)
  145. # 2.保存选址范围信息
  146. geomId = saveGeom(ewkt)
  147. # 3.获取用地类型信息
  148. landType = json_res["landType"]
  149. landType = getLandType(landType, "YDYHFLDM")
  150. # 4.获取模板信息
  151. factorTemplates = getTemplateByCode(landType)
  152. # TODO 以哪个因子列表为准,模版和因子个数怎么匹配
  153. now = datetime.datetime.now()
  154. formatted_time = now.strftime("%Y%m%d%H%M%S")
  155. res = {
  156. "xzmj": 1500,
  157. "xmmc": "规划选址项目_"+formatted_time,
  158. "jsdw": "建设单位",
  159. "ydxz_bsm": landType,
  160. "ydmjbegin": json_res["area"]["min"],
  161. "ydmjend": json_res["area"]["max"],
  162. "geomId": geomId,
  163. "yxyz": [],
  164. # TODO: 循环遍历
  165. # "yxyz": [
  166. # {
  167. # "id": "259e5bbaab434dbfb9c679bd44d4bfa4",
  168. # "name": "幼儿园服务半径",
  169. # "bsm": "TB_YEY",
  170. # "conditionInfo": {
  171. # "spatial_type": "distance",
  172. # "default": "lt",
  173. # "hasValue": true,
  174. # "defaultValue": "300",
  175. # "unit": "米",
  176. # "clip": false
  177. # }
  178. # }
  179. # ],
  180. # "useMultiple": json_res["useMultiple"],
  181. "useLandType": True,
  182. # "multipleDistance": json_res["multipleDistance"]
  183. }
  184. # 循环遍历输入因子
  185. factors = json_res["factors"]
  186. input_factors = {}
  187. for factor in factors:
  188. factorInfo = getFactorByName(factor["type"])
  189. if factorInfo == None:
  190. continue
  191. factorId = factorInfo["id"]
  192. factorBsm = factorInfo["bsm"]
  193. conditionInfo = factorInfo["condition_info"]
  194. conditionObj = json.loads(conditionInfo)
  195. defaultValue = '0'
  196. default = 'lt'
  197. if "value" in factor:
  198. defaultValue = str(factor["value"])
  199. if "condition" in factor:
  200. default = factor["condition"]
  201. # if defaultValue == '':
  202. # defaultValue = '0'
  203. factor_info = {
  204. "id": factorId,
  205. "name": factor["type"],
  206. "bsm": factorBsm,
  207. "conditionInfo": {
  208. "spatial_type": conditionObj["spatial_type"],
  209. "default": default,
  210. "hasValue": conditionObj["hasValue"],
  211. "defaultValue": defaultValue,
  212. "unit": conditionObj["unit"],
  213. "clip": conditionObj["clip"]
  214. }
  215. }
  216. input_factors[factor_info["id"]] = factor_info
  217. # 循环遍历模板
  218. # 记录已经添加的因子 ID
  219. added_factor_ids = set()
  220. # 首先处理模板
  221. for factorTemplate in factorTemplates:
  222. factorId = factorTemplate["id"]
  223. factorTemplate["conditionInfo"] = json.loads(
  224. factorTemplate["conditionInfo"])
  225. res["yxyz"].append(factorTemplate)
  226. added_factor_ids.add(factorId) # 记录已添加的因子 ID
  227. # 然后检查 input_factors 并添加未在模板中的因子
  228. for factor_id, factor_info in input_factors.items():
  229. if factor_id not in added_factor_ids:
  230. res["yxyz"].append(factor_info)
  231. resObj = {}
  232. resObj["data"] = res
  233. resObj["code"] = 200
  234. resObj["type"] = "selectLand"
  235. return resObj
  236. # 获取因子信息
  237. def getFactorByName(name):
  238. with conn.cursor(cursor_factory=DictCursor) as cur:
  239. sql = "SELECT * FROM base.t_fzss_fzxz_factor WHERE name = %s"
  240. complete_sql = cur.mogrify(sql, (name,)).decode('utf-8')
  241. logger.info(f"Executing SQL: {complete_sql}")
  242. cur.execute(sql, (name,))
  243. res = cur.fetchone()
  244. return res
  245. # 获取选址范围信息
  246. def getAiDistrict(name):
  247. with conn.cursor(cursor_factory=DictCursor) as cur:
  248. sql = "SELECT public.st_asewkt(geom) as geom FROM base.t_fzss_fzxz_ai_district WHERE name = %s"
  249. complete_sql = cur.mogrify(sql, (name,)).decode('utf-8')
  250. logger.info(f"Executing SQL: {complete_sql}")
  251. cur.execute(sql, (name,))
  252. res = cur.fetchone()
  253. return res["geom"]
  254. # 保存选址范围信息
  255. def saveGeom(ewkt):
  256. new_uuid = str(uuid.uuid4()) # 生成一个新的 UUID
  257. from_type = 3
  258. with conn.cursor() as cur:
  259. sql = "INSERT INTO base.t_fzss_zhxz_file(id,geom,from_type,create_time,area) VALUES (%s,public.st_geomfromewkt(%s),%s,now(),public.st_area(public.st_geomfromewkt(%s)::public.geography))"
  260. complete_sql = cur.mogrify(
  261. sql, (new_uuid, ewkt, from_type, ewkt)).decode('utf-8')
  262. logger.info(f"Executing SQL: {complete_sql}")
  263. cur.execute(sql, (new_uuid, ewkt, from_type, ewkt))
  264. conn.commit()
  265. return new_uuid
  266. # 获取用地类型信息
  267. def getLandType(landName, fzbs):
  268. with conn.cursor(cursor_factory=DictCursor) as cur:
  269. sql = "SELECT dm,mc,fzbs FROM base.t_fzss_fzxz_dict WHERE mc = %s and fzbs=%s"
  270. complete_sql = cur.mogrify(sql, (landName, fzbs)).decode('utf-8')
  271. logger.info(f"Executing SQL: {complete_sql}")
  272. cur.execute(sql, (landName, fzbs))
  273. res = cur.fetchone()
  274. return res["dm"]
  275. # 获取内置模板信息
  276. def getTemplateByCode(code):
  277. with conn.cursor(cursor_factory=DictCursor) as cur:
  278. sql = 'SELECT factor_id as id,factor_name as name,factor_bsm as bsm,condition_info as "conditionInfo" FROM base.t_fzss_fzxz_factor_temp WHERE land_type_code = %s'
  279. complete_sql = cur.mogrify(sql, (code,)).decode('utf-8')
  280. logger.info(f"Executing SQL: {complete_sql}")
  281. cur.execute(sql, (code,))
  282. res = cur.fetchall()
  283. # 将查询结果转换为字典列表
  284. result_list = [dict(row) for row in res]
  285. return result_list
  286. # 简单知识问答,未关联本地知识库
  287. def update_chat_history_simple(user_message):
  288. global chat_history # 使用全局变量以便更新
  289. prompt = chat_history + "\\n用户:" + user_message
  290. # 生成回复,并加入聊天上下文
  291. res = ollama.generate(
  292. model="qwen2.5:7b",
  293. stream=False,
  294. system=sys_question,
  295. prompt=prompt,
  296. options={"temperature": 0, "num_ctx": 32000, },
  297. keep_alive=-1
  298. )
  299. # 获取机器人回复
  300. bot_message = res["response"]
  301. # 更新聊天历史
  302. chat_history += "\\n智能助手:" + bot_message
  303. # 返回机器人的回复
  304. return bot_message
  305. def route_query(msg):
  306. response = query(msg)
  307. # print(response)
  308. # if response:
  309. # resObj = {}
  310. # resObj["data"] = response
  311. # resObj["code"] = 200
  312. # resObj["type"] = "answer"
  313. # return resObj
  314. # return {"error": "Something went wrong"}, 400
  315. return response