Skip to content

Commit

Permalink
perf: 完善openai异常处理
Browse files Browse the repository at this point in the history
  • Loading branch information
RockChinQ committed Feb 1, 2024
1 parent a9d9211 commit 7026abe
Show file tree
Hide file tree
Showing 14 changed files with 1,195 additions and 9 deletions.
Binary file added HiraginoSansGB.ttc
Binary file not shown.
2 changes: 2 additions & 0 deletions pkg/core/controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ async def _check_output(self, query: entities.Query, result: pipeline_entities.S
self.ap.logger.debug(result.debug_notice)
if result.console_notice:
self.ap.logger.info(result.console_notice)
if result.error_notice:
self.ap.logger.error(result.error_notice)

async def _execute_from_stage(
self,
Expand Down
3 changes: 3 additions & 0 deletions pkg/pipeline/entities.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,4 +35,7 @@ class StageProcessResult(pydantic.BaseModel):
"""只要设置了就会输出到控制台"""

debug_notice: typing.Optional[str] = ''

error_notice: typing.Optional[str] = ''


9 changes: 9 additions & 0 deletions pkg/pipeline/process/handlers/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import typing
import time
import traceback

import mirai

Expand Down Expand Up @@ -78,6 +79,14 @@ async def handle(
result_type=entities.ResultType.CONTINUE,
new_query=query
)
except Exception as e:
yield entities.StageProcessResult(
result_type=entities.ResultType.INTERRUPT,
new_query=query,
user_notice=self.ap.tips_mgr.data['alter_tip_message'] if self.ap.cfg_mgr.data['hide_exce_info_to_user'] else f'{e}',
error_notice=f'{e}',
debug_notice=traceback.format_exc()
)
finally:
query.session.using_conversation.messages.append(query.user_message)
query.session.using_conversation.messages.extend(query.resp_messages)
Expand Down
24 changes: 22 additions & 2 deletions pkg/provider/requester/apis/chatcmpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@
import asyncio
import typing
import json
from typing import AsyncGenerator

import openai
import openai.types.chat.chat_completion as chat_completion

from .. import api, entities
from pkg.provider.entities import Message

from .. import api, entities, errors
from ....core import entities as core_entities
from ... import entities as llm_entities
from ...tools import entities as tools_entities
Expand Down Expand Up @@ -69,7 +72,7 @@ async def _closure(

return message

async def request(
async def _request(
self, query: core_entities.Query
) -> typing.AsyncGenerator[llm_entities.Message, None]:
"""请求"""
Expand Down Expand Up @@ -116,3 +119,20 @@ async def request(
pending_tool_calls = msg.tool_calls

req_messages.append(msg.dict(exclude_none=True))

async def request(self, query: core_entities.Query) -> AsyncGenerator[Message, None]:
try:
async for msg in self._request(query):
yield msg
except asyncio.TimeoutError:
raise errors.RequesterError('请求超时')
except openai.BadRequestError as e:
raise errors.RequesterError(f'请求错误: {e.message}')
except openai.AuthenticationError as e:
raise errors.RequesterError(f'无效的 api-key: {e.message}')
except openai.NotFoundError as e:
raise errors.RequesterError(f'请求路径错误: {e.message}')
except openai.RateLimitError as e:
raise errors.RequesterError(f'请求过于频繁: {e.message}')
except openai.APIError as e:
raise errors.RequesterError(f'请求错误: {e.message}')
5 changes: 5 additions & 0 deletions pkg/provider/requester/errors.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
class RequesterError(Exception):
"""Base class for all Requester errors."""

def __init__(self, message: str):
super().__init__("模型请求失败: "+message)
10 changes: 10 additions & 0 deletions test.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
<html>
<head>
<title>Test</title>
</head>
<body>
<h1>Test</h1>
<p>Test</p>
<p>This is a test for QChatGPT.</p>
</body>
</html>
25 changes: 25 additions & 0 deletions tests/models_api_compability/compability.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

import os

import openai

client = openai.Client(
api_key=os.environ["OPENAI_API_KEY"],
)

openai.proxies = {
'http': 'http://127.0.0.1:7890',
'https': 'http://127.0.0.1:7890',
}

resp = client.chat.completions.create(
model="code-davinci-002",
messages=[
{
"role": "user",
"content": "Hello, how are you?",
}
]
)

print(resp)
6 changes: 3 additions & 3 deletions tests/plugin_examples/auto_approval/main.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from mirai import Mirai

import pkg.qqbot.manager
import pkg.platform.manager
from pkg.plugin.models import *
from pkg.plugin.host import PluginHost

Expand All @@ -23,13 +23,13 @@ class AutoApproval(Plugin):
# 插件加载时触发
def __init__(self, plugin_host: PluginHost):
qqmgr = plugin_host.get_runtime_context().get_qqbot_manager()
assert isinstance(qqmgr, pkg.qqbot.manager.QQBotManager)
assert isinstance(qqmgr, pkg.platform.manager.PlatformManager)
self.bot = qqmgr.bot

# 向YiriMirai注册 加群申请 事件处理函数
@qqmgr.bot.on(MemberJoinRequestEvent)
async def process(event: MemberJoinRequestEvent):
assert isinstance(qqmgr, pkg.qqbot.manager.QQBotManager)
assert isinstance(qqmgr, pkg.platform.manager.PlatformManager)
if event.group_id == __group_id__:
if any([x in event.message for x in __application_contains__]):
logging.info("自动同意加群申请")
Expand Down
Loading

0 comments on commit 7026abe

Please sign in to comment.