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