You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
gcgj-dify-1.7.0/api/core/plugin/backwards_invocation/base.py

20 lines
731 B
Python

import json
from collections.abc import Generator
from pydantic import BaseModel
class BaseBackwardsInvocation:
@classmethod
def convert_to_event_stream(cls, response: Generator[BaseModel | dict, None, None] | BaseModel | dict):
if isinstance(response, Generator):
for chunk in response:
if isinstance(chunk, BaseModel):
yield chunk.model_dump_json().encode() + b'\n\n'
else:
yield json.dumps(chunk).encode() + b'\n\n'
else:
if isinstance(response, BaseModel):
yield response.model_dump_json().encode() + b'\n\n'
else:
yield json.dumps(response).encode() + b'\n\n'