赞
踩
获取API Key。由于OpenAI官网在国内无法直接访问,你可能需要使用…dddd,如果想免…和更便宜的使用到gpt可用到我搭建的国内中转中
在Flask应用中,编写一个路由函数,用于接收用户的聊天请求,调用ChatGPT API获取回复。
使用openai库提供的ChatCompletion类发送HTTP请求到ChatGPT API。设置API Key、模型名称、Prompt、温度等参数。
从API响应中提取生成的回复内容,返回给前端页面显示。
由于OpenAI的API接口在国内无法直接访问,需要将请求发送到一个自建的反向代理服务器。本教程使用daily.w-l-h.xyz
作为API代理地址。
目前我的中转支持模型:
示例:
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)
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。