You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PyRIT调用AzureOpenAI API?PyRIT代码报错求助

解决PyRIT调用Azure OpenAI API失败的思路

1. 补充Azure OpenAI必填的模型参数

你的非PyRIT代码明确指定了model="myModel",但PyRIT的OpenAIChatTarget初始化时缺少该核心参数,需添加对应部署名称:

target = OpenAIChatTarget(
    endpoint="myEndpoint",
    api_key="myApiKey",
    deployment_name="myModel"  # 替换为你Azure上的模型部署名称
)

2. 修复异步代码运行环境问题

直接使用await但未放在异步函数或主异步入口中,会触发运行时错误,需调整代码结构:

import asyncio
from pyrit.common import IN_MEMORY, initialize_pyrit
from pyrit.orchestrator import PromptSendingOrchestrator
from pyrit.prompt_target import OpenAIChatTarget

initialize_pyrit(memory_db_type=IN_MEMORY)

async def main():
    prompt = "Hello, how are you?"

    target = OpenAIChatTarget(
        endpoint="myEndpoint",
        api_key="myApiKey",
        deployment_name="myModel"
    )

    # 和非PyRIT代码保持一致,添加系统提示词
    await target.set_system_prompt_async(system_prompt="You're a helpful assistant.")

    orchestrator = PromptSendingOrchestrator(target)
    response = await orchestrator.send_prompts_async(prompt_list=[prompt])
    await orchestrator.print_conversations_async()

if __name__ == "__main__":
    asyncio.run(main())

3. 补充Azure OpenAI API版本参数(按需)

部分Azure OpenAI服务要求指定API版本,可在初始化时添加:

target = OpenAIChatTarget(
    endpoint="myEndpoint",
    api_key="myApiKey",
    deployment_name="myModel",
    api_version="2024-02-15-preview"  # 替换为你的Azure API版本
)

4. 添加异常捕获排查具体错误

原代码未捕获异常,无法定位具体问题,需添加try-except块:

async def main():
    try:
        prompt = "Hello, how are you?"
        target = OpenAIChatTarget(...)
        await target.set_system_prompt_async(...)
        orchestrator = PromptSendingOrchestrator(target)
        response = await orchestrator.send_prompts_async(prompt_list=[prompt])
        await orchestrator.print_conversations_async()
    except Exception as e:
        print(f"具体错误信息: {str(e)}")

5. 验证权限与网络配置

  • 确认API密钥拥有Azure OpenAI服务的访问权限,无IP限制或权限不足问题
  • 用curl测试网络连通性:
curl -H "Content-Type: application/json" -H "api-key: myApiKey" "myEndpoint/openai/deployments/myModel/chat/completions?api-version=2024-02-15-preview" -d '{"messages": [{"role": "user", "content": "Hello"}]}'

内容的提问来源于stack exchange,提问作者user30129718

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 14:52:06