import json import ollama PROMPT_TEMPLATE = """你是一个专业的飞书办公助手。 你的任务是根据用户的输入,判断他们的意图是找你要文件,还是日常聊天,并必须且只能输出严格的 JSON 格式反馈!绝不允许输出其他废话!!! 如果用户明确提到要发某个资料(比如报价单、宣传册、文档、介绍等),请提取关键词并返回: {"intent": "send_file", "keyword": "具体文件的关键词", "reply_text": "好的,正在为您查找相关文件..."} 如果用户只是一般聊天或找你帮忙其他事(不是要具体资料): {"intent": "reply", "reply_text": "你想对用户说的话"} 示例对话 1: 用户输入:给我发一个元核服务器报价单 助手返回:{"intent": "send_file", "keyword": "服务器报价单", "reply_text": "收到,我在资料室里找找!"} 示例对话 2: 用户输入:在吗,你是谁 助手返回:{"intent": "reply", "reply_text": "您好,我是您的专属智能助手,可以帮您检索和发送文件,请问有什么可以效劳?"} 现在请处理真正的用户输入: 用户输入:{user_input} 助手返回:""" def process_message(user_input: str) -> dict: """ 通过 Ollama 本地调用 Gemma 4B 模型。 分析用户的语义意图,并返回带有 JSON 字段的字典。 """ try: # 使用 gemma:4b 进行文本生成 response = ollama.generate( model='gemma:4b', prompt=PROMPT_TEMPLATE.replace("{user_input}", user_input), # 可根据需要修改参数,这里通常不需要特殊处理 options={'temperature': 0.1} # 调低温度确保格式稳定 ) text = response.get('response', '').strip() # 清理由于模型自我发挥生成的 markdown 代码块符号 if text.startswith("```json"): text = text[7:] elif text.startswith("```"): text = text[3:] if text.endswith("```"): text = text[:-3] text = text.strip() # 解析返回的 JSON data = json.loads(text) return data except json.JSONDecodeError as decode_err: print(f"LLM 结果不是标准的 JSON: {text}. 错误信息: {decode_err}") # 保底处理 return {"intent": "reply", "reply_text": "不好意思,刚没听清您的问题,能再说一遍吗?"} except Exception as e: print(f"Agent 调用出现错误: {e}") return {"intent": "reply", "reply_text": "不好意思,我现在有点状况,暂时无法理解您的意思(可能是 Ollama 服务没开或者模型没加载好)。"}