-
Notifications
You must be signed in to change notification settings - Fork 9.2k
feat: support Coze #2227
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
LarryZhu-dev
wants to merge
2
commits into
zhayujie:master
Choose a base branch
from
LarryZhu-dev:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
feat: support Coze #2227
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,97 @@ | ||
# encoding:utf-8 | ||
|
||
import requests | ||
import json | ||
from common import const | ||
from bot.bot import Bot | ||
from bot.session_manager import SessionManager | ||
from bridge.context import ContextType | ||
from bridge.reply import Reply, ReplyType | ||
from common.log import logger | ||
from config import conf | ||
from bot.coze.coze_session import CozeSession | ||
|
||
COZE_API_KEY = conf().get("coze_api_key") | ||
COZE_BOT_ID = conf().get("coze_bot_id") | ||
|
||
class CozeBot(Bot): | ||
|
||
def __init__(self): | ||
super().__init__() | ||
self.sessions = SessionManager(CozeSession, model="coze") | ||
|
||
def reply(self, query, context=None): | ||
# acquire reply content | ||
if context and context.type: | ||
if context.type == ContextType.TEXT: | ||
# logger.info("[COZE] query={}".format(query)) | ||
session_id = context["session_id"] | ||
reply = None | ||
if query == "#清除记忆": | ||
self.sessions.clear_session(session_id) | ||
reply = Reply(ReplyType.INFO, "记忆已清除") | ||
elif query == "#清除所有": | ||
self.sessions.clear_all_session() | ||
reply = Reply(ReplyType.INFO, "所有人记忆已清除") | ||
else: | ||
session = self.sessions.session_query(query, session_id) | ||
result = self.reply_text(query) | ||
total_tokens, completion_tokens, reply_content = ( | ||
result["total_tokens"], | ||
result["completion_tokens"], | ||
result["content"], | ||
) | ||
logger.debug( | ||
"[COZE] new_query={}, session_id={}, reply_cont={}, completion_tokens={}".format(session.messages, session_id, reply_content, completion_tokens) | ||
) | ||
|
||
if total_tokens == 0: | ||
reply = Reply(ReplyType.ERROR, reply_content) | ||
else: | ||
self.sessions.session_reply(reply_content, session_id, total_tokens) | ||
reply = Reply(ReplyType.TEXT, reply_content) | ||
return reply | ||
elif context.type == ContextType.IMAGE_CREATE: | ||
ok, retstring = self.create_img(query, 0) | ||
reply = None | ||
if ok: | ||
reply = Reply(ReplyType.IMAGE_URL, retstring) | ||
else: | ||
reply = Reply(ReplyType.ERROR, retstring) | ||
return reply | ||
|
||
def reply_text(self, session: str, retry_count=0): | ||
try: | ||
# logger.info("[COZE] model={}".format(session.model)) | ||
url = "https://api.coze.cn/open_api/v2/chat" | ||
headers = { | ||
'Content-Type': 'application/json', | ||
'Authorization': 'Bearer ' + COZE_API_KEY | ||
} | ||
payload = { | ||
'query': session, | ||
"conversation_id": "keep", | ||
'user': "keep", | ||
"bot_id": COZE_BOT_ID, | ||
"stream": False | ||
} | ||
print(payload["query"]) | ||
response = requests.request("POST", url, headers=headers, data=json.dumps(payload)) | ||
response_text = json.loads(response.text) | ||
# logger.info(f"[COZE] response text={response_text}") | ||
res_content = response_text["messages"][1]["content"] | ||
total_tokens = 1 | ||
completion_tokens = 1 | ||
# logger.info("[COZE] reply={}".format(res_content)) | ||
return { | ||
"total_tokens": total_tokens, | ||
"completion_tokens": completion_tokens, | ||
"content": res_content, | ||
} | ||
except Exception as e: | ||
need_retry = retry_count < 2 | ||
logger.warn("[COZE] Exception: {}".format(e)) | ||
need_retry = False | ||
self.sessions.clear_session(session.session_id) | ||
result = {"total_tokens": 0, "completion_tokens": 0, "content": "出错了: {}".format(e)} | ||
return result |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
from bot.session_manager import Session | ||
from common.log import logger | ||
|
||
""" | ||
e.g. [ | ||
{"role": "user", "content": "Who won the world series in 2020?"}, | ||
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."}, | ||
{"role": "user", "content": "Where was it played?"} | ||
] | ||
""" | ||
|
||
|
||
class CozeSession(Session): | ||
def __init__(self, session_id, system_prompt=None, model="gpt-3.5-turbo"): | ||
super().__init__(session_id, system_prompt) | ||
self.model = model | ||
# 百度文心不支持system prompt | ||
# self.reset() | ||
|
||
def discard_exceeding(self, max_tokens, cur_tokens=None): | ||
precise = True | ||
try: | ||
cur_tokens = self.calc_tokens() | ||
except Exception as e: | ||
precise = False | ||
if cur_tokens is None: | ||
raise e | ||
logger.debug("Exception when counting tokens precisely for query: {}".format(e)) | ||
while cur_tokens > max_tokens: | ||
if len(self.messages) >= 2: | ||
self.messages.pop(0) | ||
self.messages.pop(0) | ||
else: | ||
logger.debug("max_tokens={}, total_tokens={}, len(messages)={}".format(max_tokens, cur_tokens, len(self.messages))) | ||
break | ||
if precise: | ||
cur_tokens = self.calc_tokens() | ||
else: | ||
cur_tokens = cur_tokens - max_tokens | ||
return cur_tokens | ||
|
||
def calc_tokens(self): | ||
return num_tokens_from_messages(self.messages, self.model) | ||
|
||
|
||
def num_tokens_from_messages(messages, model): | ||
"""Returns the number of tokens used by a list of messages.""" | ||
tokens = 0 | ||
for msg in messages: | ||
# 官方token计算规则暂不明确: "大约为 token数为 "中文字 + 其他语种单词数 x 1.3" | ||
# 这里先直接根据字数粗略估算吧,暂不影响正常使用,仅在判断是否丢弃历史会话的时候会有偏差 | ||
tokens += len(msg["content"]) | ||
return tokens |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.