Python如何对接文心一言
引言
文心一言是百度研发的Ai机器,能够与人对话互动,回答问题,协助创作,高效便捷地帮助人们获取信息、知识和灵感。
申请Api Key
前往百度智能云
https://console.bce.baidu.com/qianfan/ais/console/applicationConsole/application
登录并创建应用,拿到需要的API Key和Secret Key:

编辑源代码
修改参数:
api_key:替换成自己的
secret_key:替换自己的
redis的配置是用于保存access_token,该token通过接口获取默认有效期为30天。可自行决定是否需要redis的配合。
import requests
import json
import redis
# 文心一言配置
api_key = "你的api_key"
secret_key = "你的secret_key"
# redis配置
redis_host = "127.0.0.1"
redis_port = 6379
redis_db = 0
class ChatBot:
def __init__(self, api_key, secret_key):
self.api_key = api_key
self.secret_key = secret_key
self.message_history = []
self.redis_client = redis.Redis(host=redis_host, port=redis_port, db=redis_db)
self.chat_url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions?access_token={}"
def get_token(self):
if self.redis_client.exists('access_token'):
return self.redis_client.get('access_token').decode()
else:
get_access_token_url = ("https://aip.baidubce.com/oauth/2.0/token?"
"client_id={}"
"&client_secret={}"
"&grant_type=client_credentials").format(
self.api_key, self.secret_key)
response = requests.get(get_access_token_url)
self.redis_client.setex('access_token', response.json()['expires_in'], response.json()['access_token'])
return response.json()['access_token']
def check_tokens(self, total_tokens):
if total_tokens > 4800:
self.message_history = self.message_history[len(self.message_history) / 2:]
def add_chat_history(self, message):
self.message_history.append(message)
payload = json.dumps({
"messages": self.message_history
})
return payload
def send_message(self, message):
payload = self.add_chat_history({
"role": "user",
"content": message
})
headers = {'Content-Type': 'application/json'}
response = requests.post(self.chat_url.format(self.get_token()), headers=headers, data=payload)
self.add_chat_history({
"role": "assistant",
"content": response.json()['result']
})
return response.json()['result']
if __name__ == '__main__':
chatbot = ChatBot(api_key, secret_key)
while True:
message = input("you: ")
if message.strip() != "":
reply = chatbot.send_message(message)
print("bot: ", reply)思维扩展
通过上面的代码逻辑,我们是否可以尝试:通过麦克风获取用户的语音指令转成文字,然后通过文心一言拿到返回的内容再生成语音进行播放。是不是就成了智能语音助手🤔
以上就是Python如何对接文心一言的详细内容,更多关于Python对接文心一言的资料请关注脚本之家其它相关文章!
相关文章
Python如何使用struct.unpack处理二进制文件
这篇文章主要介绍了Python如何使用struct.unpack处理二进制文件问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教2024-02-02
Python实现添加或移除PowerPoint中的背景图和背景颜色
在处理 PowerPoint 演示文稿时,我们常常会遇到需要为幻灯片添加或移除背景的情况,本文将介绍如何使用 Python 在 PowerPoint 中添加或移除背景,并提供详细步骤和代码示例,帮助你快速上手2026-05-05
torchxrayvision包安装过程(附pytorch1.6cpu版安装)
这篇文章主要介绍了torchxrayvision包安装过程(附pytorch1.6cpu版安装),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-08-08


最新评论