260323 function add report chat and front
This commit is contained in:
1 parent
605317c2b2
commit
5e8ea03b6c
16 files changed
+2351
-100
No files matched your search
@@ -7,11 +7,13 @@ backend/app/api/admin.py
|
||||
from flask import Blueprint, request, jsonify
|
||||
from app.models import Agent, User, PermissionRequest, ChatLog, Feedback, Department, UserFavoriteAgent, UserDefaultAgent, QuickQuestion, UserHomepageConfig
|
||||
from app.decorators import require_admin
|
||||
from app.config import Config
|
||||
from app import db
|
||||
from sqlalchemy import func, desc, inspect
|
||||
from datetime import datetime
|
||||
import csv
|
||||
import io
|
||||
import requests
|
||||
|
||||
admin_bp = Blueprint('admin', __name__)
|
||||
|
||||
@@ -165,6 +167,138 @@ def delete_agent(id):
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/test', methods=['POST'])
|
||||
@require_admin
|
||||
def test_agent(id):
|
||||
"""
|
||||
测试应用连通性与基础响应质量。
|
||||
返回:请求地址、输出信息、结果分析。
|
||||
若测试通过,则自动将应用状态置为启用。
|
||||
"""
|
||||
agent = db.session.get(Agent, id)
|
||||
if not agent:
|
||||
return jsonify({'error': 'Not found'}), 404
|
||||
|
||||
tested_at = datetime.utcnow().isoformat()
|
||||
|
||||
if agent.type == 'iframe':
|
||||
iframe_url = (agent.extra_config or {}).get('iframe_url')
|
||||
if not iframe_url:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing iframe_url in extra_config.',
|
||||
'analysis': '测试失败:未配置 iframe URL。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at
|
||||
}), 400
|
||||
try:
|
||||
resp = requests.get(iframe_url, timeout=(5, 15), allow_redirects=True)
|
||||
success = 200 <= resp.status_code < 400
|
||||
if success and not agent.is_active:
|
||||
agent.is_active = True
|
||||
db.session.commit()
|
||||
return jsonify({
|
||||
'success': success,
|
||||
'request_url': iframe_url,
|
||||
'output_info': f'HTTP {resp.status_code}; response length={len(resp.text)}',
|
||||
'analysis': '测试通过:iframe 地址可访问。' if success else '测试失败:iframe 地址不可访问或返回异常状态。',
|
||||
'http_status': resp.status_code,
|
||||
'tested_at': tested_at
|
||||
}), 200
|
||||
except requests.RequestException as e:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'request_url': iframe_url,
|
||||
'output_info': str(e),
|
||||
'analysis': '测试失败:请求 iframe 地址异常。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at
|
||||
}), 200
|
||||
|
||||
if not agent.dify_api_key:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing dify_api_key.',
|
||||
'analysis': '测试失败:未配置 API Key。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at
|
||||
}), 400
|
||||
|
||||
base_url = (agent.api_base_url or Config.DIFY_API_BASE or '').rstrip('/')
|
||||
if not base_url:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'request_url': '',
|
||||
'output_info': 'Missing api_base_url.',
|
||||
'analysis': '测试失败:未配置 API Base URL。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at
|
||||
}), 400
|
||||
|
||||
request_url = f'{base_url}/chat-messages'
|
||||
payload = {
|
||||
'inputs': {},
|
||||
'query': '系统连通性测试,请简短回复OK。',
|
||||
'response_mode': 'blocking',
|
||||
'conversation_id': '',
|
||||
'user': 'admin_test'
|
||||
}
|
||||
headers = {
|
||||
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
|
||||
try:
|
||||
resp = requests.post(request_url, headers=headers, json=payload, timeout=(5, 25))
|
||||
raw_text = (resp.text or '')[:4000]
|
||||
output_info = raw_text
|
||||
success = False
|
||||
analysis = f'测试失败:HTTP {resp.status_code}。'
|
||||
|
||||
try:
|
||||
data = resp.json()
|
||||
answer = data.get('answer') if isinstance(data, dict) else None
|
||||
if answer:
|
||||
output_info = str(answer)[:4000]
|
||||
if resp.ok and isinstance(answer, str) and answer.strip():
|
||||
success = True
|
||||
analysis = '测试通过:接口连通正常,已成功返回回答。'
|
||||
elif resp.ok:
|
||||
analysis = '测试未通过:接口可访问,但未返回有效回答。'
|
||||
else:
|
||||
message = data.get('message') if isinstance(data, dict) else None
|
||||
if message:
|
||||
output_info = str(message)[:4000]
|
||||
except ValueError:
|
||||
if resp.ok and raw_text.strip():
|
||||
success = True
|
||||
analysis = '测试通过:接口连通正常,返回了文本内容。'
|
||||
|
||||
if success and not agent.is_active:
|
||||
agent.is_active = True
|
||||
db.session.commit()
|
||||
|
||||
return jsonify({
|
||||
'success': success,
|
||||
'request_url': request_url,
|
||||
'output_info': output_info,
|
||||
'analysis': analysis,
|
||||
'http_status': resp.status_code,
|
||||
'tested_at': tested_at
|
||||
}), 200
|
||||
except requests.RequestException as e:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'request_url': request_url,
|
||||
'output_info': str(e),
|
||||
'analysis': '测试失败:请求异常(网络、超时或认证问题)。',
|
||||
'http_status': 0,
|
||||
'tested_at': tested_at
|
||||
}), 200
|
||||
|
||||
|
||||
@admin_bp.route('/agents/<int:id>/permissions', methods=['POST'])
|
||||
@require_admin
|
||||
def update_agent_permissions(id):
|
||||
@@ -525,3 +659,56 @@ def get_table_data(table):
|
||||
res.append(d)
|
||||
|
||||
return jsonify(res)
|
||||
|
||||
|
||||
@admin_bp.route('/database/chat_logs/batch-delete', methods=['POST'])
|
||||
@require_admin
|
||||
def batch_delete_chat_logs():
|
||||
"""
|
||||
Batch delete chat logs by ids.
|
||||
Only accepts chat_log ids to avoid accidental table-wide deletion.
|
||||
"""
|
||||
data = request.get_json() or {}
|
||||
raw_ids = data.get('ids', [])
|
||||
if not isinstance(raw_ids, list) or not raw_ids:
|
||||
return jsonify({'error': 'ids is required'}), 400
|
||||
|
||||
ids = []
|
||||
for v in raw_ids:
|
||||
try:
|
||||
ids.append(int(v))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
|
||||
if not ids:
|
||||
return jsonify({'error': 'No valid ids'}), 400
|
||||
|
||||
cnt = db.session.query(ChatLog).filter(ChatLog.id.in_(ids)).delete(synchronize_session=False)
|
||||
db.session.commit()
|
||||
return jsonify({'deleted_count': cnt})
|
||||
|
||||
|
||||
@admin_bp.route('/database/<table>/count', methods=['GET'])
|
||||
@require_admin
|
||||
def get_table_count(table):
|
||||
"""
|
||||
Return total row count for admin report tables.
|
||||
"""
|
||||
model_map = {
|
||||
'users': User,
|
||||
'agents': Agent,
|
||||
'chat_logs': ChatLog,
|
||||
'feedbacks': Feedback,
|
||||
'permission_requests': PermissionRequest,
|
||||
'departments': Department,
|
||||
'quick_questions': QuickQuestion,
|
||||
'user_homepage_configs': UserHomepageConfig,
|
||||
'user_favorite_agents': UserFavoriteAgent,
|
||||
'user_default_agents': UserDefaultAgent
|
||||
}
|
||||
model = model_map.get(table)
|
||||
if not model:
|
||||
return jsonify({'error': 'Invalid table'}), 400
|
||||
|
||||
total = db.session.query(func.count(model.id)).scalar()
|
||||
return jsonify({'table': table, 'total': int(total or 0)})
|
||||
@@ -0,0 +1,25 @@
|
||||
from app import create_app, db
|
||||
from app.models import ChatLog, User
|
||||
from sqlalchemy import func
|
||||
|
||||
app = create_app('development')
|
||||
with app.app_context():
|
||||
print('=== 数据库中的用户 ===')
|
||||
users = db.session.query(User).all()
|
||||
for u in users:
|
||||
print(f'id={u.id}, username={u.username}, role={u.role}')
|
||||
|
||||
print()
|
||||
print('=== 各用户对 Agent 3 的会话统计 ===')
|
||||
for uid in [1, 2, 3, 4, 5]:
|
||||
count = db.session.query(func.count(ChatLog.id)).filter(
|
||||
ChatLog.user_id == uid,
|
||||
ChatLog.agent_id == 3
|
||||
).scalar()
|
||||
print(f'user_id={uid}: {count} logs')
|
||||
|
||||
print()
|
||||
print('=== ChatLog 样本 (Agent 3) ===')
|
||||
logs = db.session.query(ChatLog).filter(ChatLog.agent_id == 3).order_by(ChatLog.created_at.desc()).limit(5).all()
|
||||
for log in logs:
|
||||
print(f'user_id={log.user_id}, conv_id={log.conversation_id}, query={log.query[:40]}...')
|
||||
@@ -0,0 +1,129 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
fix_agent_permission.py
|
||||
文件用途:修复 Agent 权限问题
|
||||
关键逻辑:
|
||||
1. 根据 username 或 user_id 获取用户
|
||||
2. 给用户分配指定的 agent 权限
|
||||
3. 支持批量分配和查看当前权限
|
||||
语法实现:使用 SQLAlchemy relationship 操作多对多关联
|
||||
"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import User, Agent
|
||||
|
||||
|
||||
def grant_agent_permission(username=None, user_id=None, agent_ids=None, grant_all=False):
|
||||
"""
|
||||
给用户分配 Agent 权限
|
||||
|
||||
参数:
|
||||
username: 用户名
|
||||
user_id: 用户 ID
|
||||
agent_ids: 要分配的 Agent ID 列表,如 [1, 2, 3]
|
||||
grant_all: 是否授予所有 Agent 的权限
|
||||
"""
|
||||
env = os.getenv('FLASK_ENV', 'production')
|
||||
app = create_app(env)
|
||||
|
||||
with app.app_context():
|
||||
user = None
|
||||
if user_id:
|
||||
user = User.query.get(int(user_id))
|
||||
elif username:
|
||||
user = User.query.filter_by(username=username).first()
|
||||
|
||||
if not user:
|
||||
print(f"❌ 用户不存在: username={username}, user_id={user_id}")
|
||||
return False
|
||||
|
||||
print(f"✅ 找到用户: {user.username} (ID: {user.id}, Role: {user.role})")
|
||||
|
||||
if grant_all:
|
||||
agents = Agent.query.all()
|
||||
agent_ids = [a.id for a in agents]
|
||||
print(f"📋 所有可用 Agent: {agent_ids}")
|
||||
|
||||
if not agent_ids:
|
||||
print("⚠️ 未指定 agent_ids,使用 --grant-all 授予所有权限")
|
||||
agents = Agent.query.all()
|
||||
user.agents = agents
|
||||
else:
|
||||
agents = Agent.query.filter(Agent.id.in_(agent_ids)).all()
|
||||
if not agents:
|
||||
print(f"❌ 未找到 ID 为 {agent_ids} 的 Agent")
|
||||
return False
|
||||
user.agents = agents
|
||||
|
||||
db.session.commit()
|
||||
print(f"✅ 权限授予成功!用户 {user.username} 现在可以访问 Agent: {[a.id for a in user.agents]}")
|
||||
return True
|
||||
|
||||
|
||||
def list_user_permissions(username=None, user_id=None):
|
||||
"""查看用户的 Agent 权限"""
|
||||
env = os.getenv('FLASK_ENV', 'production')
|
||||
app = create_app(env)
|
||||
|
||||
with app.app_context():
|
||||
user = None
|
||||
if user_id:
|
||||
user = User.query.get(int(user_id))
|
||||
elif username:
|
||||
user = User.query.filter_by(username=username).first()
|
||||
|
||||
if not user:
|
||||
print(f"❌ 用户不存在: username={username}, user_id={user_id}")
|
||||
return
|
||||
|
||||
print(f"\n👤 用户: {user.username} (ID: {user.id}, Role: {user.role})")
|
||||
print(f"📋 当前可访问的 Agent: {[a.id for a in user.agents]}")
|
||||
print("\n📋 所有 Agent 列表:")
|
||||
all_agents = Agent.query.all()
|
||||
for a in all_agents:
|
||||
has_access = a in user.agents
|
||||
print(f" [{a.id}] {a.name} - {'✅ 有权限' if has_access else '❌ 无权限'}")
|
||||
|
||||
|
||||
def list_all_users():
|
||||
"""列出所有用户及其权限"""
|
||||
env = os.getenv('FLASK_ENV', 'production')
|
||||
app = create_app(env)
|
||||
|
||||
with app.app_context():
|
||||
users = User.query.all()
|
||||
print("\n👥 所有用户列表:")
|
||||
for u in users:
|
||||
print(f" [{u.id}] {u.username} (Role: {u.role}) - Agents: {[a.id for a in u.agents]}")
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description='修复 Agent 权限')
|
||||
parser.add_argument('--username', '-u', type=str, help='用户名')
|
||||
parser.add_argument('--user-id', '-i', type=int, help='用户 ID')
|
||||
parser.add_argument('--agent-ids', '-a', type=int, nargs='+', help='Agent ID 列表,如: 1 2 3')
|
||||
parser.add_argument('--grant-all', '-g', action='store_true', help='授予所有 Agent 权限')
|
||||
parser.add_argument('--list', '-l', action='store_true', help='查看用户权限')
|
||||
parser.add_argument('--list-users', action='store_true', help='列出所有用户')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
if args.list_users:
|
||||
list_all_users()
|
||||
elif args.list:
|
||||
list_user_permissions(username=args.username, user_id=args.user_id)
|
||||
elif args.grant_all or args.agent_ids:
|
||||
grant_agent_permission(
|
||||
username=args.username,
|
||||
user_id=args.user_id,
|
||||
agent_ids=args.agent_ids,
|
||||
grant_all=args.grant_all
|
||||
)
|
||||
else:
|
||||
parser.print_help()
|
||||
@@ -0,0 +1,80 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
测试认证头格式脚本
|
||||
用途:测试不同的认证头格式
|
||||
"""
|
||||
import requests
|
||||
import json
|
||||
|
||||
BASE_URL = "http://127.0.0.1:5002"
|
||||
|
||||
def test_auth_header_format():
|
||||
"""测试不同的认证头格式"""
|
||||
|
||||
test_cases = [
|
||||
{
|
||||
"name": "格式1: 直接存储用户对象",
|
||||
"user_data": {"id": 1, "username": "admin", "role": "admin"},
|
||||
"description": "localStorage.setItem('hxops_user', JSON.stringify(user))"
|
||||
},
|
||||
{
|
||||
"name": "格式2: 包装格式 {user, expiry}",
|
||||
"user_data": {"user": {"id": 1, "username": "admin", "role": "admin"}, "expiry": 123456789},
|
||||
"description": "localStorage.setItem('hxops_user', JSON.stringify({user, expiry}))"
|
||||
},
|
||||
]
|
||||
|
||||
for tc in test_cases:
|
||||
print("\n" + "=" * 60)
|
||||
print(f"测试: {tc['name']}")
|
||||
print(f"描述: {tc['description']}")
|
||||
print(f"存储数据: {json.dumps(tc['user_data'], ensure_ascii=False)}")
|
||||
print("-" * 60)
|
||||
|
||||
# 模拟前端 JSON.parse 后的结果
|
||||
user = tc['user_data']
|
||||
|
||||
# 如果是包装格式,提取 user
|
||||
if 'user' in user:
|
||||
user = user['user']
|
||||
|
||||
headers = {
|
||||
'X-Username': user.get('username', ''),
|
||||
'X-Role': user.get('role', ''),
|
||||
}
|
||||
if user.get('id'):
|
||||
headers['X-User-Id'] = str(user['id'])
|
||||
|
||||
print(f"生成的 Headers: {headers}")
|
||||
|
||||
# 测试 API
|
||||
url = f"{BASE_URL}/api/chat/sessions?agent_id=3"
|
||||
response = requests.get(url, headers=headers, timeout=5)
|
||||
print(f"响应状态: {response.status_code}")
|
||||
if response.status_code != 200:
|
||||
print(f"响应内容: {response.text}")
|
||||
|
||||
def test_frontend_storage_format():
|
||||
"""测试前端实际存储格式"""
|
||||
print("\n" + "=" * 60)
|
||||
print("分析前端存储格式")
|
||||
print("=" * 60)
|
||||
|
||||
# 前端代码分析
|
||||
# WorkspaceView.vue 登录成功后:
|
||||
# localStorage.setItem('hxops_user', JSON.stringify({ user, expiry }));
|
||||
# 其中 user 是登录 API 返回的对象: {id, username, role}
|
||||
|
||||
print("前端存储逻辑分析:")
|
||||
print("1. 登录成功后调用: localStorage.setItem('hxops_user', JSON.stringify({ user, expiry }))")
|
||||
print("2. 其中 user 来自登录 API 返回: {id: 1, username: 'admin', role: 'admin'}")
|
||||
print("3. 实际存储格式: {\"user\": {\"id\": 1, \"username\": \"admin\", \"role\": \"admin\"}, \"expiry\": 123456789}")
|
||||
print("\n前端解析逻辑 (useChat.ts):")
|
||||
print("1. 获取: localStorage.getItem('hxops_user')")
|
||||
print("2. 解析: JSON.parse(stored)")
|
||||
print("3. 直接当作用户对象使用,不检查是否有 'user' 键")
|
||||
print("\n问题: 解析时没有处理包装格式,导致 username/role 为 undefined")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_frontend_storage_format()
|
||||
test_auth_header_format()
|
||||
@@ -0,0 +1,209 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
测试聊天 API 脚本
|
||||
用途:验证后端聊天功能是否正常工作
|
||||
"""
|
||||
import requests
|
||||
import json
|
||||
import sys
|
||||
|
||||
BASE_URL = "http://127.0.0.1:5002"
|
||||
|
||||
def test_login():
|
||||
"""测试登录 API"""
|
||||
print("=" * 50)
|
||||
print("任务一:测试登录 API")
|
||||
print("=" * 50)
|
||||
|
||||
url = f"{BASE_URL}/api/user/login"
|
||||
data = {"username": "admin", "password": "Hxit@54321"}
|
||||
|
||||
print(f"请求 URL: {url}")
|
||||
print(f"请求参数: {json.dumps(data, ensure_ascii=False)}")
|
||||
|
||||
try:
|
||||
response = requests.post(url, json=data, timeout=10)
|
||||
print(f"响应状态码: {response.status_code}")
|
||||
print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}")
|
||||
|
||||
if response.status_code == 200:
|
||||
user_data = response.json()
|
||||
return {
|
||||
"user_id": user_data.get("id"),
|
||||
"username": user_data.get("username"),
|
||||
"role": user_data.get("role")
|
||||
}
|
||||
except Exception as e:
|
||||
print(f"错误: {e}")
|
||||
|
||||
return None
|
||||
|
||||
def test_chat_sessions(user_info, agent_id):
|
||||
"""测试获取聊天会话列表"""
|
||||
print("\n" + "=" * 50)
|
||||
print(f"任务二:测试获取聊天会话列表 (agent_id={agent_id})")
|
||||
print("=" * 50)
|
||||
|
||||
url = f"{BASE_URL}/api/chat/sessions"
|
||||
headers = {
|
||||
"X-Username": user_info["username"],
|
||||
"X-Role": user_info["role"],
|
||||
"X-User-Id": str(user_info["user_id"])
|
||||
}
|
||||
|
||||
params = {"agent_id": agent_id}
|
||||
|
||||
print(f"请求 URL: {url}")
|
||||
print(f"请求 Headers: {headers}")
|
||||
print(f"请求参数: {params}")
|
||||
|
||||
try:
|
||||
response = requests.get(url, headers=headers, params=params, timeout=10)
|
||||
print(f"响应状态码: {response.status_code}")
|
||||
print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}")
|
||||
return response.status_code == 200
|
||||
except Exception as e:
|
||||
print(f"错误: {e}")
|
||||
return False
|
||||
|
||||
def test_chat_completions(user_info, agent_id):
|
||||
"""测试发送聊天消息"""
|
||||
print("\n" + "=" * 50)
|
||||
print(f"任务三:测试发送聊天消息 (agent_id={agent_id})")
|
||||
print("=" * 50)
|
||||
|
||||
url = f"{BASE_URL}/api/chat/completions"
|
||||
headers = {
|
||||
"X-Username": user_info["username"],
|
||||
"X-Role": user_info["role"],
|
||||
"X-User-Id": str(user_info["user_id"]),
|
||||
"Accept": "text/event-stream"
|
||||
}
|
||||
data = {
|
||||
"query": "年假有多少天?",
|
||||
"agent_id": agent_id,
|
||||
"conversation_id": ""
|
||||
}
|
||||
|
||||
print(f"请求 URL: {url}")
|
||||
print(f"请求 Headers: {headers}")
|
||||
print(f"请求体: {json.dumps(data, ensure_ascii=False)}")
|
||||
|
||||
full_response = []
|
||||
error_count = 0
|
||||
message_count = 0
|
||||
|
||||
try:
|
||||
response = requests.post(url, headers=headers, json=data, stream=True, timeout=60)
|
||||
print(f"响应状态码: {response.status_code}")
|
||||
print("-" * 30)
|
||||
print("流式响应内容:")
|
||||
print("-" * 30)
|
||||
|
||||
for line in response.iter_lines():
|
||||
if line:
|
||||
decoded_line = line.decode('utf-8')
|
||||
print(decoded_line)
|
||||
full_response.append(decoded_line)
|
||||
|
||||
if decoded_line.startswith('data: '):
|
||||
try:
|
||||
json_str = decoded_line[6:]
|
||||
event_data = json.loads(json_str)
|
||||
event = event_data.get("event")
|
||||
|
||||
if event == "message":
|
||||
message_count += 1
|
||||
answer = event_data.get("data", {}).get("answer", "")
|
||||
if answer:
|
||||
print(f"\n>>> 第 {message_count} 条消息: {answer[:100]}...")
|
||||
elif event == "error":
|
||||
error_count += 1
|
||||
error_msg = event_data.get("message", "")
|
||||
print(f"\n!!! 错误事件: {error_msg}")
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
print("-" * 30)
|
||||
print(f"消息计数: {message_count}")
|
||||
print(f"错误计数: {error_count}")
|
||||
|
||||
if message_count > 0:
|
||||
print("\n✅ 聊天功能测试成功!")
|
||||
return True
|
||||
elif error_count > 0:
|
||||
print("\n⚠️ 聊天功能返回了错误,但连接正常")
|
||||
return True
|
||||
else:
|
||||
print("\n❌ 聊天功能测试失败:无消息返回")
|
||||
return False
|
||||
|
||||
except requests.exceptions.Timeout:
|
||||
print("❌ 错误: 请求超时")
|
||||
return False
|
||||
except requests.exceptions.ConnectionError as e:
|
||||
print(f"❌ 错误: 连接失败 - {e}")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"❌ 错误: {e}")
|
||||
return False
|
||||
|
||||
def test_without_auth():
|
||||
"""测试未带认证头的请求"""
|
||||
print("\n" + "=" * 50)
|
||||
print("任务四:测试未带认证头的请求")
|
||||
print("=" * 50)
|
||||
|
||||
url = f"{BASE_URL}/api/chat/sessions?agent_id=3"
|
||||
|
||||
print(f"请求 URL: {url}")
|
||||
print("请求 Headers: (无)")
|
||||
|
||||
try:
|
||||
response = requests.get(url, timeout=10)
|
||||
print(f"响应状态码: {response.status_code}")
|
||||
print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}")
|
||||
|
||||
if response.status_code == 403:
|
||||
print("✅ 未带认证头时正确返回 403 权限错误(预期行为)")
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"错误: {e}")
|
||||
|
||||
return False
|
||||
|
||||
def main():
|
||||
print("=" * 60)
|
||||
print("hxops 聊天功能测试脚本")
|
||||
print("=" * 60)
|
||||
|
||||
# 测试一:登录
|
||||
user_info = test_login()
|
||||
if not user_info:
|
||||
print("\n❌ 登录失败,请检查后端服务是否运行")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"\n✅ 登录成功,用户: {user_info['username']}, 角色: {user_info['role']}")
|
||||
|
||||
# 测试二:获取聊天会话列表
|
||||
agent_id = 3 # 人事规章 Agent
|
||||
if not test_chat_sessions(user_info, agent_id):
|
||||
print("\n❌ 获取聊天会话列表失败")
|
||||
sys.exit(1)
|
||||
|
||||
print(f"\n✅ 获取聊天会话列表成功")
|
||||
|
||||
# 测试三:发送聊天消息
|
||||
if not test_chat_completions(user_info, agent_id):
|
||||
print("\n❌ 发送聊天消息失败")
|
||||
sys.exit(1)
|
||||
|
||||
# 测试四:未带认证头
|
||||
test_without_auth()
|
||||
|
||||
print("\n" + "=" * 60)
|
||||
print("所有测试完成!")
|
||||
print("=" * 60)
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in new issue
Block a user