Skip to content

Commit 9c324aa

Browse files
authored
optimize: replace json.loads with TypeAdapter for JSON unmarshaling (#103)
* refactor: replace json.loads with TypeAdapter for JSON validation in request readers and model - Updated JSON parsing in BackwardsInvocation, StdioRequestReader, and TCPReaderWriter to use TypeAdapter for improved validation. - Enhanced error handling in OAICompatLargeLanguageModel by replacing json.loads with TypeAdapter, ensuring better compliance with expected JSON schema. * fix: linter
1 parent f714fc9 commit 9c324aa

File tree

4 files changed

+14
-13
lines changed

4 files changed

+14
-13
lines changed

python/dify_plugin/core/runtime.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
1-
import json
21
import uuid
32
from abc import ABC
43
from collections.abc import Generator, Mapping
54
from concurrent.futures import ThreadPoolExecutor
65
from enum import Enum
7-
from typing import Generic, Optional, TypeVar, Union
6+
from typing import Any, Generic, Optional, TypeVar, Union
87

98
import httpx
10-
from pydantic import BaseModel
9+
from pydantic import BaseModel, TypeAdapter
1110
from yarl import URL
1211

1312
from dify_plugin.config.config import InstallMethod
@@ -276,7 +275,7 @@ def generator():
276275
if not line:
277276
continue
278277

279-
data = json.loads(line)
278+
data = TypeAdapter(dict[str, Any]).validate_json(line)
280279
yield PluginInStreamBase(
281280
session_id=data["session_id"],
282281
event=PluginInStreamEvent.value_of(data["event"]),

python/dify_plugin/core/server/stdio/request_reader.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,9 @@
11
import sys
22
from collections.abc import Generator
3-
from json import loads
3+
from typing import Any
44

55
from gevent.os import tp_read
6+
from pydantic import TypeAdapter
67

78
from dify_plugin.core.entities.plugin.io import (
89
PluginInStream,
@@ -37,7 +38,7 @@ def _read_stream(self) -> Generator[PluginInStream, None, None]:
3738
lines = lines[:-1]
3839
for line in lines:
3940
try:
40-
data = loads(line)
41+
data = TypeAdapter(dict[str, Any]).validate_json(line)
4142
yield PluginInStream(
4243
session_id=data["session_id"],
4344
event=PluginInStreamEvent.value_of(data["event"]),

python/dify_plugin/core/server/tcp/request_reader.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@
55
import socket as native_socket
66
import time
77
from collections.abc import Callable, Generator
8-
from json import loads
98
from threading import Lock
10-
from typing import Optional
9+
from typing import Any, Optional
1110

1211
from gevent import sleep
1312
from gevent import socket as gevent_socket
1413
from gevent.select import select
14+
from pydantic import TypeAdapter
1515

1616
from dify_plugin.core.entities.message import InitializeMessage
1717
from dify_plugin.core.entities.plugin.io import (
@@ -190,7 +190,7 @@ def _read_stream(self) -> Generator[PluginInStream, None, None]:
190190
lines = lines[:-1]
191191
for line in lines:
192192
try:
193-
data = loads(line)
193+
data = TypeAdapter(dict[str, Any]).validate_json(line)
194194
chunk = PluginInStream(
195195
session_id=data["session_id"],
196196
event=PluginInStreamEvent.value_of(data["event"]),

python/dify_plugin/interfaces/model/openai_compatible/llm.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,11 @@
33
import logging
44
from collections.abc import Generator
55
from decimal import Decimal
6-
from typing import Optional, Union, cast
6+
from typing import Any, Optional, Union, cast
77
from urllib.parse import urljoin
88

99
import requests
10+
from pydantic import TypeAdapter, ValidationError
1011

1112
from dify_plugin.entities import I18nObject
1213
from dify_plugin.entities.model import (
@@ -356,7 +357,7 @@ def _generate(
356357
if not json_schema:
357358
raise ValueError("Must define JSON Schema when the response format is json_schema")
358359
try:
359-
schema = json.loads(json_schema)
360+
schema = TypeAdapter(dict[str, Any]).validate_json(json_schema)
360361
except Exception as exc:
361362
raise ValueError(f"not correct json_schema format: {json_schema}") from exc
362363
model_parameters.pop("json_schema")
@@ -517,9 +518,9 @@ def _handle_generate_stream_response(
517518
continue
518519

519520
try:
520-
chunk_json: dict = json.loads(decoded_chunk)
521+
chunk_json: dict = TypeAdapter(dict[str, Any]).validate_json(decoded_chunk)
521522
# stream ended
522-
except json.JSONDecodeError:
523+
except ValidationError:
523524
yield self._create_final_llm_result_chunk(
524525
index=chunk_index + 1,
525526
message=AssistantPromptMessage(content=""),

0 commit comments

Comments
 (0)