明白!我帮你写一个更完整的 Flask 服务端示例,集成调用大模型接口(用模拟的 Dify/DeepSeek API),并生成格式化的 Word 文档,支持本地保存和下载。
完整示例:Flask + Dify/DeepSeek 模拟接口 + Word 文件生成
from flask import Flask, request, send_from_directory, jsonify
from docx import Document
import os
import time
import uuid
import requests
app = Flask(__name__)
# 文件保存目录
SAVE_FOLDER = './generated_docs'
os.makedirs(SAVE_FOLDER, exist_ok=True)
# 模拟调用大模型接口函数(请替换为你实际的 Dify/DeepSeek API)
def query_dify_deepseek(question: str) -> str:
# 这里演示使用伪API,实际要替换成你的接口
# 示例模拟返回
# 你也可以用 requests.post 调用真实接口
dummy_answer = f"这是针对问题【{question}】的大模型模拟回答内容。"
return dummy_answer
@app.route('/ask', methods=['POST'])
def ask():
data = request.json
question = data.get('question')
if not question:
return jsonify({"error": "问题不能为空"}), 400
# 调用大模型接口
answer = query_dify_deepseek(question)
# 生成 Word 文档
doc = Document()
doc.add_heading("问题", level=1)
doc.add_paragraph(question)
doc.add_heading("回答", level=1)
doc.add_paragraph(answer)
# 生成唯一文件名
filename = f"answer_{int(time.time())}_{uuid.uuid4().hex[:8]}.docx"
filepath = os.path.join(SAVE_FOLDER, filename)
doc.save(filepath)
return jsonify({"filename": filename, "message": "回答生成成功"})
@app.route('/download/<filename>', methods=['GET'])
def download(filename):
try:
return send_from_directory(SAVE_FOLDER, filename, as_attachment=True)
except Exception as e:
return jsonify({"error": "文件不存在或无法访问", "details": str(e)}), 404
if __name__ == '__main__':
app.run(debug=True, port=5000)
使用方法
-
启动服务:
python your_flask_file.py
-
发送请求(示例用 curl):
curl -X POST http://127.0.0.1:5000/ask -H "Content-Type: application/json" -d '{"question":"什么是人工智能?"}'
-
返回示例:
{
"filename": "answer_1681234567_a1b2c3d4.docx",
"message": "回答生成成功"
}
-
下载文件:
浏览器访问
http://127.0.0.1:5000/download/answer_1681234567_a1b2c3d4.docx
即可下载 Word 文件。
下一步
-
你可以把
query_dify_deepseek
替换为真实接口调用逻辑,传入 API Key,调用大模型生成回答。 -
需要生成更复杂 Word 文档格式,如表格、图片等也可以告诉我帮你写。
-
需要前端页面调用和展示,也可以帮你写一个简易的 Web UI。
需要我帮你写具体的 Dify/DeepSeek API 调用示例吗?或者帮你做一个简单的网页前端吗?