文心一言4.0(ERNIE-Bot-4)申请方法及简单调用代码示例

10月17日过后,估计很多人会看到类似的新闻,如图:

我看到这则新闻也是觉得非常感兴趣,于是本着“百闻不如一见”的实事求是的态度检索如何申请,没想到还真找到了ERNIE-Bot-4(俗称:文心一言4.0)的申请入口,如下:

  • 体验地址

企业用户/个人开发者:填写表单申请开通:百度智能云千帆大模型平台邀您测试 审核通过后即可免费调用千帆文心4.0API

  • API文档

ERNIE-Bot-4 – 千帆大模型平台 | 百度智能云文档


 

我本人是填写表单申请一天左右收到了“百度智能云”的短信通知我通过了申请,老样子,先上图:

通过之后即使不是很擅长调用接口来测试模型质量,百度智能云也会提供在线测试的入口方便我们测试,如图:

也是可以外接知识库或者调整各种参数的,还算便利,也提供了prompt模板作为参考。

如果我们不想每次都打开网站去测试,也可以在本地进行调用来测试,下面以python为例:

先在百度智能云控制台“应用接入”里创建应用,内容自己发挥,主要是我们需要的AppID,API Key以及Secret Key。

当然,我们需要开通一下对应接口的付费,我这里是只开通了ERNIE-Bot-4的付费,0.12¥/千tokens,跟其他模型比可能有点小贵,自费开通,为爱发电哈哈。

好了,万事具备,下面就是一个简单的多轮对话代码示例:

import requests
import json
import os
import pickle


class WenXinYiYanChat:
    def __init__(self, api_key, secret_key, user_id="这里输入你的APPID", file_name="history.pkl"):
        # 初始化方法,用于设置API密钥、用户ID、文件名等
        self.api_key = api_key
        self.secret_key = secret_key
        self.user_id = user_id
        self.file_name = file_name
        self.access_token = self.get_access_token()
        self.messages = []
        self.is_paused = False

    def get_access_token(self):
        # 获取access_token,用于后续的API调用
        url = "https://aip.baidubce.com/oauth/2.0/token"
        params = {
            'grant_type': 'client_credentials',
            'client_id': self.api_key,
            'client_secret': self.secret_key
        }
        headers = {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
        response = requests.post(url, headers=headers, params=params)
        return response.json().get("access_token")

    def chat(self, user_message):
        # 进行对话的主要方法
        if self.is_paused:
            return "对话目前已暂停。请先恢复对话再继续。"

        self.messages.append({"role": "user", "content": user_message})

        payload = {
            "messages": self.messages,
            "user_id": self.user_id,
            "temperature": 0.95,
            "top_p": 0.8,
            "penalty_score": 1.0
        }

        url = f"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro?access_token={self.access_token}"
        headers = {'Content-Type': 'application/json'}
        response = requests.post(url, headers=headers, data=json.dumps(payload))
        assistant_message = response.json().get("result")
        self.messages.append({"role": "assistant", "content": assistant_message})
        return assistant_message

    def clear_history(self):
        # 清除对话历史记录
        self.messages = []

    def get_chat_history(self):
        # 获取对话历史记录
        return self.messages

    def save_history(self):
        # 将对话历史记录保存到文件中
        with open(self.file_name, "wb") as f:
            pickle.dump(self.messages, f)

    def load_history(self):
        # 从文件中读取对话历史记录
        if os.path.exists(self.file_name):
            with open(self.file_name, "rb") as f:
                self.messages = pickle.load(f)

    def pause_chat(self):
        # 暂停对话,并保存对话历史记录
        self.is_paused = True
        self.save_history()

    def resume_chat(self):
        # 恢复对话,并加载对话历史记录
        self.is_paused = False
        self.load_history()


if __name__ == "__main__":
    api_key = input("请输入您的API Key: ")
    secret_key = input("请输入您的Secret Key: ")
    '''
    如果不想每次都输入这两个KEY就把上面两行注释掉,去除下面两行的注释
    '''
    # api_key = "在这里输入你的API Key"
    # secret_key = "在这里输入你的Secret Key"
    chat_instance = WenXinYiYanChat(api_key, secret_key)

    while True:
        user_message = input("靓仔: ")

        # 添加控制语句,用于实现功能
        if user_message.lower() == "暂停":
            chat_instance.pause_chat()
            print("对话已暂停。")
        elif user_message.lower() == "恢复":
            chat_instance.resume_chat()
            print("对话已恢复。")
        elif user_message.lower() == "清除":
            chat_instance.clear_history()
            print("对话历史记录已清除。")
        elif user_message.lower() == "查看":
            history = chat_instance.get_chat_history()
            print("对话历史记录如下:")
            for message in history:
                print(message["role"] + ": " + message["content"])
        elif user_message.lower() == "载入":
            chat_instance.load_history()
            print("对话历史记录已载入。")
        elif user_message.lower() in ["exit", "退出"]:
            break
        else:
            response = chat_instance.chat(user_message)
            print("文心一言4.0: ", response)

以上是一个非常简陋的多轮对话代码示例,仅供测试接口,佬轻喷,虽然国外的模型质量很高,价格也便宜,国内模型开发的开源项目确实少之又少,但还是希望有更多人能够关注国内模型,众人拾柴火焰高,一同开发出更多更优秀的项目,最后,上效果图:

如果有友友开发出了更好的项目或者发现了更好的项目,记得踢我,一起学习!

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
社会演员多的头像社会演员多普通用户
上一篇 2023年12月5日
下一篇 2023年12月5日

相关推荐