使用Python发送OpenAI Chat API请求的代码解析

在这篇博客中,我们将解析一个使用Python发送OpenAI Chat API请求的代码片段,来检查openai apikey的可用性

你也可以将3.5的模型更换成4.0来检查是否支持4.0

1. 导入所需的库

这里不使用官方库 没有为什么

更新成使用官方库了 没有为什么

首先,我们需要导入所需的库。在这个例子中,我们使用了以下库:

import pandas as pd
import openai
```python
# 完整代码
import pandas as pd
import requests
import json

# 1. Read the CSV file
df = pd.read_csv('apykey.csv')

# 2. Traverse the DataFrame
for i, api_key in df['OPENAI_API_KEY'].items():
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    data = {
        "model": "gpt-3.5-turbo",
        "messages": [{"role": "system", "content": "Hello"}, {"role": "user", "content": "Hello!"}]
    }

    response = requests.post('https:/api.opneai.com/v1/chat/completions', headers=headers, data=json.dumps(data))

    # if 'error' in response.text:
    if 'error' in response.text:
        status = 'error'
    else:
        status = 'ok'

    # Print the API key and status
    print(f"API Key: {api_key}, Status: {status}")

    df.loc[i, 'status'] = status  # Update the status column

# Save the updated DataFrame back to CSV
df.to_csv('apykey.csv', index=False)