python对接openai的api,使用chatgpt再也不犯愁了

import requests

def generate_text(prompt, model, api_key):
    url = "https://api.openai.com/v1/engines/text-davinci-002/jobs"

    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {api_key}"
    }

    data = {
        "prompt": prompt,
        "max_tokens": 100,
        "temperature": 0.5,
        "model": model
    }

    response = requests.post(url, headers=headers, json=data)
    if response.status_code == 200:
        response_json = response.json()
        return response_json["choices"][0]["text"]
    else:
        raise Exception(f"Request failed with status code {response.status_code}")

使用方式:

需要将api_key换成你自己的。

prompt = "What is the meaning of life?"
model = "text-davinci-002"
api_key = "YOUR_API_KEY"

generated_text = generate_text(prompt, model, api_key)
print(generated_text)

 

posted @ 2023-02-01 23:04  无恙大势  阅读(1893)  评论(1)    收藏  举报