在使用API密钥开发Python脚本时,Azure OpenAI出现错误

import openai# 设置openai.api_key = 'xxxxxxxxxxxxxxxxxxxxxx'openai.api_base = "xxxxxxxxxxxxxxxxxxxxxx"openai.api_version = '2024-08-20'  # 确保此版本正确def test_openai():    try:        response = openai.Image.create(            prompt="一只狗在雨中的图片",            model="dall-e-3",  # 如有需要,可以尝试使用不同的模型            n=1,            size="1024x1024"        )        print(response)    except Exception as e:        print(f"错误: {e}")test_openai()

错误: 资源未找到

我已经创建了Azure OpenAI模型dall-e-3

API密钥和API基础地址在使用模型gpt-35-turbo时都有效


回答:

您遇到这个错误是因为您需要使用部署名称而不是模型名称。

您需要创建一个客户端来连接并生成结果。

下面的代码对我来说是有效的。

我使用Flask应用来运行OpenAI代码,并在index.html文件中查看生成的图片。

app.py:

from flask import Flask,render_templateimport osfrom openai import AzureOpenAIimport jsonapp = Flask(__name__)@app.route('/', methods=['GET'])def fetch_image_url():    try:        client = AzureOpenAI(        api_version="2024-05-01-preview",        azure_endpoint="https://xxxxxxxxxx.openai.azure.com/",        api_key="xxxxxxxxxxxxxxxxxx"        )        result = client.images.generate(            model="dallechatgpt",            prompt="一只狗在雨中的图片",            n=1        )        image_url = json.loads(result.model_dump_json())['data'][0]['url']        return render_template('index.html',image_url=image_url)    except Exception as e:        print(f"错误{e}")        if __name__== "__main__":    app.run()

templates/index.html

<!DOCTYPE html><html lang="en"><head>    <meta charset="UTF-8">    <meta name="viewport" content="width=device-width, initial-scale=1.0">    <title>文档</title></head><body>    {% if image %}    <h2>生成的图片:</h2>    <img src="{{ image }}" alt="生成的图片" style="width: auto; height: 50vh;">    {% endif %}</body></html>

requirements.txt:

flaskopenai

输出:

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注