ai_service/serve.py
2025-05-14 12:15:20 +08:00

74 lines
2.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# server.py
from flask import Flask, request, jsonify
from flask_cors import CORS
import requests # 用于发起HTTP请求(比如调用外部接口)
import json
app = Flask(__name__)
CORS(app) # 如果前后端分离需要跨域启用CORS
@app.route('/generate', methods=['POST'])
def generate():
try:
# 1. 从请求体中获取参数
data = request.json
prompt = data.get('prompt', '')
width = data.get('width', 512)
height = data.get('height', 512)
print(f'收到参数: prompt={prompt}, width={width}, height={height}')
# 2. 调用大模型API或其他逻辑生成图片
images = generate_images_coze(prompt, width, height)
# 返回 JSON 格式数据给前端
return jsonify({'images': images})
except Exception as e:
print('图片生成出错:', e)
return jsonify({'error': '图片生成出错'}), 500
def generate_images_coze(prompt, width, height):
print(f'正在根据 "{prompt}" 生成内容 (宽{width},高{height})...')
url = 'https://api.coze.cn/v3/chat'
headers = {
'Authorization': 'Bearer pat_7G46ritHNFFvDnbeIIzXWaoPabf8ocbHsGfnAl20te1dsdHX2aTiRKR0XTLbauHW',
'Content-Type': 'application/json'
}
data = {
"bot_id": "7486021323127980071",
"user_id": "123",
"stream": True,
"auto_save_history": True,
"additional_messages": [
{
"role": "user",
"content": prompt,
"content_type": "text"
}
]
}
try:
resp = requests.post(url, headers=headers, data=json.dumps(data))
resp.raise_for_status() # 如果响应非200会抛异常
result_text = resp.text
print('Coze API 返回结果:', result_text)
# 假设并没有真正返回图片链接,就先返回一个测试
return [f"大模型返回的内容:{result_text}"]
except Exception as e:
print('调用 Coze API 失败:', e)
# 出错的话就返回空列表
return []
if __name__ == '__main__':
app.run(host='0.0.0.0', port=9000, debug=False)