Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit76ff9d5

Browse files
committed
feat!: handle openai api error
1 parentfcf5381 commit76ff9d5

File tree

3 files changed

+75
-7
lines changed

3 files changed

+75
-7
lines changed

‎dive_mcp_host/httpd/routers/models.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,17 @@ class InteractiveContent(BaseModel):
158158
content:AuthenticationRequiredContent
159159

160160

161+
classErrorContent(BaseModel):
162+
"""Error content."""
163+
164+
message:str
165+
type:str
166+
167+
model_config=ConfigDict(
168+
extra="allow",
169+
)
170+
171+
161172
classStreamMessage(BaseModel):
162173
"""Stream message."""
163174

@@ -175,6 +186,7 @@ class StreamMessage(BaseModel):
175186
str
176187
|list[ToolCallsContent]
177188
|ToolResultContent
189+
|ErrorContent
178190
|ChatInfoContent
179191
|MessageInfoContent
180192
|InteractiveContent

‎dive_mcp_host/httpd/routers/utils.py‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
)
2323
fromlangchain_core.messages.toolimportToolMessage
2424
fromlangchain_core.output_parsersimportStrOutputParser
25+
fromopenaiimportAPIErrorasOpenAIAPIError
2526
frompydanticimportBaseModel
2627
fromstarlette.datastructuresimportState
2728

@@ -51,6 +52,7 @@
5152
fromdive_mcp_host.httpd.routers.modelsimport (
5253
AuthenticationRequiredContent,
5354
ChatInfoContent,
55+
ErrorContent,
5456
InteractiveContent,
5557
MessageInfoContent,
5658
StreamMessage,
@@ -109,9 +111,18 @@ async def __aexit__(self, exc_type, exc_val, exc_tb) -> None: # noqa: ANN001
109111
importtraceback
110112

111113
logger.error(traceback.format_exception(exc_type,exc_val,exc_tb))
114+
content=ErrorContent(message=str(exc_val),type="thread-query-error")
115+
116+
if (error:=getattr(exc_val,"error",None))andisinstance(
117+
error,OpenAIAPIError
118+
):
119+
content.message=error.message
120+
content.type=error.type
121+
content.code=error.code
122+
112123
self._exit_message=StreamMessage(
113124
type="error",
114-
content=f"<thread-query-error>{exc_val}</thread-query-error>",
125+
content=content,
115126
).model_dump_json(by_alias=True)
116127

117128
self.done=True
@@ -356,7 +367,7 @@ async def handle_chat(
356367
),
357368
)
358369

359-
ifnotoriginal_msg_exist:
370+
ifquery_inputandnotoriginal_msg_exist:
360371
awaitdb.create_message(
361372
NewMessage(
362373
chatId=chat_id,
@@ -584,7 +595,9 @@ async def _stream_text_msg(self, message: AIMessage) -> None:
584595
awaitself.stream.write(
585596
StreamMessage(
586597
type="error",
587-
content="stop_reason: max_tokens",
598+
content=ErrorContent(
599+
message="stop_reason: max_tokens",type="max_tokens"
600+
),
588601
)
589602
)
590603

‎tests/httpd/routers/test_chat.py‎

Lines changed: 47 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
fromfastapi.testclientimportTestClient
1111
fromlangchain_core.messagesimportAIMessage,AIMessageChunk,ToolCall
1212

13+
fromdive_mcp_host.host.errorsimportThreadQueryError
1314
fromdive_mcp_host.httpd.routers.chatimportERROR_MSG_ID,DataResult
1415
fromdive_mcp_host.httpd.routers.modelsimportSortBy
1516
fromdive_mcp_host.httpd.serverimportDiveHostAPI
@@ -1163,10 +1164,9 @@ def mock_process_chat(*args, **kwargs):
11631164
has_chat_info=True
11641165
ifinner_json["type"]=="error":
11651166
has_error=True
1166-
assert (
1167-
inner_json["content"]
1168-
=="<thread-query-error>an test error</thread-query-error>"
1169-
)
1167+
error_content=inner_json["content"]
1168+
asserterror_content["message"]=="an test error"
1169+
asserterror_content["type"]=="thread-query-error"
11701170

11711171
asserthas_chat_info
11721172
asserthas_error
@@ -1209,3 +1209,46 @@ def test_chat_with_tool_progress(
12091209
has_progress=True
12101210

12111211
asserthas_progress
1212+
1213+
1214+
deftest_chat_with_openai_error(test_client,monkeypatch):
1215+
"""Test the chat endpoint with an OpenAI error."""
1216+
client,app=test_client
1217+
fromopenaiimportAPIErrorasOpenAIAPIError
1218+
1219+
defmock_process_chat(*args,**kwargs):
1220+
raiseOpenAIAPIError(
1221+
message="an test error",
1222+
request=None,
1223+
body={
1224+
"type":"insufficient_quota",
1225+
"code":"insufficient_quota",
1226+
},
1227+
)
1228+
1229+
monkeypatch.setattr(
1230+
"dive_mcp_host.models.fake.FakeMessageToolModel._generate",
1231+
mock_process_chat,
1232+
)
1233+
1234+
response=client.post(
1235+
"/api/chat",data={"chatId":"test_chat_id","message":"Calculate 2+2"}
1236+
)
1237+
assertresponse.status_code==SUCCESS_CODE
1238+
1239+
has_chat_info=False
1240+
has_error=False
1241+
1242+
forjson_objinhelper.extract_stream(response.text):
1243+
assert"message"injson_obj
1244+
ifjson_obj["message"]:
1245+
inner_json=json.loads(json_obj["message"])
1246+
ifinner_json["type"]=="chat_info":
1247+
has_chat_info=True
1248+
ifinner_json["type"]=="error":
1249+
has_error=True
1250+
error_content=inner_json["content"]
1251+
asserterror_content["type"]=="insufficient_quota"
1252+
1253+
asserthas_chat_info
1254+
asserthas_error

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp