2024-04-08 18:51:46 +08:00
|
|
|
import json
|
|
|
|
from typing import Optional
|
|
|
|
|
|
|
|
from core.app.app_config.entities import (
|
|
|
|
DatasetEntity,
|
|
|
|
DatasetRetrieveConfigEntity,
|
|
|
|
EasyUIBasedAppConfig,
|
|
|
|
ExternalDataVariableEntity,
|
|
|
|
ModelConfigEntity,
|
|
|
|
PromptTemplateEntity,
|
|
|
|
VariableEntity,
|
|
|
|
)
|
|
|
|
from core.app.apps.agent_chat.app_config_manager import AgentChatAppConfigManager
|
|
|
|
from core.app.apps.chat.app_config_manager import ChatAppConfigManager
|
|
|
|
from core.app.apps.completion.app_config_manager import CompletionAppConfigManager
|
2024-08-13 14:44:10 +08:00
|
|
|
from core.file.file_obj import FileExtraConfig
|
2024-04-08 18:51:46 +08:00
|
|
|
from core.helper import encrypter
|
|
|
|
from core.model_runtime.entities.llm_entities import LLMMode
|
|
|
|
from core.model_runtime.utils.encoders import jsonable_encoder
|
|
|
|
from core.prompt.simple_prompt_transform import SimplePromptTransform
|
|
|
|
from core.workflow.entities.node_entities import NodeType
|
|
|
|
from events.app_event import app_was_created
|
|
|
|
from extensions.ext_database import db
|
|
|
|
from models.account import Account
|
|
|
|
from models.api_based_extension import APIBasedExtension, APIBasedExtensionPoint
|
|
|
|
from models.model import App, AppMode, AppModelConfig
|
|
|
|
from models.workflow import Workflow, WorkflowType
|
|
|
|
|
|
|
|
|
|
|
|
class WorkflowConverter:
|
|
|
|
"""
|
|
|
|
App Convert to Workflow Mode
|
|
|
|
"""
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
def convert_to_workflow(
|
|
|
|
self, app_model: App, account: Account, name: str, icon_type: str, icon: str, icon_background: str
|
|
|
|
):
|
2024-04-08 18:51:46 +08:00
|
|
|
"""
|
|
|
|
Convert app to workflow
|
|
|
|
|
|
|
|
- basic mode of chatbot app
|
|
|
|
|
|
|
|
- expert mode of chatbot app
|
|
|
|
|
|
|
|
- completion app
|
|
|
|
|
|
|
|
:param app_model: App instance
|
|
|
|
:param account: Account
|
|
|
|
:param name: new app name
|
|
|
|
:param icon: new app icon
|
2024-08-19 09:16:33 +08:00
|
|
|
:param icon_type: new app icon type
|
2024-04-08 18:51:46 +08:00
|
|
|
:param icon_background: new app icon background
|
|
|
|
:return: new App instance
|
|
|
|
"""
|
|
|
|
# convert app model config
|
2024-08-20 17:51:49 +08:00
|
|
|
if not app_model.app_model_config:
|
|
|
|
raise ValueError("App model config is required")
|
|
|
|
|
2024-04-08 18:51:46 +08:00
|
|
|
workflow = self.convert_app_model_config_to_workflow(
|
2024-08-20 17:51:49 +08:00
|
|
|
app_model=app_model, app_model_config=app_model.app_model_config, account_id=account.id
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
# create new app
|
|
|
|
new_app = App()
|
|
|
|
new_app.tenant_id = app_model.tenant_id
|
2024-09-12 15:50:49 +08:00
|
|
|
new_app.name = name or app_model.name + "(workflow)"
|
2024-08-20 17:51:49 +08:00
|
|
|
new_app.mode = AppMode.ADVANCED_CHAT.value if app_model.mode == AppMode.CHAT.value else AppMode.WORKFLOW.value
|
2024-09-12 15:50:49 +08:00
|
|
|
new_app.icon_type = icon_type or app_model.icon_type
|
|
|
|
new_app.icon = icon or app_model.icon
|
|
|
|
new_app.icon_background = icon_background or app_model.icon_background
|
2024-04-08 18:51:46 +08:00
|
|
|
new_app.enable_site = app_model.enable_site
|
|
|
|
new_app.enable_api = app_model.enable_api
|
|
|
|
new_app.api_rpm = app_model.api_rpm
|
|
|
|
new_app.api_rph = app_model.api_rph
|
|
|
|
new_app.is_demo = False
|
|
|
|
new_app.is_public = app_model.is_public
|
2024-08-28 08:47:30 +08:00
|
|
|
new_app.created_by = account.id
|
|
|
|
new_app.updated_by = account.id
|
2024-04-08 18:51:46 +08:00
|
|
|
db.session.add(new_app)
|
|
|
|
db.session.flush()
|
|
|
|
db.session.commit()
|
|
|
|
|
|
|
|
workflow.app_id = new_app.id
|
|
|
|
db.session.commit()
|
|
|
|
|
|
|
|
app_was_created.send(new_app, account=account)
|
|
|
|
|
|
|
|
return new_app
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
def convert_app_model_config_to_workflow(self, app_model: App, app_model_config: AppModelConfig, account_id: str):
|
2024-04-08 18:51:46 +08:00
|
|
|
"""
|
|
|
|
Convert app model config to workflow mode
|
|
|
|
:param app_model: App instance
|
|
|
|
:param app_model_config: AppModelConfig instance
|
|
|
|
:param account_id: Account ID
|
|
|
|
"""
|
|
|
|
# get new app mode
|
|
|
|
new_app_mode = self._get_new_app_mode(app_model)
|
|
|
|
|
|
|
|
# convert app model config
|
2024-08-20 17:51:49 +08:00
|
|
|
app_config = self._convert_to_app_config(app_model=app_model, app_model_config=app_model_config)
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
# init workflow graph
|
2024-08-20 17:51:49 +08:00
|
|
|
graph = {"nodes": [], "edges": []}
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
# Convert list:
|
|
|
|
# - variables -> start
|
|
|
|
# - model_config -> llm
|
|
|
|
# - prompt_template -> llm
|
|
|
|
# - file_upload -> llm
|
|
|
|
# - external_data_variables -> http-request
|
|
|
|
# - dataset -> knowledge-retrieval
|
|
|
|
# - show_retrieve_source -> knowledge-retrieval
|
|
|
|
|
|
|
|
# convert to start node
|
2024-08-20 17:51:49 +08:00
|
|
|
start_node = self._convert_to_start_node(variables=app_config.variables)
|
2024-04-08 18:51:46 +08:00
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
graph["nodes"].append(start_node)
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
# convert to http request node
|
|
|
|
external_data_variable_node_mapping = {}
|
|
|
|
if app_config.external_data_variables:
|
|
|
|
http_request_nodes, external_data_variable_node_mapping = self._convert_to_http_request_node(
|
|
|
|
app_model=app_model,
|
|
|
|
variables=app_config.variables,
|
2024-08-20 17:51:49 +08:00
|
|
|
external_data_variables=app_config.external_data_variables,
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
for http_request_node in http_request_nodes:
|
|
|
|
graph = self._append_node(graph, http_request_node)
|
|
|
|
|
|
|
|
# convert to knowledge retrieval node
|
|
|
|
if app_config.dataset:
|
|
|
|
knowledge_retrieval_node = self._convert_to_knowledge_retrieval_node(
|
2024-08-20 17:51:49 +08:00
|
|
|
new_app_mode=new_app_mode, dataset_config=app_config.dataset, model_config=app_config.model
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
if knowledge_retrieval_node:
|
|
|
|
graph = self._append_node(graph, knowledge_retrieval_node)
|
|
|
|
|
|
|
|
# convert to llm node
|
|
|
|
llm_node = self._convert_to_llm_node(
|
|
|
|
original_app_mode=AppMode.value_of(app_model.mode),
|
|
|
|
new_app_mode=new_app_mode,
|
|
|
|
graph=graph,
|
|
|
|
model_config=app_config.model,
|
|
|
|
prompt_template=app_config.prompt_template,
|
|
|
|
file_upload=app_config.additional_features.file_upload,
|
2024-08-20 17:51:49 +08:00
|
|
|
external_data_variable_node_mapping=external_data_variable_node_mapping,
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
graph = self._append_node(graph, llm_node)
|
|
|
|
|
|
|
|
if new_app_mode == AppMode.WORKFLOW:
|
|
|
|
# convert to end node by app mode
|
|
|
|
end_node = self._convert_to_end_node()
|
|
|
|
graph = self._append_node(graph, end_node)
|
|
|
|
else:
|
|
|
|
answer_node = self._convert_to_answer_node()
|
|
|
|
graph = self._append_node(graph, answer_node)
|
|
|
|
|
|
|
|
app_model_config_dict = app_config.app_model_config_dict
|
|
|
|
|
|
|
|
# features
|
|
|
|
if new_app_mode == AppMode.ADVANCED_CHAT:
|
|
|
|
features = {
|
|
|
|
"opening_statement": app_model_config_dict.get("opening_statement"),
|
|
|
|
"suggested_questions": app_model_config_dict.get("suggested_questions"),
|
|
|
|
"suggested_questions_after_answer": app_model_config_dict.get("suggested_questions_after_answer"),
|
|
|
|
"speech_to_text": app_model_config_dict.get("speech_to_text"),
|
|
|
|
"text_to_speech": app_model_config_dict.get("text_to_speech"),
|
|
|
|
"file_upload": app_model_config_dict.get("file_upload"),
|
|
|
|
"sensitive_word_avoidance": app_model_config_dict.get("sensitive_word_avoidance"),
|
|
|
|
"retriever_resource": app_model_config_dict.get("retriever_resource"),
|
|
|
|
}
|
|
|
|
else:
|
|
|
|
features = {
|
|
|
|
"text_to_speech": app_model_config_dict.get("text_to_speech"),
|
|
|
|
"file_upload": app_model_config_dict.get("file_upload"),
|
|
|
|
"sensitive_word_avoidance": app_model_config_dict.get("sensitive_word_avoidance"),
|
|
|
|
}
|
|
|
|
|
|
|
|
# create workflow record
|
|
|
|
workflow = Workflow(
|
|
|
|
tenant_id=app_model.tenant_id,
|
|
|
|
app_id=app_model.id,
|
|
|
|
type=WorkflowType.from_app_mode(new_app_mode).value,
|
2024-08-20 17:51:49 +08:00
|
|
|
version="draft",
|
2024-04-08 18:51:46 +08:00
|
|
|
graph=json.dumps(graph),
|
|
|
|
features=json.dumps(features),
|
2024-07-22 15:29:39 +08:00
|
|
|
created_by=account_id,
|
|
|
|
environment_variables=[],
|
2024-08-17 10:30:12 +08:00
|
|
|
conversation_variables=[],
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
db.session.add(workflow)
|
|
|
|
db.session.commit()
|
|
|
|
|
|
|
|
return workflow
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
def _convert_to_app_config(self, app_model: App, app_model_config: AppModelConfig) -> EasyUIBasedAppConfig:
|
2024-04-08 18:51:46 +08:00
|
|
|
app_mode = AppMode.value_of(app_model.mode)
|
|
|
|
if app_mode == AppMode.AGENT_CHAT or app_model.is_agent:
|
|
|
|
app_model.mode = AppMode.AGENT_CHAT.value
|
|
|
|
app_config = AgentChatAppConfigManager.get_app_config(
|
2024-08-20 17:51:49 +08:00
|
|
|
app_model=app_model, app_model_config=app_model_config
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
elif app_mode == AppMode.CHAT:
|
2024-08-20 17:51:49 +08:00
|
|
|
app_config = ChatAppConfigManager.get_app_config(app_model=app_model, app_model_config=app_model_config)
|
2024-04-08 18:51:46 +08:00
|
|
|
elif app_mode == AppMode.COMPLETION:
|
|
|
|
app_config = CompletionAppConfigManager.get_app_config(
|
2024-08-20 17:51:49 +08:00
|
|
|
app_model=app_model, app_model_config=app_model_config
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
raise ValueError("Invalid app mode")
|
|
|
|
|
|
|
|
return app_config
|
|
|
|
|
|
|
|
def _convert_to_start_node(self, variables: list[VariableEntity]) -> dict:
|
|
|
|
"""
|
|
|
|
Convert to Start Node
|
|
|
|
:param variables: list of variables
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
return {
|
|
|
|
"id": "start",
|
|
|
|
"position": None,
|
|
|
|
"data": {
|
|
|
|
"title": "START",
|
|
|
|
"type": NodeType.START.value,
|
2024-08-20 17:51:49 +08:00
|
|
|
"variables": [jsonable_encoder(v) for v in variables],
|
|
|
|
},
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
def _convert_to_http_request_node(
|
|
|
|
self, app_model: App, variables: list[VariableEntity], external_data_variables: list[ExternalDataVariableEntity]
|
|
|
|
) -> tuple[list[dict], dict[str, str]]:
|
2024-04-08 18:51:46 +08:00
|
|
|
"""
|
|
|
|
Convert API Based Extension to HTTP Request Node
|
|
|
|
:param app_model: App instance
|
|
|
|
:param variables: list of variables
|
|
|
|
:param external_data_variables: list of external data variables
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
index = 1
|
|
|
|
nodes = []
|
|
|
|
external_data_variable_node_mapping = {}
|
|
|
|
tenant_id = app_model.tenant_id
|
|
|
|
for external_data_variable in external_data_variables:
|
|
|
|
tool_type = external_data_variable.type
|
|
|
|
if tool_type != "api":
|
|
|
|
continue
|
|
|
|
|
|
|
|
tool_variable = external_data_variable.variable
|
|
|
|
tool_config = external_data_variable.config
|
|
|
|
|
|
|
|
# get params from config
|
|
|
|
api_based_extension_id = tool_config.get("api_based_extension_id")
|
2024-08-20 17:51:49 +08:00
|
|
|
if not api_based_extension_id:
|
|
|
|
continue
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
# get api_based_extension
|
|
|
|
api_based_extension = self._get_api_based_extension(
|
2024-08-20 17:51:49 +08:00
|
|
|
tenant_id=tenant_id, api_based_extension_id=api_based_extension_id
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
|
|
|
|
# decrypt api_key
|
2024-08-20 17:51:49 +08:00
|
|
|
api_key = encrypter.decrypt_token(tenant_id=tenant_id, token=api_based_extension.api_key)
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
inputs = {}
|
|
|
|
for v in variables:
|
2024-08-20 17:51:49 +08:00
|
|
|
inputs[v.variable] = "{{#start." + v.variable + "#}}"
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
request_body = {
|
2024-08-20 17:51:49 +08:00
|
|
|
"point": APIBasedExtensionPoint.APP_EXTERNAL_DATA_TOOL_QUERY.value,
|
|
|
|
"params": {
|
|
|
|
"app_id": app_model.id,
|
|
|
|
"tool_variable": tool_variable,
|
|
|
|
"inputs": inputs,
|
|
|
|
"query": "{{#sys.query#}}" if app_model.mode == AppMode.CHAT.value else "",
|
|
|
|
},
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
request_body_json = json.dumps(request_body)
|
2024-08-20 17:51:49 +08:00
|
|
|
request_body_json = request_body_json.replace(r"\{\{", "{{").replace(r"\}\}", "}}")
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
http_request_node = {
|
|
|
|
"id": f"http_request_{index}",
|
|
|
|
"position": None,
|
|
|
|
"data": {
|
|
|
|
"title": f"HTTP REQUEST {api_based_extension.name}",
|
|
|
|
"type": NodeType.HTTP_REQUEST.value,
|
|
|
|
"method": "post",
|
|
|
|
"url": api_based_extension.api_endpoint,
|
2024-08-20 17:51:49 +08:00
|
|
|
"authorization": {"type": "api-key", "config": {"type": "bearer", "api_key": api_key}},
|
2024-04-08 18:51:46 +08:00
|
|
|
"headers": "",
|
|
|
|
"params": "",
|
2024-08-20 17:51:49 +08:00
|
|
|
"body": {"type": "json", "data": request_body_json},
|
|
|
|
},
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
nodes.append(http_request_node)
|
|
|
|
|
|
|
|
# append code node for response body parsing
|
|
|
|
code_node = {
|
|
|
|
"id": f"code_{index}",
|
|
|
|
"position": None,
|
|
|
|
"data": {
|
|
|
|
"title": f"Parse {api_based_extension.name} Response",
|
|
|
|
"type": NodeType.CODE.value,
|
2024-08-20 17:51:49 +08:00
|
|
|
"variables": [{"variable": "response_json", "value_selector": [http_request_node["id"], "body"]}],
|
2024-04-08 18:51:46 +08:00
|
|
|
"code_language": "python3",
|
|
|
|
"code": "import json\n\ndef main(response_json: str) -> str:\n response_body = json.loads("
|
2024-08-20 17:51:49 +08:00
|
|
|
'response_json)\n return {\n "result": response_body["result"]\n }',
|
|
|
|
"outputs": {"result": {"type": "string"}},
|
|
|
|
},
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
nodes.append(code_node)
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
external_data_variable_node_mapping[external_data_variable.variable] = code_node["id"]
|
2024-04-08 18:51:46 +08:00
|
|
|
index += 1
|
|
|
|
|
|
|
|
return nodes, external_data_variable_node_mapping
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
def _convert_to_knowledge_retrieval_node(
|
|
|
|
self, new_app_mode: AppMode, dataset_config: DatasetEntity, model_config: ModelConfigEntity
|
|
|
|
) -> Optional[dict]:
|
2024-04-08 18:51:46 +08:00
|
|
|
"""
|
|
|
|
Convert datasets to Knowledge Retrieval Node
|
|
|
|
:param new_app_mode: new app mode
|
|
|
|
:param dataset_config: dataset
|
|
|
|
:param model_config: model config
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
retrieve_config = dataset_config.retrieve_config
|
|
|
|
if new_app_mode == AppMode.ADVANCED_CHAT:
|
|
|
|
query_variable_selector = ["sys", "query"]
|
|
|
|
elif retrieve_config.query_variable:
|
|
|
|
# fetch query variable
|
|
|
|
query_variable_selector = ["start", retrieve_config.query_variable]
|
|
|
|
else:
|
|
|
|
return None
|
|
|
|
|
|
|
|
return {
|
|
|
|
"id": "knowledge_retrieval",
|
|
|
|
"position": None,
|
|
|
|
"data": {
|
|
|
|
"title": "KNOWLEDGE RETRIEVAL",
|
|
|
|
"type": NodeType.KNOWLEDGE_RETRIEVAL.value,
|
|
|
|
"query_variable_selector": query_variable_selector,
|
|
|
|
"dataset_ids": dataset_config.dataset_ids,
|
|
|
|
"retrieval_mode": retrieve_config.retrieve_strategy.value,
|
|
|
|
"single_retrieval_config": {
|
|
|
|
"model": {
|
|
|
|
"provider": model_config.provider,
|
|
|
|
"name": model_config.model,
|
|
|
|
"mode": model_config.mode,
|
|
|
|
"completion_params": {
|
|
|
|
**model_config.parameters,
|
|
|
|
"stop": model_config.stop,
|
2024-08-20 17:51:49 +08:00
|
|
|
},
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
}
|
|
|
|
if retrieve_config.retrieve_strategy == DatasetRetrieveConfigEntity.RetrieveStrategy.SINGLE
|
|
|
|
else None,
|
|
|
|
"multiple_retrieval_config": {
|
|
|
|
"top_k": retrieve_config.top_k,
|
|
|
|
"score_threshold": retrieve_config.score_threshold,
|
2024-08-20 17:51:49 +08:00
|
|
|
"reranking_model": retrieve_config.reranking_model,
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
if retrieve_config.retrieve_strategy == DatasetRetrieveConfigEntity.RetrieveStrategy.MULTIPLE
|
|
|
|
else None,
|
2024-08-20 17:51:49 +08:00
|
|
|
},
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
def _convert_to_llm_node(
|
|
|
|
self,
|
|
|
|
original_app_mode: AppMode,
|
|
|
|
new_app_mode: AppMode,
|
|
|
|
graph: dict,
|
|
|
|
model_config: ModelConfigEntity,
|
|
|
|
prompt_template: PromptTemplateEntity,
|
|
|
|
file_upload: Optional[FileExtraConfig] = None,
|
|
|
|
external_data_variable_node_mapping: dict[str, str] | None = None,
|
|
|
|
) -> dict:
|
2024-04-08 18:51:46 +08:00
|
|
|
"""
|
|
|
|
Convert to LLM Node
|
|
|
|
:param original_app_mode: original app mode
|
|
|
|
:param new_app_mode: new app mode
|
|
|
|
:param graph: graph
|
|
|
|
:param model_config: model config
|
|
|
|
:param prompt_template: prompt template
|
|
|
|
:param file_upload: file upload config (optional)
|
|
|
|
:param external_data_variable_node_mapping: external data variable node mapping
|
|
|
|
"""
|
|
|
|
# fetch start and knowledge retrieval node
|
2024-08-20 17:51:49 +08:00
|
|
|
start_node = next(filter(lambda n: n["data"]["type"] == NodeType.START.value, graph["nodes"]))
|
|
|
|
knowledge_retrieval_node = next(
|
|
|
|
filter(lambda n: n["data"]["type"] == NodeType.KNOWLEDGE_RETRIEVAL.value, graph["nodes"]), None
|
|
|
|
)
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
role_prefix = None
|
|
|
|
|
|
|
|
# Chat Model
|
|
|
|
if model_config.mode == LLMMode.CHAT.value:
|
|
|
|
if prompt_template.prompt_type == PromptTemplateEntity.PromptType.SIMPLE:
|
2024-08-20 17:51:49 +08:00
|
|
|
if not prompt_template.simple_prompt_template:
|
|
|
|
raise ValueError("Simple prompt template is required")
|
2024-04-08 18:51:46 +08:00
|
|
|
# get prompt template
|
|
|
|
prompt_transform = SimplePromptTransform()
|
|
|
|
prompt_template_config = prompt_transform.get_prompt_template(
|
|
|
|
app_mode=original_app_mode,
|
|
|
|
provider=model_config.provider,
|
|
|
|
model=model_config.model,
|
|
|
|
pre_prompt=prompt_template.simple_prompt_template,
|
|
|
|
has_context=knowledge_retrieval_node is not None,
|
2024-08-20 17:51:49 +08:00
|
|
|
query_in_prompt=False,
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
template = prompt_template_config["prompt_template"].template
|
2024-04-08 18:51:46 +08:00
|
|
|
if not template:
|
|
|
|
prompts = []
|
|
|
|
else:
|
|
|
|
template = self._replace_template_variables(
|
2024-08-20 17:51:49 +08:00
|
|
|
template, start_node["data"]["variables"], external_data_variable_node_mapping
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
prompts = [{"role": "user", "text": template}]
|
2024-04-08 18:51:46 +08:00
|
|
|
else:
|
|
|
|
advanced_chat_prompt_template = prompt_template.advanced_chat_prompt_template
|
|
|
|
|
|
|
|
prompts = []
|
2024-08-20 17:51:49 +08:00
|
|
|
if advanced_chat_prompt_template:
|
|
|
|
for m in advanced_chat_prompt_template.messages:
|
2024-04-08 18:51:46 +08:00
|
|
|
text = m.text
|
|
|
|
text = self._replace_template_variables(
|
2024-08-20 17:51:49 +08:00
|
|
|
text, start_node["data"]["variables"], external_data_variable_node_mapping
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
prompts.append({"role": m.role.value, "text": text})
|
2024-04-08 18:51:46 +08:00
|
|
|
# Completion Model
|
|
|
|
else:
|
|
|
|
if prompt_template.prompt_type == PromptTemplateEntity.PromptType.SIMPLE:
|
2024-08-20 17:51:49 +08:00
|
|
|
if not prompt_template.simple_prompt_template:
|
|
|
|
raise ValueError("Simple prompt template is required")
|
2024-04-08 18:51:46 +08:00
|
|
|
# get prompt template
|
|
|
|
prompt_transform = SimplePromptTransform()
|
|
|
|
prompt_template_config = prompt_transform.get_prompt_template(
|
|
|
|
app_mode=original_app_mode,
|
|
|
|
provider=model_config.provider,
|
|
|
|
model=model_config.model,
|
|
|
|
pre_prompt=prompt_template.simple_prompt_template,
|
|
|
|
has_context=knowledge_retrieval_node is not None,
|
2024-08-20 17:51:49 +08:00
|
|
|
query_in_prompt=False,
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
template = prompt_template_config["prompt_template"].template
|
2024-04-08 18:51:46 +08:00
|
|
|
template = self._replace_template_variables(
|
2024-08-20 17:51:49 +08:00
|
|
|
template=template,
|
|
|
|
variables=start_node["data"]["variables"],
|
|
|
|
external_data_variable_node_mapping=external_data_variable_node_mapping,
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
prompts = {"text": template}
|
2024-04-08 18:51:46 +08:00
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
prompt_rules = prompt_template_config["prompt_rules"]
|
2024-04-08 18:51:46 +08:00
|
|
|
role_prefix = {
|
2024-08-20 17:51:49 +08:00
|
|
|
"user": prompt_rules.get("human_prefix", "Human"),
|
|
|
|
"assistant": prompt_rules.get("assistant_prefix", "Assistant"),
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
else:
|
|
|
|
advanced_completion_prompt_template = prompt_template.advanced_completion_prompt_template
|
|
|
|
if advanced_completion_prompt_template:
|
|
|
|
text = advanced_completion_prompt_template.prompt
|
|
|
|
text = self._replace_template_variables(
|
2024-08-20 17:51:49 +08:00
|
|
|
template=text,
|
|
|
|
variables=start_node["data"]["variables"],
|
|
|
|
external_data_variable_node_mapping=external_data_variable_node_mapping,
|
2024-04-08 18:51:46 +08:00
|
|
|
)
|
|
|
|
else:
|
|
|
|
text = ""
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
text = text.replace("{{#query#}}", "{{#sys.query#}}")
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
prompts = {
|
|
|
|
"text": text,
|
|
|
|
}
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
if advanced_completion_prompt_template and advanced_completion_prompt_template.role_prefix:
|
2024-04-08 18:51:46 +08:00
|
|
|
role_prefix = {
|
|
|
|
"user": advanced_completion_prompt_template.role_prefix.user,
|
2024-08-20 17:51:49 +08:00
|
|
|
"assistant": advanced_completion_prompt_template.role_prefix.assistant,
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
memory = None
|
|
|
|
if new_app_mode == AppMode.ADVANCED_CHAT:
|
2024-08-20 17:51:49 +08:00
|
|
|
memory = {"role_prefix": role_prefix, "window": {"enabled": False}}
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
completion_params = model_config.parameters
|
|
|
|
completion_params.update({"stop": model_config.stop})
|
|
|
|
return {
|
|
|
|
"id": "llm",
|
|
|
|
"position": None,
|
|
|
|
"data": {
|
|
|
|
"title": "LLM",
|
|
|
|
"type": NodeType.LLM.value,
|
|
|
|
"model": {
|
|
|
|
"provider": model_config.provider,
|
|
|
|
"name": model_config.model,
|
|
|
|
"mode": model_config.mode,
|
2024-08-20 17:51:49 +08:00
|
|
|
"completion_params": completion_params,
|
2024-04-08 18:51:46 +08:00
|
|
|
},
|
|
|
|
"prompt_template": prompts,
|
|
|
|
"memory": memory,
|
|
|
|
"context": {
|
|
|
|
"enabled": knowledge_retrieval_node is not None,
|
|
|
|
"variable_selector": ["knowledge_retrieval", "result"]
|
2024-08-20 17:51:49 +08:00
|
|
|
if knowledge_retrieval_node is not None
|
|
|
|
else None,
|
2024-04-08 18:51:46 +08:00
|
|
|
},
|
|
|
|
"vision": {
|
|
|
|
"enabled": file_upload is not None,
|
|
|
|
"variable_selector": ["sys", "files"] if file_upload is not None else None,
|
2024-08-20 17:51:49 +08:00
|
|
|
"configs": {"detail": file_upload.image_config["detail"]}
|
|
|
|
if file_upload is not None and file_upload.image_config is not None
|
|
|
|
else None,
|
|
|
|
},
|
|
|
|
},
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
def _replace_template_variables(
|
|
|
|
self, template: str, variables: list[dict], external_data_variable_node_mapping: dict[str, str] | None = None
|
|
|
|
) -> str:
|
2024-04-08 18:51:46 +08:00
|
|
|
"""
|
|
|
|
Replace Template Variables
|
|
|
|
:param template: template
|
|
|
|
:param variables: list of variables
|
2024-08-16 14:19:01 +08:00
|
|
|
:param external_data_variable_node_mapping: external data variable node mapping
|
2024-04-08 18:51:46 +08:00
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
for v in variables:
|
2024-08-20 17:51:49 +08:00
|
|
|
template = template.replace("{{" + v["variable"] + "}}", "{{#start." + v["variable"] + "#}}")
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
if external_data_variable_node_mapping:
|
|
|
|
for variable, code_node_id in external_data_variable_node_mapping.items():
|
2024-08-20 17:51:49 +08:00
|
|
|
template = template.replace("{{" + variable + "}}", "{{#" + code_node_id + ".result#}}")
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
return template
|
|
|
|
|
|
|
|
def _convert_to_end_node(self) -> dict:
|
|
|
|
"""
|
|
|
|
Convert to End Node
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
# for original completion app
|
|
|
|
return {
|
|
|
|
"id": "end",
|
|
|
|
"position": None,
|
|
|
|
"data": {
|
|
|
|
"title": "END",
|
|
|
|
"type": NodeType.END.value,
|
2024-08-20 17:51:49 +08:00
|
|
|
"outputs": [{"variable": "result", "value_selector": ["llm", "text"]}],
|
|
|
|
},
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
def _convert_to_answer_node(self) -> dict:
|
|
|
|
"""
|
|
|
|
Convert to Answer Node
|
|
|
|
:return:
|
|
|
|
"""
|
|
|
|
# for original chat app
|
|
|
|
return {
|
|
|
|
"id": "answer",
|
|
|
|
"position": None,
|
2024-08-20 17:51:49 +08:00
|
|
|
"data": {"title": "ANSWER", "type": NodeType.ANSWER.value, "answer": "{{#llm.text#}}"},
|
2024-04-08 18:51:46 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
def _create_edge(self, source: str, target: str) -> dict:
|
|
|
|
"""
|
|
|
|
Create Edge
|
|
|
|
:param source: source node id
|
|
|
|
:param target: target node id
|
|
|
|
:return:
|
|
|
|
"""
|
2024-08-20 17:51:49 +08:00
|
|
|
return {"id": f"{source}-{target}", "source": source, "target": target}
|
2024-04-08 18:51:46 +08:00
|
|
|
|
|
|
|
def _append_node(self, graph: dict, node: dict) -> dict:
|
|
|
|
"""
|
|
|
|
Append Node to Graph
|
|
|
|
|
|
|
|
:param graph: Graph, include: nodes, edges
|
|
|
|
:param node: Node to append
|
|
|
|
:return:
|
|
|
|
"""
|
2024-08-20 17:51:49 +08:00
|
|
|
previous_node = graph["nodes"][-1]
|
|
|
|
graph["nodes"].append(node)
|
|
|
|
graph["edges"].append(self._create_edge(previous_node["id"], node["id"]))
|
2024-04-08 18:51:46 +08:00
|
|
|
return graph
|
|
|
|
|
|
|
|
def _get_new_app_mode(self, app_model: App) -> AppMode:
|
|
|
|
"""
|
|
|
|
Get new app mode
|
|
|
|
:param app_model: App instance
|
|
|
|
:return: AppMode
|
|
|
|
"""
|
|
|
|
if app_model.mode == AppMode.COMPLETION.value:
|
|
|
|
return AppMode.WORKFLOW
|
|
|
|
else:
|
|
|
|
return AppMode.ADVANCED_CHAT
|
|
|
|
|
2024-08-20 17:51:49 +08:00
|
|
|
def _get_api_based_extension(self, tenant_id: str, api_based_extension_id: str):
|
2024-04-08 18:51:46 +08:00
|
|
|
"""
|
|
|
|
Get API Based Extension
|
|
|
|
:param tenant_id: tenant id
|
|
|
|
:param api_based_extension_id: api based extension id
|
|
|
|
:return:
|
|
|
|
"""
|
2024-08-20 17:51:49 +08:00
|
|
|
api_based_extension = (
|
|
|
|
db.session.query(APIBasedExtension)
|
|
|
|
.filter(APIBasedExtension.tenant_id == tenant_id, APIBasedExtension.id == api_based_extension_id)
|
|
|
|
.first()
|
|
|
|
)
|
|
|
|
|
|
|
|
if not api_based_extension:
|
|
|
|
raise ValueError(f"API Based Extension not found, id: {api_based_extension_id}")
|
|
|
|
|
|
|
|
return api_based_extension
|