【GPT】Python使用request方法获取

说明

通常可以直接使用import openai直接使用api,在某些特殊情景,限制了第三方库的使用,可以考虑直接使用request

示例代码

import requests
# Your OpenAI API Key
api_key = "6"
# The text prompt you want to generate a response
input_prompt = input("输入需要跟chat AI的聊天内容:")
prompt = input_prompt
# The URL for OpenAI's API
url = "https://qpi.openai.com/v1/chat/completions"
# The headers for the API request
headers = {
    
    
  "Content-Type": "application/json",
  "Authorization": f"Bearer {
      
      api_key}"
}
data = {
    
    
  "model":"gpt-3.5-turbo",
  "messages": [{
    
    "role":"user","content":prompt}],
  "max_tokens":800,
  "temperature":0.5,
  "frequency_penalty":0,
  "presence_penalty":0
}
# Make the API request
response = requests.post(url, headers=headers, json=data)
# Check if the request was successful
if response.status_code == 200:
  # Extract the generated text from the response
  generated_text = response.json()['choices'][0]['message']['content']
  usage = response.json()['choices'][0]['usage']
  print(generated_text)
  print(usage)
else:
  # Handle the error
  print(f"Request failed with status code {
      
      response.status_code}")

猜你喜欢

转载自blog.csdn.net/qq_25262697/article/details/129661936