当前位置:   article > 正文

国内如何调用ChatGPT API接口和获取GPT4apikey_chatgpt apikey 中转 csdn

chatgpt apikey 中转 csdn

国内如何调用ChatGPT API接口和获取的GPT4apikey

获取API Key。由于OpenAI官网在国内无法直接访问,你可能需要使用…dddd,如果想免…和更便宜的使用到gpt可用到我搭建的国内中转中

调用ChatGPT API

  1. 在Flask应用中,编写一个路由函数,用于接收用户的聊天请求,调用ChatGPT API获取回复。

  2. 使用openai库提供的ChatCompletion类发送HTTP请求到ChatGPT API。设置API Key、模型名称、Prompt、温度等参数。

  3. 从API响应中提取生成的回复内容,返回给前端页面显示。

  4. 由于OpenAI的API接口在国内无法直接访问,需要将请求发送到一个自建的反向代理服务器。本教程使用daily.w-l-h.xyz作为API代理地址。

选择模型

目前我的中转支持模型:

  • GPT (基本全部模型)
  • midjourney
  • stable-diffusion
  • dall-e-3/2

示例:
在这里插入图片描述

[插入一张代码编辑器截图,展示调用API的Python代码]

import numpy as np
import requests
import json

content_all = ''
def get_chat_gpt_response(prompt):
    global content_all
    url = "https://daily.w-l-h.xyz/v1/chat/completions"
    headers = {
        "Authorization": "Bearer apikey(需要获取:https://daily.w-l-h.xyz)",
        "Content-Type": "application/json"
    }
    data = {
        "model": "gpt-3.5-turbo",
        "stream":True,
        "messages": [{"role": "user", "content": prompt}],
    }

    response = requests.post(url, headers=headers, json=data)
    for line in response.iter_lines():
        if line:
            decoded_line = line.decode('utf-8')
            if decoded_line == 'data: [DONE]':
                break
            if decoded_line.startswith('data: '):
                data_str = decoded_line.replace('data: ', '')
                data_json = json.loads(data_str)
                content = data_json['choices'][0]['delta'].get('content', '')
                if content == '':
                    continue
                print(content)
                content_all += content

resp = get_chat_gpt_response('水仙花代码python')
print(content_all)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/AllinToyou/article/detail/513681
推荐阅读
相关标签
  

闽ICP备14008679号