故障排除教程¶
快速诊断¶
运行此诊断脚本以检查您的 ToolUniverse 安装情况:
from tooluniverse import ToolUniverse
# Run basic system check
try:
tu = ToolUniverse()
tu.load_tools()
print(f"✅ ToolUniverse working correctly! {len(tu.all_tools)} tools loaded.")
except Exception as e:
print(f"❌ Issue detected: {e}")
安装问题¶
ImportError: 未找到名为 ‘tooluniverse’ 的模块¶
症状: Python 无法找到 ToolUniverse 模块。
诊断:
python -c "import tooluniverse; print(tooluniverse.__version__)"
解决方案:
依赖冲突¶
症状: 安装过程中出现软件包版本冲突。
检查依赖项:
pip check
解决方案:
创建清洁环境:
conda create -n tooluniverse python=3.10 conda activate tooluniverse pip install tooluniverse
更新冲突的程序包:
pip install --upgrade requests urllib3 certifi安装特定版本:
pip install 'requests>=2.25.0,<3.0.0'
运行时错误¶
工具未找到错误¶
症状: ToolNotFoundError: 未找到工具 'XYZ'
诊断:
from tooluniverse import ToolUniverse
tu = ToolUniverse()
tu.load_tools()
# List available tools
print("Available tools:")
for tool_name in tu.list_built_in_tools(mode='list_name'):
print(f" - {tool_name}")
解决方案:
检查工具名称拼写:
# Correct tool names correct_names = [ "OpenTargets_get_associated_targets_by_disease_efoId", "PubChem_get_compound_info", "UniProt_get_function_by_accession" ]
验证工具已加载:
if "OpenTargets_tool" not in tu.all_tool_dict: print("OpenTargets tool not loaded") # Check for missing dependencies
手动工具装载:
from tooluniverse.opentargets_tool import OpenTargetsTool tool = OpenTargetsTool() tu.register_custom_tool(tool_instance=tool)
API 认证错误¶
Symptom: 401 Unauthorized, 403 Forbidden, or “API key required” errors.
Common API Error Codes¶
When you encounter API errors, check this reference table:
Error Code |
Meaning |
Solution |
|---|---|---|
401 Unauthorized |
Invalid or missing API key |
Verify API key is correct and environment variable is set correctly. Check with |
403 Forbidden |
Valid key but insufficient permissions |
Check account subscription level. May need to upgrade or request additional access from API provider. |
429 Too Many Requests |
Rate limit exceeded |
Add API key for higher limits, enable caching with |
404 Not Found |
Invalid resource identifier |
Verify ID format (e.g., UniProt accession “P05067”, ChEMBL ID “CHEMBL25”). Check Glossary for ID formats. |
502 Bad Gateway |
Service temporarily unavailable |
Wait 30-60 seconds and retry. Check API provider’s status page if error persists. |
503 Service Unavailable |
API endpoint overloaded or maintenance |
Retry with exponential backoff (wait 2s, 4s, 8s…). Check provider status page. |
诊断:
import os
# Check if API keys are set (environment variables)
api_keys = {
'NVIDIA_API_KEY': os.getenv('NVIDIA_API_KEY'),
'NCBI_API_KEY': os.getenv('NCBI_API_KEY'),
'SEMANTIC_SCHOLAR_API_KEY': os.getenv('SEMANTIC_SCHOLAR_API_KEY'),
'DISGENET_API_KEY': os.getenv('DISGENET_API_KEY'),
'USPTO_API_KEY': os.getenv('USPTO_API_KEY'),
'FDA_API_KEY': os.getenv('FDA_API_KEY'),
'OMIM_API_KEY': os.getenv('OMIM_API_KEY'),
}
for key, value in api_keys.items():
status = "✓ Set" if value else "✗ Missing"
print(f"{key}: {status}")
解决方案:
Identify which API key you need:
See API Keys and Authentication for a complete list of which tools require which API keys and how to obtain them.
Set API keys in environment:
# Linux/macOS export NVIDIA_API_KEY="your_key_here" export NCBI_API_KEY="your_ncbi_key" # Windows (Command Prompt) set NVIDIA_API_KEY=your_key_here # Windows (PowerShell) $env:NVIDIA_API_KEY="your_key_here"
Use .env file (recommended):
# Copy template and fill in your keys cp docs/.env.template .env nano .env # or use any text editor
from dotenv import load_dotenv load_dotenv() # Load from .env file
In Python code:
import os os.environ['NVIDIA_API_KEY'] = 'your_key_here' os.environ['NCBI_API_KEY'] = 'your_ncbi_key'
Common API key issues:
Key is expired or invalid: Regenerate the key from the provider’s dashboard
Key has insufficient permissions: Check that the key has the necessary scopes/permissions
Key not loaded: Ensure environment variables are set before importing ToolUniverse
Typo in variable name: Double-check spelling (e.g.,
NVIDIA_API_KEYnotNVIDIA_KEY)
速率限制错误¶
症状: 429 请求过多 或 RateLimitExceeded
Understanding Rate Limits:
Many services limit how many requests you can make per second/minute. API keys typically provide much higher limits:
Service |
Without API Key |
With API Key |
|---|---|---|
NCBI E-utilities |
3 req/sec |
10 req/sec (3x faster, set NCBI_API_KEY) |
Semantic Scholar |
1 req/sec |
100 req/sec (100x faster, set SEMANTIC_SCHOLAR_API_KEY) |
OpenFDA |
40 req/min |
240 req/min (6x faster, set FDA_API_KEY) |
解决方案:
Get an API key for higher limits:
See API Keys and Authentication for how to obtain API keys for each service.
在请求之间添加延迟:
import time for query in queries: result = tu.run(query) time.sleep(1) # Wait 1 second between requests
使用批处理:
# Process in smaller batches batch_size = 5 for i in range(0, len(queries), batch_size): batch = queries[i:i+batch_size] results = tu.run(batch, max_workers=4) time.sleep(2) # Pause between batches
Enable caching to avoid redundant requests:
import os os.environ["TOOLUNIVERSE_CACHE_DEFAULT_TTL"] = "3600" # 1 hour result = tu.run(query, use_cache=True)
网络与连接¶
连接超时¶
症状: ConnectionTimeout 或 ReadTimeout 错误。
诊断:
import requests
# Test basic connectivity
try:
response = requests.get('https://httpbin.org/delay/1', timeout=5)
print(f"Network OK: {response.status_code}")
except requests.exceptions.Timeout:
print("Network timeout - check connection")
解决方案:
增加超时时间:
tu = ToolUniverse() # timeout is configured per-tool at the HTTP request level检查网络连接:
ping google.com curl -I https://platform-api.opentargets.org
配置智能体(如有需要):
import os os.environ['HTTP_PROXY'] = 'http://proxy.company.com:8080' os.environ['HTTPS_PROXY'] = 'http://proxy.company.com:8080'
SSL 证书错误¶
症状: SSLError 或证书验证失败。
解决方案:
更新证书:
pip install --upgrade certifi requests urllib3临时绕过(不建议用于生产环境):
import ssl ssl._create_default_https_context = ssl._create_unverified_context
企业防火墙:
请联系您的IT部门以正确配置证书。
性能问题¶
查询性能缓慢¶
诊断:
import time
from tooluniverse import ToolUniverse
tu = ToolUniverse()
# Time a query
start_time = time.time()
result = tu.run({"name": "tool_name", "arguments": {}})
elapsed = time.time() - start_time
print(f"Query took {elapsed:.2f} seconds")
优化策略:
启用缓存:
import os os.environ["TOOLUNIVERSE_CACHE_DEFAULT_TTL"] = "3600" # 1 hour tu = ToolUniverse() result = tu.run(..., use_cache=True)
使用异步操作:
import asyncio async def run_queries(): tasks = [tu.run(query) for query in queries] # run() is context-aware results = await asyncio.gather(*tasks) return results
批量处理相似查询:
# Instead of individual queries by gene symbol, prefer accession-based queries accession_info = [] for accession in accessions: info = tu.run({ "name": "UniProt_get_function_by_accession", "arguments": {"accession": accession} }) accession_info.append(info) # Use batch processing queries = [ {"name": "UniProt_get_function_by_accession", "arguments": {"accession": accession}} for accession in accessions ] results = tu.run(queries, max_workers=4)
内存使用问题¶
症状: 高内存消耗或``MemoryError``。
诊断:
import psutil
import os
process = psutil.Process(os.getpid())
memory_mb = process.memory_info().rss / 1024 / 1024
print(f"Memory usage: {memory_mb:.1f} MB")
解决方案:
分块处理数据:
def process_large_dataset(data, chunk_size=100): for i in range(0, len(data), chunk_size): chunk = data[i:i+chunk_size] yield tu.run(chunk, max_workers=4)
定期清理缓存:
tu.clear_cache()对于大量结果,使用生成器:
def yield_results(queries): for query in queries: yield tu.run(query)
MCP 服务器问题¶
MCP 服务器无法启动¶
症状: 服务器无法启动或立即崩溃。
诊断:
# Test server directly tooluniverse-smcp --debug
解决方案:
检查端口可用性:
# Check if port is in use lsof -i :3000 # Linux/Mac netstat -an | findstr :3000 # Windows
使用不同端口:
tooluniverse-smcp --port 3001检查权限:
# Ensure user can bind to port sudo tooluniverse-smcp # If needed
Claude/AI 助手未找到工具¶
诊断:
验证 MCP 服务器是否正在运行:
curl http://localhost:3000/health检查 Claude 配置:
确保在 Claude Desktop 设置中正确配置 MCP 服务器。
解决方案:
重启服务器和 Claude
检查 Claude 日志 以排查连接错误
验证工具注册:
# In MCP server tools = tu.return_all_loaded_tools() print(f"Registered {len(tools)} tools")
高级调试¶
启用调试日志记录¶
import logging
# Enable debug logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('tooluniverse')
logger.setLevel(logging.DEBUG)
# Now run your code
tu = ToolUniverse()
捕获详细的错误信息¶
import traceback
try:
result = tu.run(query)
except Exception as e:
print(f"Error: {e}")
print(f"Type: {type(e).__name__}")
print("Traceback:")
traceback.print_exc()
分析性能瓶颈¶
import cProfile
import pstats
# Profile your code
profiler = cProfile.Profile()
profiler.enable()
# Your ToolUniverse code here
tu = ToolUniverse()
result = tu.run(query)
profiler.disable()
# Analyze results
stats = pstats.Stats(profiler)
stats.sort_stats('cumulative')
stats.print_stats(10)
获取帮助¶
如果以上解决方案均无效:
查看常见问题解答:Comprehensive FAQ
搜索 GitHub 问题:Issues
创建缺陷报告,内容包括:
ToolUniverse 版本:
tooluniverse.__version__Python 版本:
python --version操作系统
完整错误信息及追踪记录
重现该问题的最简代码示例
加入我们的社区:Discord 服务器链接
from tooluniverse.diagnostics import run_diagnostic print(run_diagnostic())请在您的错误报告中包含此输出。