加入豆包AI :doubao-1-5-lite-32k-250115

This commit is contained in:
liuwei
2025-02-28 16:33:27 +08:00
parent 24502ed18c
commit 06718629e7
7 changed files with 165 additions and 7 deletions

138
base/func_doubao.py Normal file
View File

@@ -0,0 +1,138 @@
import requests
import json
import logging
from datetime import datetime
class Doubao():
def __init__(self, conf: dict) -> None:
self.key = conf.get("key")
self.api = conf.get("api")
prompt = conf.get("prompt")
self.model = conf.get("model")
self.LOG = logging.getLogger("doubao")
self.conversation_list = {}
self.system_content_msg = {"role": "system", "content": prompt}
def __repr__(self):
return 'Doubao'
def get_answer(self, question: str, wxid: str) -> str:
# 设置请求头
self.updateMessage(wxid, question, "user")
rsp = ""
try:
headers = {
"Content-Type": "application/json; charset=utf-8",
"Authorization": f"Bearer {self.key}"
}
# 设置请求的payload
data = {
"model": self.model,
"messages": [
self.system_content_msg,
{
"role": "user",
"content": f"{question}"
}
]
}
# 发送POST请求
response = requests.post(self.api, headers=headers, data=json.dumps(data), )
response.encoding = 'utf-8'
# 输出响应内容
print(response.status_code)
# print(response.text)
rsp = extract_content(response.text)
self.updateMessage(wxid, rsp, "assistant")
except Exception as e0:
self.LOG.error(f"发生未知错误:{str(e0)}")
return rsp
def updateMessage(self, wxid: str, question: str, role: str) -> None:
now_time = str(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
time_mk = "当需要回答时间时请直接参考回复:"
# 初始化聊天记录,组装系统信息
if wxid not in self.conversation_list.keys():
question_ = [
self.system_content_msg,
{"role": "system", "content": "" + time_mk + now_time}
]
self.conversation_list[wxid] = question_
# 当前问题
content_question_ = {"role": role, "content": question}
self.conversation_list[wxid].append(content_question_)
for cont in self.conversation_list[wxid]:
if cont["role"] != "system":
continue
if cont["content"].startswith(time_mk):
cont["content"] = time_mk + now_time
# 只存储10条记录超过滚动清除
i = len(self.conversation_list[wxid])
if i > 10:
print("滚动清除微信记录:" + wxid)
# 删除多余的记录,倒着删,且跳过第一个的系统消息
del self.conversation_list[wxid][1]
@staticmethod
def value_check(conf: dict) -> bool:
if conf:
if conf.get("key") and conf.get("api") and conf.get("prompt"):
return True
return False
# 解析JSON
def extract_content(data_string):
try:
data = json.loads(data_string)
# 提取content字段
content = data["choices"][0]["message"].get("content", "")
return content
except json.JSONDecodeError:
print("Invalid JSON")
return None
if __name__ == '__main__':
from configuration import Config
config = Config().DOUBAO
if not config:
exit(0)
chat = Doubao(config)
while True:
q = input(">>> ")
try:
time_start = datetime.now() # 记录开始时间
print(chat.get_answer(q, "Jyunere"))
time_end = datetime.now() # 记录结束时间
print(f"{round((time_end - time_start).total_seconds(), 2)}s") # 计算的时间差为程序的执行时间,单位为秒/s
except Exception as e:
print(e)
# curl
# https: // ark.cn - beijing.volces.com / api / v3 / chat / completions \
# - H
# "Content-Type: application/json" \
# - H
# "Authorization: Bearer b8586595-eb81-483d-8e91-a35cc789729e" \
# - d
# '{
# "model": "doubao-1-5-lite-32k-250115",
# "messages": [
# {"role": "system", "content": "你是人工智能助手."},
# {"role": "user", "content": "常见的十字花科植物有哪些?"}
# ]
#
# }'

View File

@@ -108,4 +108,15 @@ deepseek:
请回复时以以下格式进行返回:
- 问题描述:
- 问题评价:分析问题的提出角度,如(财经、彩票、房产、股票、家居、教育、科技、社会、时尚、时政、体育、星座、游戏、娱乐)等
- 总结经过300个字以内的优化返回返回内容请进行一定程度的结构化方便快速阅读' # 根据需要对角色进行设定
- 总结经过300个字以内的优化返回返回内容请进行一定程度的结构化方便快速阅读' # 根据需要对角色进行设定
doubao:
key: b8586595-eb81-483d-8e91-a35cc789729e
api: https://ark.cn-beijing.volces.com/api/v3/chat/completions # 如果你不知道这是干嘛的,就不要改
model: doubao-1-5-lite-32k-250115 #
prompt: '你是一个信息归纳分析工程师,你根据提问会搜索相关资料。经过信息精炼之后返回内容。
请回复时以以下格式进行返回:
- 问题描述:
- 问题评价:分析问题的提出角度,如(财经、彩票、房产、股票、家居、教育、科技、社会、时尚、时政、体育、星座、游戏、娱乐)等
- 总结经过300个字以内的优化返回返回内容请进行一定程度的结构化方便快速阅读' # 根据需要对角色进行设定

View File

@@ -39,3 +39,4 @@ class Config(object):
self.ZhiPu = yconfig.get("zhipu", {})
self.CLAUDE = yconfig.get("claude", {})
self.DEEPSEEK =yconfig.get("deepseek",{})
self.DOUBAO =yconfig.get("doubao",{})

View File

@@ -11,12 +11,14 @@ class ChatType(IntEnum):
BardAssistant = 5 # Google Bard
ZhiPu = 6 # ZhiPu
CLAUDE = 7 # CLAUDE
DOUBAO = 8 # doubao
@staticmethod
def is_in_chat_types(chat_type: int) -> bool:
if chat_type in [ChatType.TIGER_BOT.value, ChatType.CHATGPT.value,
ChatType.XINGHUO_WEB.value, ChatType.CHATGLM.value,
ChatType.BardAssistant.value, ChatType.ZhiPu.value, ChatType.CLAUDE.value]:
ChatType.BardAssistant.value, ChatType.ZhiPu.value, ChatType.CLAUDE.value,
ChatType.DOUBAO.value]:
return True
return False

View File

@@ -75,7 +75,7 @@ def get_messages(group_id, all_contacts: dict):
'%Y-%m-%d %H:%M:%S')
# 更新 Redis 存储的当前时间
r.set(key, current_date)
# r.set(key, current_date)
with connection.cursor() as cursor:
# 执行查询,获取最近 8 小时的消息

View File

@@ -1,6 +1,7 @@
import requests
import json
# 解析JSON
def extract_content(data_string):
try:
@@ -15,8 +16,9 @@ def extract_content(data_string):
def message_summary(content):
# 设置Authorization和URL
authorization = "46a5674a-e978-491b-a810-5d54605f2c36" # 请替换为真实的Authorization token
url = 'http://127.0.0.1:8080/v1/chat/completions'
authorization = "Bearer b8586595-eb81-483d-8e91-a35cc789729e" # 请替换为真实的Authorization token
url = 'https://ark.cn-beijing.volces.com/api/v3/chat/completions'
# 群聊精华总结生成指令
prompt = """
【基础要求】
@@ -114,10 +116,9 @@ def message_summary(content):
- 个性化适配:根据群成员特点,生成个性化头衔和角色。
"""
data = {
# "stream": True,
"model": "windsurf/gpt4o",
"model": "doubao-1-5-lite-32k-250115",
"messages": [
{
"role": "system",

View File

@@ -9,6 +9,7 @@ from threading import Thread
from datetime import datetime, timedelta
import random
from base.func_doubao import Doubao
from base.func_epic import is_friday, get_free
from base.func_zhipu import ZhiPu
@@ -74,6 +75,8 @@ class Robot(Job):
self.chat = ZhiPu(self.config.ZhiPu)
elif chat_type == ChatType.CLAUDE.value and Claude.value_check(self.config.CLAUDE):
self.chat = Claude(self.config.CLAUDE)
elif chat_type == ChatType.DOUBAO.value and Claude.value_check(self.config.DOUBAO):
self.chat = Doubao(self.config.DOUBAO)
else:
self.LOG.warning("未配置模型")
self.chat = None
@@ -92,6 +95,8 @@ class Robot(Job):
self.chat = ZhiPu(self.config.ZhiPu)
elif Claude.value_check(self.config.CLAUDE):
self.chat = Claude(self.config.CLAUDE)
elif Doubao.value_check(self.config.DOUBAO):
self.chat = Doubao(self.config.DOUBAO)
else:
self.LOG.warning("未配置模型")
self.chat = None