admin管理员组

文章数量:1529452

效果图

他可以做到有记忆的正常对话,不过需要大家自行探索。在Python环境下可以,也可以中文对话

#只能说英文,不能够连续对话
import ujson
import urequests as requests
import network
import time

openai_api_key = "你的CHatGPT——API"
openai_api_base = "https://api.chatanywhere/v1"#用你自己所申请API给出的网址

WiFi_name = "你的WiFi名字"
WiFi_key = "你的WiFi密码"
def do_connect():
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    if not wlan.isconnected():
        print('正在连接WiFi...')
        wlan.connect(WiFi_name , WiFi_key )
        i = 1
        while not wlan.isconnected():
            print("正在链接...{}".format(i))
            i += 1
            time.sleep(1)
    print('network config:', wlan.ifconfig())
    
def send_request(input_message):
    message = {"role": "user", "content": input_message}
    payload = {
        "model": "gpt-3.5-turbo",
        "messages": [message]
    }
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Bearer {openai_api_key}"
    }
    response = requests.post(openai_api_base + "/chat/completions", json=payload, headers=headers)
    return response

# 循环接收用户输入并回复
do_connect()
while True:
    input_message = input("User: ")  # 接收用户输入
    print (input_message)
    response = send_request(input_message)  # 发送请求
    completion = ujson.loads(response.text)['choices'][0]['message']['content']  # 获取 AI 的回复
    print("AI: " + completion)  # 输出给用户

该代码暂时只能完成单次对话,不具备记忆功能,不能使用中文,会报错。我不知道怎么解决,因为要准备期末考试,没时间找解决方法,有大佬可以教教我。

在该代码的基础上可以进行语音转文字以及文字转语音等操作,实现对话机器人,除此以外还可以加入显示屏,制作自己的桌面机器人。自己动手比买现成还玩多了。

本文标签: 英文chatGPT