不能使用API

简介: 使用api 报错Cannot connect to host dashscope.aliyuncs.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]🚨 异常: TranslationRecognizerRealtime has stopped.

alibabacloud-bailian-speech-demo/s/speech-r/translate_speech_from_microphone_for_r/python master !1 ?11 ❯ python quick_ssl_bypass_test.py
⚠️ 警告: 此测试禁用了SSL验证!

🎯 目的: 验证API密钥是否有效

✅ API密钥: sk-8119136...
📡 连接中...
🎉 连接成功! (SSL验证已禁用)
❌ 错误: Cannot connect to host dashscope.aliyuncs.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1000)')]
🚨 异常: TranslationRecognizerRealtime has stopped.

!/usr/bin/env python3

-- coding: utf-8 --

"""
API密钥诊断工具
用于检查DashScope API密钥的有效性和权限
"""

import os
import sys
import dashscope
from dashscope.audio.asr import *
import requests
import json

def check_api_key_format():
"""检查API密钥格式"""
api_key = os.environ.get('DASHSCOPE_API_KEY', '')

print("=== API密钥格式检查 ===")
if not api_key:
    print("❌ 未设置DASHSCOPE_API_KEY环境变量")
    return False

if api_key == '<your-dashscope-api-key>':
    print("❌ API密钥未设置(仍为默认值)")
    return False

if not api_key.startswith('sk-'):
    print("❌ API密钥格式不正确(应以'sk-'开头)")
    return False

if len(api_key) < 20:
    print("❌ API密钥长度过短")
    return False

print(f"✅ API密钥格式正确: {api_key[:10]}...")
return True

def test_basic_api_access():
"""测试基本API访问"""
print("\n=== 基本API访问测试 ===")

try:
    # 设置API密钥
    dashscope.api_key = os.environ.get('DASHSCOPE_API_KEY')

    # 尝试调用一个简单的API来测试连接
    from dashscope import Generation

    response = Generation.call(
        model='qwen-turbo',
        prompt='Hello',
        max_tokens=10
    )

    if response.status_code == 200:
        print("✅ 基本API访问正常")
        return True
    else:
        print(f"❌ API访问失败: {response.status_code}")
        print(f"错误信息: {response.message}")
        return False

except Exception as e:
    print(f"❌ API访问异常: {str(e)}")
    return False

def test_audio_service_access():
"""测试音频服务访问权限"""
print("\n=== 音频服务权限测试 ===")

try:
    # 创建一个简单的回调类用于测试
    class TestCallback(TranslationRecognizerCallback):
        def __init__(self):
            self.success = False
            self.error_msg = ""

        def on_open(self):
            print("✅ 音频服务连接成功")
            self.success = True

        def on_error(self, message):
            self.error_msg = f"错误: {message.message}"
            print(f"❌ 音频服务错误: {message.message}")

        def on_event(self, request_id, transcription_result, translation_result, usage):
            pass

        def on_complete(self):
            pass

        def on_close(self):
            pass

    callback = TestCallback()

    # 尝试创建翻译识别器
    translator = TranslationRecognizerRealtime(
        model='gummy-realtime-v1',
        format='pcm',
        sample_rate=16000,
        transcription_enabled=False,
        translation_enabled=True,
        translation_target_languages=['en'],
        callback=callback,
    )

    # 尝试启动服务
    translator.start()

    # 等待一下看是否有错误
    import time
    time.sleep(2)

    translator.stop()

    if callback.success:
        print("✅ 音频翻译服务权限正常")
        return True
    else:
        print(f"❌ 音频翻译服务权限问题: {callback.error_msg}")
        return False

except Exception as e:
    print(f"❌ 音频服务测试异常: {str(e)}")
    return False

def check_account_status():
"""检查账户状态"""
print("\n=== 账户状态建议 ===")
print("如果API密钥格式正确但仍无法访问,请检查:")
print("1. 🌐 登录阿里云控制台: https://dashscope.console.aliyun.com/")
print("2. 💰 检查账户余额是否充足")
print("3. 🔧 确认是否已开通'通义千问'服务")
print("4. 🎙️ 确认是否已开通'语音合成与识别'服务")
print("5. 🔑 尝试重新生成API密钥")
print("6. 📍 检查服务区域设置(推荐使用'华东1(杭州)')")
print("7. 📋 查看控制台中的服务使用限制")

def provide_solutions():
"""提供解决方案"""
print("\n=== 解决方案建议 ===")
print("1. 重新获取API密钥:")
print(" - 访问: https://dashscope.console.aliyun.com/api-key")
print(" - 删除现有密钥,重新创建")
print(" - 确保账户已实名认证")

print("\n2. 开通必要服务:")
print("   - DashScope通义千问: https://dashscope.console.aliyun.com/")
print("   - 语音技术服务: https://nls-portal.console.aliyun.com/")

print("\n3. 检查计费和配额:")
print("   - 确保账户有足够余额")
print("   - 检查API调用限制")

print("\n4. 如果是新账户:")
print("   - 可能需要等待服务开通(通常几分钟)")
print("   - 确保完成实名认证")

def main():
"""主函数"""
print("DashScope API 诊断工具")
print("=" * 50)

# 检查API密钥格式
format_ok = check_api_key_format()

if not format_ok:
    print("\n请先正确设置API密钥:")
    print("export DASHSCOPE_API_KEY='你的实际API密钥'")
    return

# 测试基本API访问
basic_ok = test_basic_api_access()

# 测试音频服务
audio_ok = test_audio_service_access()

# 提供建议
check_account_status()

if not basic_ok or not audio_ok:
    provide_solutions()

print("\n" + "=" * 50)
if basic_ok and audio_ok:
    print("🎉 所有测试通过!您的API密钥应该可以正常使用。")
else:
    print("⚠️  存在权限问题,请按照上述建议进行排查。")

if name == 'main':
main()

相关文章
|
数据采集 机器学习/深度学习 算法
|
8月前
|
人工智能 IDE API
10行代码,实现你的专属阿里云OpenAPI MCP Server
本文介绍如何用10行Python代码创建专属阿里云OpenAPI MCP Server。针对传统MCP Server工具固化、开发复杂等问题,提出借助alibaba-cloud-ops-mcp-server实现灵活拓展的方案。通过配置服务与API名称,运行简短代码即可生成支持SSE连接的MCP Server。用户无需深入了解阿里云OpenAPI细节,大幅降低开发门槛。未来将探索通用工具设计,实现固定工具调用任意API,进一步提升灵活性与效率。
|
安全 Java 开发者
Java 21 新特性详解(Record、Pattern Matching、Switch 改进)
Java 21发布,作为LTS版本带来Record模式匹配、Switch表达式增强等重要特性,提升代码简洁性与可读性。支持嵌套匹配、类型检查与条件判断,结合密封类实现安全多态,优化性能并减少冗余代码,助力开发者构建更高效、清晰的现代Java应用。
346 2
|
数据采集 Linux 网络安全
python 爬虫遇到的aiohttp证书错误解决办法
python 爬虫遇到的aiohttp证书错误解决办法
749 0
|
4月前
|
安全 数据安全/隐私保护
屏幕自动点击器, 手机自动点击器, 自动连点器屏幕【autojs】
完整UI界面:包含悬浮窗控制面板,支持拖动位置调整 核心功能:单点/连续点击、位置记录、任务执行与停止
|
10月前
|
安全 Linux 开发工具
【Azure 环境】Azure 虚拟机上部署 DeepSeek R1 模型教程(1.5B参数)【失败】
遇见错误一:operator torchvision::nms does not exist 遇见错误二:RuntimeError: Failed to infer device type
907 22
Idea的server.port端口不生效yml配置文件不生效
Idea的server.port端口不生效yml配置文件不生效
1253 2
|
机器学习/深度学习 自然语言处理 机器人
【RAG实践】Rerank,让RAG更近一步
本文主要关注在Rerank,本文中,Rerank可以在不牺牲准确性的情况下加速LLM的查询(实际上可能提高准确率),Rerank通过从上下文中删除不相关的节点,重新排序相关节点来实现这一点。
|
安全 开发工具 git
蓝易云 - git rebase和merge区别
在选择使用Merge还是Rebase时,需要根据具体的工作流程和团队的规定来决定。一般来说,如果你想保持完整的历史记录并且避免可能的冲突,你应该使用Merge。如果你想要一个干净的、线性的历史记录,你可以使用Rebase。
593 4
|
网络协议 Serverless 应用服务中间件
Serverless 应用引擎操作报错合集之在阿里云函数计算中,服务器调用FC函数时出现 "[Errno -3] Temporary failure in name resolution)" 错误如何解决
Serverless 应用引擎(SAE)是阿里云提供的Serverless PaaS平台,支持Spring Cloud、Dubbo、HSF等主流微服务框架,简化应用的部署、运维和弹性伸缩。在使用SAE过程中,可能会遇到各种操作报错。以下是一些常见的报错情况及其可能的原因和解决方法。
990 4