This commit is contained in:
Ricky 2024-01-31 11:58:07 +08:00 • committed by GitHub
commit 2660fbaa20
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
58 changed files with 312 additions and 312 deletions

View file

@ -170,7 +170,7 @@ class AssistantApplicationRunner(AppRunner):
# load tool variables
tool_conversation_variables = self._load_tool_variables(conversation_id=conversation.id,
user_id=application_generate_entity.user_id,
tanent_id=application_generate_entity.tenant_id)
tenant_id=application_generate_entity.tenant_id)
# convert db variables to tool variables
tool_variables = self._convert_db_variables_to_tool_variables(tool_conversation_variables)
@ -254,13 +254,13 @@ class AssistantApplicationRunner(AppRunner):
agent=True
)
def _load_tool_variables(self, conversation_id: str, user_id: str, tanent_id: str) -> ToolConversationVariables:
def _load_tool_variables(self, conversation_id: str, user_id: str, tenant_id: str) -> ToolConversationVariables:
"""
load tool variables from database
"""
tool_variables: ToolConversationVariables = db.session.query(ToolConversationVariables).filter(
ToolConversationVariables.conversation_id == conversation_id,
ToolConversationVariables.tenant_id == tanent_id
ToolConversationVariables.tenant_id == tenant_id
).first()
if tool_variables:
@ -271,7 +271,7 @@ class AssistantApplicationRunner(AppRunner):
tool_variables = ToolConversationVariables(
conversation_id=conversation_id,
user_id=user_id,
tenant_id=tanent_id,
tenant_id=tenant_id,
variables_str='[]',
)
db.session.add(tool_variables)

View file

@ -12,7 +12,7 @@ from models.model import MessageAgentThought, Message, MessageFile
from models.tools import ToolConversationVariables
from core.tools.entities.tool_entities import ToolInvokeMessage, ToolInvokeMessageBinary, \
ToolRuntimeVariablePool, ToolParamter
ToolRuntimeVariablePool, ToolParameter
from core.tools.tool.tool import Tool
from core.tools.tool_manager import ToolManager
from core.tools.tool_file_manager import ToolFileManager
@ -108,9 +108,9 @@ class BaseAssistantApplicationRunner(AppRunner):
else:
self.stream_tool_call = False
def _repacket_app_orchestration_config(self, app_orchestration_config: AppOrchestrationConfigEntity) -> AppOrchestrationConfigEntity:
def _repack_app_orchestration_config(self, app_orchestration_config: AppOrchestrationConfigEntity) -> AppOrchestrationConfigEntity:
"""
Repacket app orchestration config
Repack app orchestration config
"""
if app_orchestration_config.prompt_template.simple_prompt_template is None:
app_orchestration_config.prompt_template.simple_prompt_template = ''
@ -126,7 +126,7 @@ class BaseAssistantApplicationRunner(AppRunner):
if response.type == ToolInvokeMessage.MessageType.TEXT:
result += response.message
elif response.type == ToolInvokeMessage.MessageType.LINK:
result += f"result link: {response.message}. please dirct user to check it."
result += f"result link: {response.message}. please tell user to check it."
elif response.type == ToolInvokeMessage.MessageType.IMAGE_LINK or \
response.type == ToolInvokeMessage.MessageType.IMAGE:
result += f"image has been created and sent to user already, you should tell user to check it now."
@ -141,7 +141,7 @@ class BaseAssistantApplicationRunner(AppRunner):
"""
tool_entity = ToolManager.get_tool_runtime(
provider_type=tool.provider_type, provider_name=tool.provider_id, tool_name=tool.tool_name,
tanent_id=self.application_generate_entity.tenant_id,
tenant_id=self.application_generate_entity.tenant_id,
agent_callback=self.agent_callback
)
tool_entity.load_variables(self.variables_pool)
@ -185,20 +185,20 @@ class BaseAssistantApplicationRunner(AppRunner):
for parameter in parameters:
parameter_type = 'string'
enum = []
if parameter.type == ToolParamter.ToolParameterType.STRING:
if parameter.type == ToolParameter.ToolParameterType.STRING:
parameter_type = 'string'
elif parameter.type == ToolParamter.ToolParameterType.BOOLEAN:
elif parameter.type == ToolParameter.ToolParameterType.BOOLEAN:
parameter_type = 'boolean'
elif parameter.type == ToolParamter.ToolParameterType.NUMBER:
elif parameter.type == ToolParameter.ToolParameterType.NUMBER:
parameter_type = 'number'
elif parameter.type == ToolParamter.ToolParameterType.SELECT:
elif parameter.type == ToolParameter.ToolParameterType.SELECT:
for option in parameter.options:
enum.append(option.value)
parameter_type = 'string'
else:
raise ValueError(f"parameter type {parameter.type} is not supported")
if parameter.form == ToolParamter.ToolParameterForm.FORM:
if parameter.form == ToolParameter.ToolParameterForm.FORM:
# get tool parameter from form
tool_parameter_config = tool.tool_parameters.get(parameter.name)
if not tool_parameter_config:
@ -207,7 +207,7 @@ class BaseAssistantApplicationRunner(AppRunner):
if not tool_parameter_config and parameter.required:
raise ValueError(f"tool parameter {parameter.name} not found in tool config")
if parameter.type == ToolParamter.ToolParameterType.SELECT:
if parameter.type == ToolParameter.ToolParameterType.SELECT:
# check if tool_parameter_config in options
options = list(map(lambda x: x.value, parameter.options))
if tool_parameter_config not in options:
@ -215,7 +215,7 @@ class BaseAssistantApplicationRunner(AppRunner):
# convert tool parameter config to correct type
try:
if parameter.type == ToolParamter.ToolParameterType.NUMBER:
if parameter.type == ToolParameter.ToolParameterType.NUMBER:
# check if tool parameter is integer
if isinstance(tool_parameter_config, int):
tool_parameter_config = tool_parameter_config
@ -226,11 +226,11 @@ class BaseAssistantApplicationRunner(AppRunner):
tool_parameter_config = float(tool_parameter_config)
else:
tool_parameter_config = int(tool_parameter_config)
elif parameter.type == ToolParamter.ToolParameterType.BOOLEAN:
elif parameter.type == ToolParameter.ToolParameterType.BOOLEAN:
tool_parameter_config = bool(tool_parameter_config)
elif parameter.type not in [ToolParamter.ToolParameterType.SELECT, ToolParamter.ToolParameterType.STRING]:
elif parameter.type not in [ToolParameter.ToolParameterType.SELECT, ToolParameter.ToolParameterType.STRING]:
tool_parameter_config = str(tool_parameter_config)
elif parameter.type == ToolParamter.ToolParameterType:
elif parameter.type == ToolParameter.ToolParameterType:
tool_parameter_config = str(tool_parameter_config)
except Exception as e:
raise ValueError(f"tool parameter {parameter.name} value {tool_parameter_config} is not correct type")
@ -238,7 +238,7 @@ class BaseAssistantApplicationRunner(AppRunner):
# save tool parameter to tool entity memory
runtime_parameters[parameter.name] = tool_parameter_config
elif parameter.form == ToolParamter.ToolParameterForm.LLM:
elif parameter.form == ToolParameter.ToolParameterForm.LLM:
message_tool.parameters['properties'][parameter.name] = {
"type": parameter_type,
"description": parameter.llm_description or '',
@ -292,20 +292,20 @@ class BaseAssistantApplicationRunner(AppRunner):
for parameter in tool_runtime_parameters:
parameter_type = 'string'
enum = []
if parameter.type == ToolParamter.ToolParameterType.STRING:
if parameter.type == ToolParameter.ToolParameterType.STRING:
parameter_type = 'string'
elif parameter.type == ToolParamter.ToolParameterType.BOOLEAN:
elif parameter.type == ToolParameter.ToolParameterType.BOOLEAN:
parameter_type = 'boolean'
elif parameter.type == ToolParamter.ToolParameterType.NUMBER:
elif parameter.type == ToolParameter.ToolParameterType.NUMBER:
parameter_type = 'number'
elif parameter.type == ToolParamter.ToolParameterType.SELECT:
elif parameter.type == ToolParameter.ToolParameterType.SELECT:
for option in parameter.options:
enum.append(option.value)
parameter_type = 'string'
else:
raise ValueError(f"parameter type {parameter.type} is not supported")
if parameter.form == ToolParamter.ToolParameterForm.LLM:
if parameter.form == ToolParameter.ToolParameterForm.LLM:
prompt_tool.parameters['properties'][parameter.name] = {
"type": parameter_type,
"description": parameter.llm_description or '',

View file

@ -12,7 +12,7 @@ from core.model_runtime.entities.llm_entities import LLMResult, LLMUsage, LLMRes
from core.model_manager import ModelInstance
from core.tools.errors import ToolInvokeError, ToolNotFoundError, \
ToolNotSupportedError, ToolProviderNotFoundError, ToolParamterValidationError, \
ToolNotSupportedError, ToolProviderNotFoundError, ToolParameterValidationError, \
ToolProviderCredentialValidationError
from core.features.assistant_base_runner import BaseAssistantApplicationRunner
@ -28,7 +28,7 @@ class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
Run Cot agent application
"""
app_orchestration_config = self.app_orchestration_config
self._repacket_app_orchestration_config(app_orchestration_config)
self._repack_app_orchestration_config(app_orchestration_config)
agent_scratchpad: List[AgentScratchpadUnit] = []
@ -71,7 +71,7 @@ class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
}
final_answer = ''
def increse_usage(final_llm_usage_dict: Dict[str, LLMUsage], usage: LLMUsage):
def increase_usage(final_llm_usage_dict: Dict[str, LLMUsage], usage: LLMUsage):
if not final_llm_usage_dict['usage']:
final_llm_usage_dict['usage'] = usage
else:
@ -105,7 +105,7 @@ class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
self.queue_manager.publish_agent_thought(agent_thought, PublishFrom.APPLICATION_MANAGER)
# update prompt messages
prompt_messages = self._originze_cot_prompt_messages(
prompt_messages = self._organize_cot_prompt_messages(
mode=app_orchestration_config.model_config.mode,
prompt_messages=prompt_messages,
tools=prompt_messages_tools,
@ -138,7 +138,7 @@ class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
# get llm usage
if llm_result.usage:
increse_usage(llm_usage, llm_result.usage)
increase_usage(llm_usage, llm_result.usage)
# publish agent thought if it's first iteration
if iteration_step == 1:
@ -208,7 +208,7 @@ class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
try:
tool_response = tool_instance.invoke(
user_id=self.user_id,
tool_paramters=tool_call_args if isinstance(tool_call_args, dict) else json.loads(tool_call_args)
tool_parameters=tool_call_args if isinstance(tool_call_args, dict) else json.loads(tool_call_args)
)
# transform tool response to llm friendly response
tool_response = self.transform_tool_invoke_messages(tool_response)
@ -226,15 +226,15 @@ class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
message_file_ids = [message_file.id for message_file, _ in message_files]
except ToolProviderCredentialValidationError as e:
error_response = f"Plese check your tool provider credentials"
error_response = f"Please check your tool provider credentials"
except (
ToolNotFoundError, ToolNotSupportedError, ToolProviderNotFoundError
) as e:
error_response = f"there is not a tool named {tool_call_name}"
except (
ToolParamterValidationError
ToolParameterValidationError
) as e:
error_response = f"tool paramters validation error: {e}, please check your tool paramters"
error_response = f"tool parameters validation error: {e}, please check your tool parameters"
except ToolInvokeError as e:
error_response = f"tool invoke error: {e}"
except Exception as e:
@ -469,7 +469,7 @@ class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
if not next_iteration.find("{{observation}}") >= 0:
raise ValueError("{{observation}} is required in next_iteration")
def _convert_strachpad_list_to_str(self, agent_scratchpad: List[AgentScratchpadUnit]) -> str:
def _convert_scratchpad_list_to_str(self, agent_scratchpad: List[AgentScratchpadUnit]) -> str:
"""
convert agent scratchpad list to str
"""
@ -481,7 +481,7 @@ class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
return result
def _originze_cot_prompt_messages(self, mode: Literal["completion", "chat"],
def _organize_cot_prompt_messages(self, mode: Literal["completion", "chat"],
prompt_messages: List[PromptMessage],
tools: List[PromptMessageTool],
agent_scratchpad: List[AgentScratchpadUnit],
@ -490,7 +490,7 @@ class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
input: str,
) -> List[PromptMessage]:
"""
originze chain of thought prompt messages, a standard prompt message is like:
organize chain of thought prompt messages, a standard prompt message is like:
Respond to the human as helpfully and accurately as possible.
{{instruction}}
@ -528,7 +528,7 @@ class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
.replace("{{tools}}", tools_str) \
.replace("{{tool_names}}", tool_names)
# originze prompt messages
# organize prompt messages
if mode == "chat":
# override system message
overrided = False
@ -559,7 +559,7 @@ class AssistantCotApplicationRunner(BaseAssistantApplicationRunner):
return prompt_messages
elif mode == "completion":
# parse agent scratchpad
agent_scratchpad_str = self._convert_strachpad_list_to_str(agent_scratchpad)
agent_scratchpad_str = self._convert_scratchpad_list_to_str(agent_scratchpad)
# parse prompt messages
return [UserPromptMessage(
content=first_prompt.replace("{{instruction}}", instruction)

View file

@ -10,7 +10,7 @@ from core.model_manager import ModelInstance
from core.application_queue_manager import PublishFrom
from core.tools.errors import ToolInvokeError, ToolNotFoundError, \
ToolNotSupportedError, ToolProviderNotFoundError, ToolParamterValidationError, \
ToolNotSupportedError, ToolProviderNotFoundError, ToolParameterValidationError, \
ToolProviderCredentialValidationError
from core.features.assistant_base_runner import BaseAssistantApplicationRunner
@ -247,7 +247,7 @@ class AssistantFunctionCallApplicationRunner(BaseAssistantApplicationRunner):
try:
tool_invoke_message = tool_instance.invoke(
user_id=self.user_id,
tool_paramters=tool_call_args,
tool_parameters=tool_call_args,
)
# transform tool invoke message to get LLM friendly message
tool_invoke_message = self.transform_tool_invoke_messages(tool_invoke_message)
@ -272,9 +272,9 @@ class AssistantFunctionCallApplicationRunner(BaseAssistantApplicationRunner):
) as e:
error_response = f"there is not a tool named {tool_call_name}"
except (
ToolParamterValidationError
ToolParameterValidationError
) as e:
error_response = f"tool paramters validation error: {e}, please check your tool paramters"
error_response = f"tool parameters validation error: {e}, please check your tool parameters"
except ToolInvokeError as e:
error_response = f"tool invoke error: {e}"
except Exception as e:

View file

@ -41,7 +41,7 @@ class OpenLLMGenerate(object):
if not server_url:
raise InvalidAuthenticationError('Invalid server URL')
defautl_llm_config = {
default_llm_config = {
"max_new_tokens": 128,
"min_length": 0,
"early_stopping": False,
@ -75,19 +75,19 @@ class OpenLLMGenerate(object):
}
if 'max_tokens' in model_parameters and type(model_parameters['max_tokens']) == int:
defautl_llm_config['max_new_tokens'] = model_parameters['max_tokens']
default_llm_config['max_new_tokens'] = model_parameters['max_tokens']
if 'temperature' in model_parameters and type(model_parameters['temperature']) == float:
defautl_llm_config['temperature'] = model_parameters['temperature']
default_llm_config['temperature'] = model_parameters['temperature']
if 'top_p' in model_parameters and type(model_parameters['top_p']) == float:
defautl_llm_config['top_p'] = model_parameters['top_p']
default_llm_config['top_p'] = model_parameters['top_p']
if 'top_k' in model_parameters and type(model_parameters['top_k']) == int:
defautl_llm_config['top_k'] = model_parameters['top_k']
default_llm_config['top_k'] = model_parameters['top_k']
if 'use_cache' in model_parameters and type(model_parameters['use_cache']) == bool:
defautl_llm_config['use_cache'] = model_parameters['use_cache']
default_llm_config['use_cache'] = model_parameters['use_cache']
headers = {
'Content-Type': 'application/json',
@ -104,7 +104,7 @@ class OpenLLMGenerate(object):
data = {
'stop': stop if stop else [],
'prompt': '\n'.join([message.content for message in prompt_messages]),
'llm_config': defautl_llm_config,
'llm_config': default_llm_config,
}
try:

View file

@ -125,7 +125,7 @@ from openai import OpenAI
class DallE3Tool(BuiltinTool):
def _invoke(self,
user_id: str,
tool_paramters: Dict[str, Any],
tool_parameters: Dict[str, Any],
) -> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
"""
invoke tools
@ -135,7 +135,7 @@ class DallE3Tool(BuiltinTool):
)
# prompt
prompt = tool_paramters.get('prompt', '')
prompt = tool_parameters.get('prompt', '')
if not prompt:
return self.create_text_message('Please input prompt')
@ -163,7 +163,7 @@ Next, we use Vectorizer.AI to convert the PNG icon generated by DallE3 into a ve
```python
from core.tools.tool.builtin_tool import BuiltinTool
from core.tools.entities.tool_entities import ToolInvokeMessage, ToolParamter
from core.tools.entities.tool_entities import ToolInvokeMessage, ToolParameter
from core.tools.errors import ToolProviderCredentialValidationError
from typing import Any, Dict, List, Union
@ -171,20 +171,20 @@ from httpx import post
from base64 import b64decode
class VectorizerTool(BuiltinTool):
def _invoke(self, user_id: str, tool_paramters: Dict[str, Any]) \
def _invoke(self, user_id: str, tool_parameters: Dict[str, Any]) \
-> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
"""
Tool invocation, the image variable name needs to be passed in from here, so that we can get the image from the variable pool
"""
def get_runtime_parameters(self) -> List[ToolParamter]:
def get_runtime_parameters(self) -> List[ToolParameter]:
"""
Override the tool parameter list, we can dynamically generate the parameter list based on the actual situation in the current variable pool, so that the LLM can generate the form based on the parameter list
"""
def is_tool_avaliable(self) -> bool:
def is_tool_available(self) -> bool:
"""
Whether the current tool is available, if there is no image in the current variable pool, then we don't need to display this tool, just return False here
"""
@ -194,7 +194,7 @@ Next, let's implement these three functions
```python
from core.tools.tool.builtin_tool import BuiltinTool
from core.tools.entities.tool_entities import ToolInvokeMessage, ToolParamter
from core.tools.entities.tool_entities import ToolInvokeMessage, ToolParameter
from core.tools.errors import ToolProviderCredentialValidationError
from typing import Any, Dict, List, Union
@ -202,7 +202,7 @@ from httpx import post
from base64 import b64decode
class VectorizerTool(BuiltinTool):
def _invoke(self, user_id: str, tool_paramters: Dict[str, Any]) \
def _invoke(self, user_id: str, tool_parameters: Dict[str, Any]) \
-> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
"""
invoke tools
@ -214,7 +214,7 @@ class VectorizerTool(BuiltinTool):
raise ToolProviderCredentialValidationError('Please input api key name and value')
# Get image_id, the definition of image_id can be found in get_runtime_parameters
image_id = tool_paramters.get('image_id', '')
image_id = tool_parameters.get('image_id', '')
if not image_id:
return self.create_text_message('Please input image id')
@ -241,24 +241,24 @@ class VectorizerTool(BuiltinTool):
meta={'mime_type': 'image/svg+xml'})
]
def get_runtime_parameters(self) -> List[ToolParamter]:
def get_runtime_parameters(self) -> List[ToolParameter]:
"""
override the runtime parameters
"""
# Here, we override the tool parameter list, define the image_id, and set its option list to all images in the current variable pool. The configuration here is consistent with the configuration in yaml.
return [
ToolParamter.get_simple_instance(
ToolParameter.get_simple_instance(
name='image_id',
llm_description=f'the image id that you want to vectorize, \
and the image id should be specified in \
{[i.name for i in self.list_default_image_variables()]}',
type=ToolParamter.ToolParameterType.SELECT,
type=ToolParameter.ToolParameterType.SELECT,
required=True,
options=[i.name for i in self.list_default_image_variables()]
)
]
def is_tool_avaliable(self) -> bool:
def is_tool_available(self) -> bool:
# Only when there are images in the variable pool, the LLM needs to use this tool
return len(self.list_default_image_variables()) > 0
```

View file

@ -146,13 +146,13 @@ from typing import Any, Dict, List, Union
class GoogleSearchTool(BuiltinTool):
def _invoke(self,
user_id: str,
tool_paramters: Dict[str, Any],
tool_parameters: Dict[str, Any],
) -> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
"""
invoke tools
"""
query = tool_paramters['query']
result_type = tool_paramters['result_type']
query = tool_parameters['query']
result_type = tool_parameters['result_type']
api_key = self.runtime.credentials['serpapi_api_key']
# TODO: search with serpapi
result = SerpAPI(api_key).run(query, result_type=result_type)
@ -163,7 +163,7 @@ class GoogleSearchTool(BuiltinTool):
```
### Parameters
The overall logic of the tool is in the `_invoke` method, this method accepts two parameters: `user_id` and `tool_paramters`, which represent the user ID and tool parameters respectively
The overall logic of the tool is in the `_invoke` method, this method accepts two parameters: `user_id` and `tool_parameters`, which represent the user ID and tool parameters respectively
### Return Data
When the tool returns, you can choose to return one message or multiple messages, here we return one message, using `create_text_message` and `create_link_message` can create a text message or a link message.
@ -195,7 +195,7 @@ class GoogleProvider(BuiltinToolProviderController):
}
).invoke(
user_id='',
tool_paramters={
tool_parameters={
"query": "test",
"result_type": "link"
},

View file

@ -125,7 +125,7 @@ from openai import OpenAI
class DallE3Tool(BuiltinTool):
def _invoke(self,
user_id: str,
tool_paramters: Dict[str, Any],
tool_parameters: Dict[str, Any],
) -> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
"""
invoke tools
@ -135,7 +135,7 @@ class DallE3Tool(BuiltinTool):
)
# prompt
prompt = tool_paramters.get('prompt', '')
prompt = tool_parameters.get('prompt', '')
if not prompt:
return self.create_text_message('Please input prompt')
@ -163,7 +163,7 @@ class DallE3Tool(BuiltinTool):
```python
from core.tools.tool.builtin_tool import BuiltinTool
from core.tools.entities.tool_entities import ToolInvokeMessage, ToolParamter
from core.tools.entities.tool_entities import ToolInvokeMessage, ToolParameter
from core.tools.errors import ToolProviderCredentialValidationError
from typing import Any, Dict, List, Union
@ -171,20 +171,20 @@ from httpx import post
from base64 import b64decode
class VectorizerTool(BuiltinTool):
def _invoke(self, user_id: str, tool_paramters: Dict[str, Any]) \
def _invoke(self, user_id: str, tool_parameters: Dict[str, Any]) \
-> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
"""
工具调用,图片变量名需要从这里传递进来,从而我们就可以从变量池中获取到图片
"""
def get_runtime_parameters(self) -> List[ToolParamter]:
def get_runtime_parameters(self) -> List[ToolParameter]:
"""
重写工具参数列表,我们可以根据当前变量池里的实际情况来动态生成参数列表,从而LLM可以根据参数列表来生成表单
"""
def is_tool_avaliable(self) -> bool:
def is_tool_available(self) -> bool:
"""
当前工具是否可用,如果当前变量池中没有图片,那么我们就不需要展示这个工具,这里返回False即可
"""
@ -194,7 +194,7 @@ class VectorizerTool(BuiltinTool):
```python
from core.tools.tool.builtin_tool import BuiltinTool
from core.tools.entities.tool_entities import ToolInvokeMessage, ToolParamter
from core.tools.entities.tool_entities import ToolInvokeMessage, ToolParameter
from core.tools.errors import ToolProviderCredentialValidationError
from typing import Any, Dict, List, Union
@ -202,7 +202,7 @@ from httpx import post
from base64 import b64decode
class VectorizerTool(BuiltinTool):
def _invoke(self, user_id: str, tool_paramters: Dict[str, Any]) \
def _invoke(self, user_id: str, tool_parameters: Dict[str, Any]) \
-> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
"""
invoke tools
@ -214,7 +214,7 @@ class VectorizerTool(BuiltinTool):
raise ToolProviderCredentialValidationError('Please input api key name and value')
# 获取image_id,image_id的定义可以在get_runtime_parameters中找到
image_id = tool_paramters.get('image_id', '')
image_id = tool_parameters.get('image_id', '')
if not image_id:
return self.create_text_message('Please input image id')
@ -241,24 +241,24 @@ class VectorizerTool(BuiltinTool):
meta={'mime_type': 'image/svg+xml'})
]
def get_runtime_parameters(self) -> List[ToolParamter]:
def get_runtime_parameters(self) -> List[ToolParameter]:
"""
override the runtime parameters
"""
# 这里,我们重写了工具参数列表,定义了image_id,并设置了它的选项列表为当前变量池中的所有图片,这里的配置与yaml中的配置是一致的
return [
ToolParamter.get_simple_instance(
ToolParameter.get_simple_instance(
name='image_id',
llm_description=f'the image id that you want to vectorize, \
and the image id should be specified in \
{[i.name for i in self.list_default_image_variables()]}',
type=ToolParamter.ToolParameterType.SELECT,
type=ToolParameter.ToolParameterType.SELECT,
required=True,
options=[i.name for i in self.list_default_image_variables()]
)
]
def is_tool_avaliable(self) -> bool:
def is_tool_available(self) -> bool:
# 只有当变量池中有图片时,LLM才需要使用这个工具
return len(self.list_default_image_variables()) > 0
```

View file

@ -146,13 +146,13 @@ from typing import Any, Dict, List, Union
class GoogleSearchTool(BuiltinTool):
def _invoke(self,
user_id: str,
tool_paramters: Dict[str, Any],
tool_parameters: Dict[str, Any],
) -> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
"""
invoke tools
"""
query = tool_paramters['query']
result_type = tool_paramters['result_type']
query = tool_parameters['query']
result_type = tool_parameters['result_type']
api_key = self.runtime.credentials['serpapi_api_key']
# TODO: search with serpapi
result = SerpAPI(api_key).run(query, result_type=result_type)
@ -163,7 +163,7 @@ class GoogleSearchTool(BuiltinTool):
```
### 参数
工具的整体逻辑都在`_invoke`方法中,这个方法接收两个参数:`user_id`和`tool_paramters`,分别表示用户ID和工具参数
工具的整体逻辑都在`_invoke`方法中,这个方法接收两个参数:`user_id`和`tool_parameters`,分别表示用户ID和工具参数
### 返回数据
在工具返回时,你可以选择返回一个消息或者多个消息,这里我们返回一个消息,使用`create_text_message`和`create_link_message`可以创建一个文本消息或者一个链接消息。
@ -195,7 +195,7 @@ class GoogleProvider(BuiltinToolProviderController):
}
).invoke(
user_id='',
tool_paramters={
tool_parameters={
"query": "test",
"result_type": "link"
},

View file

@ -1,7 +1,7 @@
from pydantic import BaseModel
from typing import Dict, Optional, Any, List
from core.tools.entities.tool_entities import ToolProviderType, ToolParamter
from core.tools.entities.tool_entities import ToolProviderType, ToolParameter
class ApiBasedToolBundle(BaseModel):
"""
@ -16,7 +16,7 @@ class ApiBasedToolBundle(BaseModel):
# operation_id
operation_id: str = None
# parameters
parameters: Optional[List[ToolParamter]] = None
parameters: Optional[List[ToolParameter]] = None
# author
author: str
# icon

View file

@ -88,11 +88,11 @@ class ToolInvokeMessageBinary(BaseModel):
url: str = Field(..., description="The url of the binary")
save_as: str = ''
class ToolParamterOption(BaseModel):
class ToolParameterOption(BaseModel):
value: str = Field(..., description="The value of the option")
label: I18nObject = Field(..., description="The label of the option")
class ToolParamter(BaseModel):
class ToolParameter(BaseModel):
class ToolParameterType(Enum):
STRING = "string"
NUMBER = "number"
@ -114,12 +114,12 @@ class ToolParamter(BaseModel):
default: Optional[str] = None
min: Optional[Union[float, int]] = None
max: Optional[Union[float, int]] = None
options: Optional[List[ToolParamterOption]] = None
options: Optional[List[ToolParameterOption]] = None
@classmethod
def get_simple_instance(cls,
name: str, llm_description: str, type: ToolParameterType,
required: bool, options: Optional[List[str]] = None) -> 'ToolParamter':
required: bool, options: Optional[List[str]] = None) -> 'ToolParameter':
"""
get a simple tool parameter
@ -129,9 +129,9 @@ class ToolParamter(BaseModel):
:param required: if the parameter is required
:param options: the options of the parameter
"""
# convert options to ToolParamterOption
# convert options to ToolParameterOption
if options:
options = [ToolParamterOption(value=option, label=I18nObject(en_US=option, zh_Hans=option)) for option in options]
options = [ToolParameterOption(value=option, label=I18nObject(en_US=option, zh_Hans=option)) for option in options]
return cls(
name=name,
label=I18nObject(en_US='', zh_Hans=''),
@ -183,7 +183,7 @@ class ToolProviderCredentials(BaseModel):
raise ValueError(f'invalid mode value {value}')
@staticmethod
def defaut(value: str) -> str:
def default(value: str) -> str:
return ""
name: str = Field(..., description="The name of the credentials")

View file

@ -4,7 +4,7 @@ from typing import List, Dict, Optional
from core.tools.entities.common_entities import I18nObject
from core.tools.entities.tool_entities import ToolProviderCredentials
from core.tools.tool.tool import ToolParamter
from core.tools.tool.tool import ToolParameter
class UserToolProvider(BaseModel):
class ProviderType(Enum):
@ -45,4 +45,4 @@ class UserTool(BaseModel):
name: str # identifier
label: I18nObject # label
description: I18nObject
parameters: Optional[List[ToolParamter]]
parameters: Optional[List[ToolParameter]]

View file

@ -4,7 +4,7 @@ class ToolProviderNotFoundError(ValueError):
class ToolNotFoundError(ValueError):
pass
class ToolParamterValidationError(ValueError):
class ToolParameterValidationError(ValueError):
pass
class ToolProviderCredentialValidationError(ValueError):

View file

@ -123,12 +123,12 @@ class ApiBasedToolProviderController(ToolProviderController):
return self.tools
def get_tools(self, user_id: str, tanent_id: str) -> List[ApiTool]:
def get_tools(self, user_id: str, tenant_id: str) -> List[ApiTool]:
"""
fetch tools from database
:param user_id: the user id
:param tanent_id: the tanent id
:param tenant_id: the tenant id
:return: the tools
"""
if self.tools is not None:
@ -136,9 +136,9 @@ class ApiBasedToolProviderController(ToolProviderController):
tools: List[Tool] = []
# get tanent api providers
# get tenant api providers
db_providers: List[ApiToolProvider] = db.session.query(ApiToolProvider).filter(
ApiToolProvider.tenant_id == tanent_id,
ApiToolProvider.tenant_id == tenant_id,
ApiToolProvider.name == self.identity.name
).all()

View file

@ -1,5 +1,5 @@
from typing import Any, Dict, List
from core.tools.entities.tool_entities import ToolProviderType, ToolParamter, ToolParamterOption
from core.tools.entities.tool_entities import ToolProviderType, ToolParameter, ToolParameterOption
from core.tools.tool.tool import Tool
from core.tools.entities.common_entities import I18nObject
from core.tools.provider.tool_provider import ToolProviderController
@ -71,7 +71,7 @@ class AppBasedToolProviderEntity(ToolProviderController):
variable_name = input_form[form_type]['variable_name']
options = input_form[form_type].get('options', [])
if form_type == 'paragraph' or form_type == 'text-input':
tool['parameters'].append(ToolParamter(
tool['parameters'].append(ToolParameter(
name=variable_name,
label=I18nObject(
en_US=label,
@ -82,13 +82,13 @@ class AppBasedToolProviderEntity(ToolProviderController):
zh_Hans=label
),
llm_description=label,
form=ToolParamter.ToolParameterForm.FORM,
type=ToolParamter.ToolParameterType.STRING,
form=ToolParameter.ToolParameterForm.FORM,
type=ToolParameter.ToolParameterType.STRING,
required=required,
default=default
))
elif form_type == 'select':
tool['parameters'].append(ToolParamter(
tool['parameters'].append(ToolParameter(
name=variable_name,
label=I18nObject(
en_US=label,
@ -99,11 +99,11 @@ class AppBasedToolProviderEntity(ToolProviderController):
zh_Hans=label
),
llm_description=label,
form=ToolParamter.ToolParameterForm.FORM,
type=ToolParamter.ToolParameterType.SELECT,
form=ToolParameter.ToolParameterForm.FORM,
type=ToolParameter.ToolParameterType.SELECT,
required=required,
default=default,
options=[ToolParamterOption(
options=[ToolParameterOption(
value=option,
label=I18nObject(
en_US=option,

View file

@ -13,7 +13,7 @@ class AzureDALLEProvider(BuiltinToolProviderController):
}
).invoke(
user_id='',
tool_paramters={
tool_parameters={
"prompt": "cute girl, blue eyes, white hair, anime style",
"size": "square",
"n": 1

View file

@ -10,7 +10,7 @@ from openai import AzureOpenAI
class DallE3Tool(BuiltinTool):
def _invoke(self,
user_id: str,
tool_paramters: Dict[str, Any],
tool_parameters: Dict[str, Any],
) -> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
"""
invoke tools
@ -28,19 +28,19 @@ class DallE3Tool(BuiltinTool):
}
# prompt
prompt = tool_paramters.get('prompt', '')
prompt = tool_parameters.get('prompt', '')
if not prompt:
return self.create_text_message('Please input prompt')
# get size
size = SIZE_MAPPING[tool_paramters.get('size', 'square')]
size = SIZE_MAPPING[tool_parameters.get('size', 'square')]
# get n
n = tool_paramters.get('n', 1)
n = tool_parameters.get('n', 1)
# get quality
quality = tool_paramters.get('quality', 'standard')
quality = tool_parameters.get('quality', 'standard')
if quality not in ['standard', 'hd']:
return self.create_text_message('Invalid quality')
# get style
style = tool_paramters.get('style', 'vivid')
style = tool_parameters.get('style', 'vivid')
if style not in ['natural', 'vivid']:
return self.create_text_message('Invalid style')

View file

@ -16,7 +16,7 @@ class ChartProvider(BuiltinToolProviderController):
}
).invoke(
user_id='',
tool_paramters={
tool_parameters={
"data": "1,3,5,7,9,2,4,6,8,10",
},
)

View file

@ -6,9 +6,9 @@ import io
from typing import Any, Dict, List, Union
class BarChartTool(BuiltinTool):
def _invoke(self, user_id: str, tool_paramters: Dict[str, Any]) \
def _invoke(self, user_id: str, tool_parameters: Dict[str, Any]) \
-> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
data = tool_paramters.get('data', '')
data = tool_parameters.get('data', '')
if not data:
return self.create_text_message('Please input data')
data = data.split(';')
@ -19,7 +19,7 @@ class BarChartTool(BuiltinTool):
else:
data = [float(i) for i in data]
axis = tool_paramters.get('x_axis', None) or None
axis = tool_parameters.get('x_axis', None) or None
if axis:
axis = axis.split(';')
if len(axis) != len(data):

View file

@ -8,14 +8,14 @@ from typing import Any, Dict, List, Union
class LinearChartTool(BuiltinTool):
def _invoke(self,
user_id: str,
tool_paramters: Dict[str, Any],
tool_parameters: Dict[str, Any],
) -> Union[ToolInvokeMessage, List[ToolInvokeMessage]]:
data = tool_paramters.get('data', '')
data = tool_parameters.get('data', '')
if not data:
return self.create_text_message('Please input data')
data = data.split(';')
axis = tool_paramters.get('x_axis', None) or None
axis = tool_parameters.get('x_axis', None) or None
if axis:
axis = axis.split(';')
if len(axis) != len(data):

Some files were not shown because too many files have changed in this diff Show more