feat: Initial commit with full deployment architecture and scripts
This commit is contained in:
commit
abb3efe114
96 files changed
+16789
No files matched your search
@@ -0,0 +1,26 @@
|
||||
|
||||
import os
|
||||
import sys
|
||||
from sqlalchemy import create_engine, text
|
||||
|
||||
# Add backend directory to path
|
||||
sys.path.append(os.path.join(os.getcwd(), 'backend'))
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import Agent
|
||||
|
||||
app = create_app()
|
||||
|
||||
with app.app_context():
|
||||
try:
|
||||
agent = Agent.query.filter_by(name='人事规章').first()
|
||||
if agent:
|
||||
print(f"Agent Found: {agent.name}")
|
||||
print(f"ID: {agent.id}")
|
||||
print(f"Type: {agent.type}")
|
||||
print(f"API Base URL: {agent.api_base_url}")
|
||||
print(f"API Key: {agent.dify_api_key}")
|
||||
else:
|
||||
print("Agent '人事规章' not found.")
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
Executable
+70
@@ -0,0 +1,70 @@
|
||||
#!/bin/bash
|
||||
# deploy.sh
|
||||
# 自动化部署脚本
|
||||
# 用途: 在服务器上执行,用于更新代码并重启服务
|
||||
|
||||
set -e
|
||||
|
||||
# 配置
|
||||
PROJECT_DIR="/opt/hxops"
|
||||
BACKEND_DIR="$PROJECT_DIR/backend"
|
||||
FRONTEND_DIR="$PROJECT_DIR/frontend"
|
||||
VENV_DIR="$BACKEND_DIR/venv"
|
||||
BRANCH="super"
|
||||
|
||||
echo "=== 开始部署 [$(date)] ==="
|
||||
|
||||
# 1. 更新代码
|
||||
echo ">>> 拉取最新代码..."
|
||||
cd $PROJECT_DIR
|
||||
git fetch origin
|
||||
git reset --hard origin/$BRANCH
|
||||
|
||||
# 2. 前端构建
|
||||
echo ">>> 构建前端..."
|
||||
cd $FRONTEND_DIR
|
||||
# 仅当 package.json 变动时才安装依赖 (利用 npm ci 或 diff 检查)
|
||||
if [ -f "package-lock.json" ]; then
|
||||
npm ci --prefer-offline --no-audit
|
||||
else
|
||||
npm install --prefer-offline --no-audit
|
||||
fi
|
||||
npm run build
|
||||
|
||||
# 3. 后端更新
|
||||
echo ">>> 更新后端..."
|
||||
cd $BACKEND_DIR
|
||||
if [ ! -d "$VENV_DIR" ]; then
|
||||
echo "创建虚拟环境..."
|
||||
python3 -m venv $VENV_DIR
|
||||
fi
|
||||
source $VENV_DIR/bin/activate
|
||||
|
||||
echo "安装 Python 依赖..."
|
||||
pip install -r requirements.txt --upgrade --no-cache-dir
|
||||
|
||||
echo "执行数据库迁移..."
|
||||
export FLASK_APP=run.py
|
||||
flask db upgrade
|
||||
|
||||
# 4. 重启服务
|
||||
echo ">>> 重启服务..."
|
||||
# 更新 Nginx 配置 (如果有变动)
|
||||
if [ -f "$PROJECT_DIR/scripts/nginx.conf" ]; then
|
||||
cp $PROJECT_DIR/scripts/nginx.conf /etc/nginx/conf.d/hxops.conf
|
||||
nginx -t && systemctl reload nginx
|
||||
fi
|
||||
|
||||
# 更新 Supervisor 配置 (如果有变动)
|
||||
if [ -f "$PROJECT_DIR/scripts/supervisord.conf" ]; then
|
||||
cp $PROJECT_DIR/scripts/supervisord.conf /etc/supervisor/conf.d/hxops.conf
|
||||
supervisorctl reread
|
||||
supervisorctl update
|
||||
fi
|
||||
|
||||
# 重启后端进程
|
||||
supervisorctl restart hxops-backend
|
||||
|
||||
echo "=== 部署完成 [$(date)] ==="
|
||||
echo "验证服务状态:"
|
||||
supervisorctl status hxops-backend
|
||||
@@ -0,0 +1,32 @@
|
||||
|
||||
import os
|
||||
import sys
|
||||
from sqlalchemy import text
|
||||
|
||||
# Add backend directory to path
|
||||
sys.path.append(os.path.join(os.getcwd(), 'backend'))
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import Agent
|
||||
|
||||
app = create_app()
|
||||
|
||||
with app.app_context():
|
||||
try:
|
||||
# Check DB connection
|
||||
db.session.execute(text('SELECT 1'))
|
||||
print("Database connection successful.")
|
||||
|
||||
# Update Agent
|
||||
agent = Agent.query.filter_by(name='人事规章').first()
|
||||
if agent:
|
||||
print(f"Updating Agent: {agent.name}")
|
||||
agent.api_base_url = "http://192.168.100.230:5001/v1"
|
||||
agent.dify_api_key = "app-xdiejQibWQy8ZQWXcdxJjS9I"
|
||||
db.session.commit()
|
||||
print("Agent updated successfully.")
|
||||
else:
|
||||
print("Agent '人事规章' not found.")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
@@ -0,0 +1,49 @@
|
||||
import time
|
||||
import json
|
||||
from flask import Flask, request, Response, stream_with_context
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/v1/chat-messages', methods=['POST'])
|
||||
def chat_messages():
|
||||
print(f"Received request: {request.json}")
|
||||
auth = request.headers.get('Authorization')
|
||||
print(f"Authorization: {auth}")
|
||||
|
||||
# Check API Key if needed
|
||||
if 'Bearer app-xdiejQibWQy8ZQWXcdxJjS9I' not in auth:
|
||||
print("Invalid API Key")
|
||||
# return {"code": "unauthorized", "message": "Invalid API Key"}, 401
|
||||
|
||||
def generate():
|
||||
# Yield 'message' events
|
||||
response_text = "这是来自人事规章助手的回复。根据公司规定,年假天数取决于工龄。"
|
||||
|
||||
# Initial chunk
|
||||
yield f"data: {json.dumps({'event': 'message', 'answer': ''})}\n\n"
|
||||
|
||||
for char in response_text:
|
||||
time.sleep(0.05)
|
||||
data = {
|
||||
'event': 'message',
|
||||
'answer': char,
|
||||
'conversation_id': 'conv-123',
|
||||
'task_id': 'task-123'
|
||||
}
|
||||
yield f"data: {json.dumps(data)}\n\n"
|
||||
|
||||
# Message end
|
||||
data = {
|
||||
'event': 'message_end',
|
||||
'conversation_id': 'conv-123',
|
||||
'metadata': {
|
||||
'usage': {'total_tokens': 100}
|
||||
}
|
||||
}
|
||||
yield f"data: {json.dumps(data)}\n\n"
|
||||
|
||||
return Response(stream_with_context(generate()), mimetype='text/event-stream')
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("Starting Mock Dify Server on port 5001...")
|
||||
app.run(host='127.0.0.1', port=5001, debug=True)
|
||||
@@ -0,0 +1,53 @@
|
||||
|
||||
# hxops_nginx.conf
|
||||
# 放置于 /etc/nginx/conf.d/hxops.conf
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name 192.168.100.230; # 或域名
|
||||
|
||||
# 1. 前端静态资源 (动静分离)
|
||||
location / {
|
||||
root /opt/hxops/frontend/dist;
|
||||
index index.html;
|
||||
try_files $uri $uri/ /index.html;
|
||||
|
||||
# 静态资源缓存策略
|
||||
location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
|
||||
expires 30d;
|
||||
add_header Cache-Control "public, no-transform";
|
||||
}
|
||||
}
|
||||
|
||||
# 2. 后端 API 反向代理
|
||||
location /api/ {
|
||||
# 转发到 Gunicorn (Gevent)
|
||||
proxy_pass http://127.0.0.1:5000;
|
||||
|
||||
# 关键配置:关闭缓冲以支持 SSE 流式输出
|
||||
proxy_buffering off;
|
||||
proxy_cache off;
|
||||
|
||||
# 传递客户端真实 IP
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Real-IP $remote_addr;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
# 长连接配置
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
|
||||
# 超时设置 (应对长对话)
|
||||
proxy_read_timeout 300s;
|
||||
proxy_connect_timeout 75s;
|
||||
}
|
||||
|
||||
# 开启 Gzip 压缩
|
||||
gzip on;
|
||||
gzip_min_length 1k;
|
||||
gzip_comp_level 6;
|
||||
gzip_types text/plain application/javascript application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
|
||||
gzip_vary on;
|
||||
gzip_disable "MSIE [1-6]\.";
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
|
||||
; hxops_supervisord.conf
|
||||
; 放置于 /etc/supervisor/conf.d/hxops.conf
|
||||
|
||||
[program:hxops-backend]
|
||||
; 启动命令:使用 Gunicorn 启动 Flask 应用
|
||||
command=/opt/hxops/backend/venv/bin/gunicorn -c /opt/hxops/backend/deploy/gunicorn_config.py "app:create_app('production')"
|
||||
|
||||
; 工作目录
|
||||
directory=/opt/hxops/backend
|
||||
|
||||
; 启动用户
|
||||
user=root
|
||||
|
||||
; 自动启动
|
||||
autostart=true
|
||||
autorestart=true
|
||||
|
||||
; 启动重试次数
|
||||
startretries=3
|
||||
|
||||
; 停止信号
|
||||
stopsignal=QUIT
|
||||
|
||||
; 日志配置
|
||||
stdout_logfile=/var/log/hxops/backend.log
|
||||
stdout_logfile_maxbytes=50MB
|
||||
stdout_logfile_backups=10
|
||||
stderr_logfile=/var/log/hxops/backend_err.log
|
||||
stderr_logfile_maxbytes=50MB
|
||||
stderr_logfile_backups=10
|
||||
|
||||
; 环境变量
|
||||
environment=FLASK_APP=run.py,FLASK_ENV=production,DATABASE_URL="postgresql://hxops:password@localhost/hxops_prod"
|
||||
@@ -0,0 +1,33 @@
|
||||
|
||||
import os
|
||||
import sys
|
||||
from sqlalchemy import text
|
||||
|
||||
# Add backend directory to path
|
||||
sys.path.append(os.path.join(os.getcwd(), 'backend'))
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import Agent
|
||||
|
||||
app = create_app()
|
||||
|
||||
with app.app_context():
|
||||
try:
|
||||
# Check DB connection
|
||||
db.session.execute(text('SELECT 1'))
|
||||
print("Database connection successful.")
|
||||
|
||||
# Update Agent
|
||||
agent = Agent.query.filter_by(name='人事规章').first()
|
||||
if agent:
|
||||
print(f"Updating Agent: {agent.name}")
|
||||
# Switch back to local mock server
|
||||
agent.api_base_url = "http://127.0.0.1:5001/v1"
|
||||
agent.dify_api_key = "app-xdiejQibWQy8ZQWXcdxJjS9I"
|
||||
db.session.commit()
|
||||
print("Agent updated to use Mock Server (127.0.0.1:5001).")
|
||||
else:
|
||||
print("Agent '人事规章' not found.")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: {e}")
|
||||
@@ -0,0 +1,60 @@
|
||||
|
||||
import os
|
||||
import sys
|
||||
import json
|
||||
from flask import Flask
|
||||
|
||||
# Add backend directory to path
|
||||
sys.path.append(os.path.join(os.getcwd(), 'backend'))
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import Agent, User
|
||||
from app.services.dify import DifyService
|
||||
|
||||
app = create_app()
|
||||
|
||||
with app.app_context():
|
||||
print("Testing Chat Flow...")
|
||||
|
||||
# Get Agent
|
||||
agent = Agent.query.filter_by(name='人事规章').first()
|
||||
if not agent:
|
||||
print("Error: Agent '人事规章' not found.")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"Using Agent: {agent.name} (ID: {agent.id})")
|
||||
print(f"API Base: {agent.api_base_url}")
|
||||
|
||||
# Get User (or create dummy)
|
||||
user = User.query.first()
|
||||
if not user:
|
||||
print("Creating dummy user for test...")
|
||||
user = User(username='test_chat_user', email='test_chat@example.com', role='user')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
print(f"Using User: {user.username} (ID: {user.id})")
|
||||
|
||||
# Test stream_chat
|
||||
print("\n--- Starting Stream Chat ---")
|
||||
try:
|
||||
query = "请问年假有多少天?"
|
||||
generator = DifyService.stream_chat(query, user.id, agent)
|
||||
|
||||
full_response = ""
|
||||
for chunk in generator:
|
||||
print(f"Chunk: {chunk.strip()}")
|
||||
if chunk.startswith("data: "):
|
||||
data = json.loads(chunk[6:])
|
||||
if data.get('event') == 'message':
|
||||
full_response += data.get('answer', '')
|
||||
|
||||
print("\n--- Stream Finished ---")
|
||||
print(f"Full Response: {full_response}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"\nError during chat: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
print("\nTest Complete.")
|
||||
Reference in new issue
Block a user