Skip to content

feat: 添加模型可用性检测模块#18

Open
jcy321 wants to merge 3 commits intoAmethystDev-Labs:mainfrom
jcy321:main
Open

feat: 添加模型可用性检测模块#18
jcy321 wants to merge 3 commits intoAmethystDev-Labs:mainfrom
jcy321:main

Conversation

@jcy321
Copy link
Copy Markdown

@jcy321 jcy321 commented Mar 10, 2026

  • 新增 availability 模块用于测试 API 模型可用性
  • 添加 Python 测试脚本检测模型能力(思考/多模态)
  • 添加可视化 HTML 报告页面
  • 添加 Go 路由支持 /availability 访问
  • 支持定时任务运行检测

- 新增 availability 模块用于测试 API 模型可用性
- 添加 Python 测试脚本检测模型能力(思考/多模态)
- 添加可视化 HTML 报告页面
- 添加 Go 路由支持 /availability 访问
- 支持定时任务运行检测
@gemini-code-assist
Copy link
Copy Markdown

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

此拉取请求引入了一个全面的模型可用性监控系统。它通过自动化测试脚本定期评估 API 模型的运行状态和特定功能(如思考和多模态),并将结果以用户友好的可视化报告形式呈现。这大大提升了对模型服务质量的洞察力,并能及时发现潜在问题,确保服务的稳定性和可靠性。

Highlights

  • 新增模型可用性检测模块: 引入了一个全新的 availability 模块,用于自动化测试 API 模型的可用性。
  • Python 测试脚本: 添加了 Python 脚本来检测模型的具体能力,包括其“思考”能力(如工具调用)和多模态(视觉)能力。
  • 可视化报告页面: 提供了一个交互式的 HTML 页面,用于直观展示模型可用性测试结果。
  • Go 路由支持: 在 Go 后端添加了 /availability 路由,以便访问和提供可视化报告页面及测试结果。
  • 定时任务支持: 设计了支持定时任务运行检测的机制,确保模型可用性能够定期自动检查。
Changelog
  • availability/README.md
    • 新增了 availability 模块的 README 文档,详细说明了目录结构、使用方法、API 密钥配置、手动运行测试、定时任务设置以及报告访问方式。
    • 文档中还列出了相关的环境变量和 API 端点。
  • availability/index.html
    • 新增了模型可用性报告的可视化 HTML 页面。
    • 页面包含了模型总览统计、思考模型列表、视觉模型列表以及所有模型的详细网格展示。
    • 实现了搜索和过滤功能,并提供了模型名称复制到剪贴板的交互功能。
    • 页面样式采用了深色主题,提升了用户体验。
  • availability/results.json
    • 新增了用于存储模型可用性测试结果的 JSON 格式文件。
    • 文件定义了时间戳、总模型数、可用模型数、思考模型列表、视觉模型列表以及每个模型的详细测试结果。
  • availability/run_test.sh
    • 新增了用于执行模型可用性检测的 shell 脚本。
    • 脚本负责切换到正确的目录,从环境变量或 api_key.txt 文件中读取 API 密钥,并调用 Python 测试脚本保存结果。
  • availability/test_models.py
    • 新增了 Python 脚本,用于检测 API 模型的可用性。
    • 脚本能够获取模型列表,测试模型的“思考”能力和多模态(视觉)能力。
    • 包含了请求超时、429 限流重试逻辑,并能将测试结果保存为 JSON 格式。
    • 支持通过命令行参数配置 API 密钥、API 地址、输出文件和请求间隔。
  • controller/availability.go
    • 新增了 availability.go 控制器,用于处理 /availability 路径下的请求。
    • 该控制器负责根据请求路径提供 availability 目录下的静态文件,如 HTML 报告、JSON 结果等。
    • 实现了文件读取、内容类型判断以及禁用缓存的功能,并支持通过环境变量自定义报告目录。
  • router/availability-router.go
    • 新增了 availability-router.go 文件,定义了 /availability 路由组。
    • 该路由组使用了 middleware.RouteTag 进行路由标记,并启用了 gzip 压缩。
    • 所有 /availability/*path 的请求都将由 controller.ServeAvailability 处理。
  • router/main.go
    • 修改了 SetRouter 函数,注册了新的 SetAvailabilityRouter,将模型可用性检测报告的路由集成到主应用中。
Activity
  • 目前没有与此拉取请求相关的活动记录。
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This PR introduces a very useful model availability detection module, including a Python detection script, a frontend report page, and a Go backend route. The overall implementation is good, with clear code structure and complete functionality. However, several security vulnerabilities were identified, including path traversal in the file serving controller, missing access control on the availability routes, and potential cross-site scripting (XSS) in the report visualization page. These critical issues must be addressed before merging. Additionally, there are areas for improvement: using a bare except: in availability/test_models.py is bad practice and should be replaced with more specific exception handling, and the copy-to-clipboard function in availability/index.html fails in HTTP environments, which contradicts the documentation's HTTP examples.

Comment on lines +22 to +30
relativePath := c.Param("path") // 获取请求的相对路径

// --- 处理默认路径 ---
if relativePath == "" || relativePath == "/" {
relativePath = "/index.html" // 默认返回首页
}

relativePath = strings.TrimPrefix(relativePath, "/") // 移除前导斜杠
filePath := filepath.Join(availabilityDir, relativePath) // 拼接完整文件路径
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

The ServeAvailability function is vulnerable to path traversal. It uses a user-supplied path parameter to construct a file path without proper sanitization. Attackers can exploit this by including ../ sequences in the path parameter (e.g., /availability/../main.go), allowing them to traverse directories and read arbitrary files on the server outside the availability directory. filepath.Join resolves .., which contributes to this vulnerability. Additionally, the current manual implementation of static file serving introduces code redundancy. To address the path traversal, filepath.Clean should be used to sanitize the path parameter as shown in the suggestion, preventing directory traversal.

relativePath := c.Param("path")
	// --- 处理默认路径 ---
	if relativePath == "" || relativePath == "/" {
		relativePath = "/index.html"
	}

	relativePath = strings.TrimPrefix(relativePath, "/")
	// Use filepath.Clean to prevent path traversal
	cleanPath := filepath.Clean(relativePath)
	if strings.HasPrefix(cleanPath, "..") || filepath.IsAbs(cleanPath) {
		c.Status(http.StatusBadRequest)
		return
	}
	filePath := filepath.Join(availabilityDir, cleanPath)

Comment on lines +13 to +18
availabilityRouter := router.Group("/availability") // 可用性报告路径前缀
availabilityRouter.Use(middleware.RouteTag("availability")) // 标记路由类型
availabilityRouter.Use(gzip.Gzip(gzip.DefaultCompression)) // 启用gzip压缩
{
availabilityRouter.GET("/*path", controller.ServeAvailability) // 所有子路径由控制器处理
}
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-high high

The /availability route group lacks any authentication or authorization checks. This allows unauthenticated users to access the availability report and, combined with the path traversal vulnerability, read arbitrary files on the server.

func SetAvailabilityRouter(router *gin.Engine) {
	availabilityRouter := router.Group("/availability")
	availabilityRouter.Use(middleware.RouteTag("availability"))
	availabilityRouter.Use(middleware.UserAuth())
	availabilityRouter.Use(middleware.AdminAuth())
	availabilityRouter.Use(gzip.Gzip(gzip.DefaultCompression))
	{
		availabilityRouter.GET("/*path", controller.ServeAvailability)
	}
}

Comment thread availability/index.html
Comment on lines +383 to +399
document.getElementById('modelGrid').innerHTML = filtered.map(m => {
const timeClass = m.responseTime < 1 ? 'fast' : m.responseTime < 5 ? 'medium' : 'slow'; // 响应时间分类
return `
<div class="model-card" onclick="copyModel('${m.model}')">
<div class="model-card-name">${m.model}</div>
<div class="model-tags">
${m.isThinking ? '<span class="tag thinking">Thinking</span>' : ''} <!-- 思考模型标签 -->
${m.supportsVision ? '<span class="tag vision">Vision</span>' : ''} <!-- 多模态标签 -->
${!m.available ? '<span class="tag unavailable">Unavailable</span>' : ''}
</div>
<div class="model-meta">
<span>${m.available ? '✅ OK' : '❌ ' + (m.error || 'N/A')}</span>
${m.responseTime ? `<span class="${timeClass}">⚡ ${m.responseTime.toFixed(1)}s</span>` : ''} <!-- 响应时间 -->
</div>
</div>
`;
}).join('');
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

security-medium medium

The availability/index.html file fetches data from results.json and renders it using innerHTML without proper escaping. Specifically, the model and error fields from the JSON data are directly embedded into the HTML. If an attacker can control the model names or trigger specific error messages (e.g., through a malicious API response), they can inject and execute arbitrary JavaScript in the context of the user's browser.

Suggested change
document.getElementById('modelGrid').innerHTML = filtered.map(m => {
const timeClass = m.responseTime < 1 ? 'fast' : m.responseTime < 5 ? 'medium' : 'slow'; // 响应时间分类
return `
<div class="model-card" onclick="copyModel('${m.model}')">
<div class="model-card-name">${m.model}</div>
<div class="model-tags">
${m.isThinking ? '<span class="tag thinking">Thinking</span>' : ''} <!-- 思考模型标签 -->
${m.supportsVision ? '<span class="tag vision">Vision</span>' : ''} <!-- 多模态标签 -->
${!m.available ? '<span class="tag unavailable">Unavailable</span>' : ''}
</div>
<div class="model-meta">
<span>${m.available ? '✅ OK' : '❌ ' + (m.error || 'N/A')}</span>
${m.responseTime ? `<span class="${timeClass}">⚡ ${m.responseTime.toFixed(1)}s</span>` : ''} <!-- 响应时间 -->
</div>
</div>
`;
}).join('');
document.getElementById('modelGrid').innerHTML = filtered.map(m => {
const timeClass = m.responseTime < 1 ? 'fast' : m.responseTime < 5 ? 'medium' : 'slow';
const safeModel = document.createElement('div').appendChild(document.createTextNode(m.model)).parentNode.innerHTML;
const safeError = document.createElement('div').appendChild(document.createTextNode(m.error || 'N/A')).parentNode.innerHTML;
return `
<div class="model-card" onclick="copyModel('${safeModel}')">
<div class="model-card-name">${safeModel}</div>
<div class="model-tags">
${m.isThinking ? '<span class="tag thinking">Thinking</span>' : ''}
${m.supportsVision ? '<span class="tag vision">Vision</span>' : ''}
${!m.available ? '<span class="tag unavailable">Unavailable</span>' : ''}
</div>
<div class="model-meta">
<span>${m.available ? '✅ OK' : '❌ ' + safeError}</span>
${m.responseTime ? `<span class="${timeClass}">⚡ ${m.responseTime.toFixed(1)}s</span>` : ''}
</div>
</div>
`;
}).join('');

Comment on lines +99 to +105
try:
response = requests.post(f"{baseUrl}/chat/completions", headers=headers, json=payload, timeout=timeout)
if response.status_code == 200:
data = response.json()
return bool(data.get("choices", [{}])[0].get("message", {}).get("content")) # 有返回内容则支持视觉
except:
pass
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

避免使用裸露的 except:

testVision 函数中,except: 会捕获所有类型的异常,包括 KeyboardInterruptSystemExit,这通常不是期望的行为。这种做法会隐藏潜在的 bug,使调试变得困难。

建议至少捕获 Exception,或者更具体的异常,例如 requests.exceptions.RequestException。同时,最好记录下发生的错误,以便排查问题。

Suggested change
try:
response = requests.post(f"{baseUrl}/chat/completions", headers=headers, json=payload, timeout=timeout)
if response.status_code == 200:
data = response.json()
return bool(data.get("choices", [{}])[0].get("message", {}).get("content")) # 有返回内容则支持视觉
except:
pass
try:
response = requests.post(f"{baseUrl}/chat/completions", headers=headers, json=payload, timeout=timeout)
if response.status_code == 200:
data = response.json()
return bool(data.get("choices", [{}])[0].get("message", {}).get("content"))
except requests.exceptions.RequestException as e:
print(f" [视觉测试请求失败]: {e}")
except Exception as e:
print(f" [视觉测试出现意外错误]: {e}")

Comment thread availability/index.html
}

function copyModel(name) {
navigator.clipboard.writeText(name).then(() => {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

剪贴板功能需要安全上下文 (HTTPS)

navigator.clipboard.writeText() API 为了安全起见,在大多数现代浏览器中只在安全上下文(即 HTTPS 页面或 localhost)下可用。

当前 README.md 中的访问示例是 http://。如果服务部署在非本地的 HTTP 环境下,“点击复制”功能将无法工作,并且可能不会有明显的错误提示。

建议:

  1. README.md 中强调建议使用 HTTPS 部署。
  2. 可以在 JavaScript 代码中增加一个检查,如果 navigator.clipboard 不可用,可以给用户一个提示,或者优雅地禁用复制功能,以改善用户体验。例如,在 copyModel 函数中添加一个 if (!navigator.clipboard) 的判断。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant