获取低成本GPT-4接口,构建你的AI应用!

国内如何调用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)
  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

暴风雨544

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值