gpt 3-试图生成嵌入时openai API出错

lrl1mhuk  于 2023-03-24  发布在  其他
关注(0)|答案(1)|浏览(191)

我有一个python代码,可以用openai创建一个embedding,但是当我尝试执行代码时,我收到了这个错误

  • 服务器当前因其他请求而过载。很抱歉!您可以重试您的请求,或者如果错误仍然存在,请通过我们的帮助中心www.example.com与我们联系help.openai.com。*

下面是python代码

# Carga el diccionario de HPOs desde un archivo JSON
with open("hpos.json") as f:
    hpos_dict = json.load(f)

# Crea un diccionario para almacenar los embeddings
hpo_embeddings = {}

i = 0
hposNumber = len(hpos_dict)
# Crea los embeddings y guárdalos en el diccionario
for hpo_id, hpo_descs in hpos_dict.items():
    embedding_list = []
    for hpo_desc in hpo_descs:
        response = openai.Embedding.create(
            input=hpo_desc,
            model="text-embedding-ada-002"
        )
        embedding_list.append(response["data"][0]["embedding"])
    hpo_embeddings[hpo_id] = embedding_list
    i = i + 1
    print( str(i) + "/" + str(hposNumber) )

# Guarda el diccionario de embeddings en un archivo JSON
with open("hpo_embeddings.json", "w") as f:
    json.dump(hpo_embeddings, f)
bwntbbo3

bwntbbo31#

要解决此问题,您可以在服务器负载降低后重试请求。您也可以尝试减少向OpenAI API发出的请求数量,以避免服务器不堪重负。或者,您可以尝试使用其他API端点或模型,这些端点或模型可能不那么忙碌。
或者你可以不断地重试调用API,直到你收到响应, checkout 这里是你的代码的更新版本来实现这一点:

import time
import json
import openai

# Set up OpenAI API credentials
openai.api_key = "YOUR_API_KEY"

# Load the HPOs dictionary from a JSON file
with open("hpos.json") as f:
    hpos_dict = json.load(f)

# Create a dictionary to store the embeddings
hpo_embeddings = {}

# Loop through each HPO and create embeddings
for hpo_id, hpo_descs in hpos_dict.items():
    embedding_list = []
    for hpo_desc in hpo_descs:
        # Retry the API call if it fails due to server overload
        while True:
            try:
                response = openai.Embedding.create(
                    input=hpo_desc,
                    model="text-embedding-ada-002"
                )
                embedding_list.append(response["data"][0]["embedding"])
                break # Exit the loop if the API call succeeds
            except openai.error.APIError as e:
                # If the API call fails, wait and retry after a delay
                print("API error:", e)
                print("Retrying in 10 seconds...")
                time.sleep(10)
        hpo_embeddings[hpo_id] = embedding_list

    print(f"Processed HPO {hpo_id}, {len(hpo_descs)} descriptions")

# Save the embeddings to a JSON file
with open("hpo_embeddings.json", "w") as f:
    json.dump(hpo_embeddings, f)

相关问题