agentscope.service.service_toolkit

Service Toolkit for service function usage.

class ServiceFunction(name: str, original_func: Callable, processed_func: Callable, json_schema: dict)[source]

Bases: object

The service function class.

json_schema: dict

The JSON schema description of the service function.

name: str

The name of the service function.

original_func: Callable

The original function before processing.

processed_func: Callable

The processed function that can be called by the model directly.

require_args: bool

Whether calling the service function requests arguments. Some arguments may have default values, so it is not necessary to provide all arguments.

class ServiceToolkit[source]

Bases: object

A service toolkit class that turns service function into string prompt format.

add(service_func: Callable[[...], Any], **kwargs: Any) None[source]

Add a service function to the toolkit, which will be processed into a tool function that can be called by the model directly, and registered in processed_funcs.

Parameters:
  • service_func (Callable[…, Any]) – The service function to be called.

  • kwargs (Any) – The arguments to be passed to the service function.

Returns:

A tuple of tool function and a dict in JSON Schema format to describe the function.

Return type:

Tuple(Callable[…, Any], dict)

Note

The description of the function and arguments are extracted from its docstring automatically, which should be well-formatted in Google style. Otherwise, their descriptions in the returned dictionary will be empty.

Suggestions:

1. The name of the service function should be self-explanatory, so that the agent can understand the function and use it properly. 2. The typing of the arguments should be provided when defining the function (e.g. def func(a: int, b: str, c: bool)), so that the agent can specify the arguments properly. 3. The execution results should be a ServiceResponse object.

Example

def bing_search(query: str, api_key: str, num_results=10):
    """Search the query in Bing search engine.

        Args:
            query: (`str`):
                The string query to search.
            api_key: (`str`):
                The API key for Bing search.
            num_results: (`int`, optional):
                The number of results to return, default to 10.
    """

    # ... Your implementation here ...
    return ServiceResponse(status, output)
add_mcp_servers(server_configs: Dict) None[source]

Add mcp servers to the toolkit.

Parameters:

server_configs (Dict) –

A dictionary containing the configuration for MCP servers. The configuration follows the Model Context Protocol specification and can be defined in TypeScript, but is available as JSON Schema for wider compatibility.

Fields:
  • ”mcpServers”: A dictionary where each key is the server

name and the value is its configuration.

Field Details:
  • ”command”: Specifies the command to execute,

which follows the stdio protocol for communication. - “args”: A list of arguments to be passed to the command. - “url”: Specifies the server’s URL, which follows the Server-Sent Events (SSE) protocol for data transmission.

Example

configs = {
“mcpServers”: {
“xxxx”: {

“command”: “npx”, “args”: [

”-y”, “@modelcontextprotocol/xxxx”

]

}, “yyyy”: {

}

}

}

classmethod get(service_func: Callable[[...], Any], **kwargs: Any) Tuple[Callable[[...], Any], dict][source]

Convert a service function into a tool function that agent can use, and generate a dictionary in JSON Schema format that can be used in OpenAI API directly. While for open-source model, developers should handle the conversation from json dictionary to prompt.

Parameters:
  • service_func (Callable[…, Any]) – The service function to be called.

  • kwargs (Any) – The arguments to be passed to the service function.

Returns:

A tuple of tool function and a dict in JSON Schema format to describe the function.

Return type:

Tuple(Callable[…, Any], dict)

Note

The description of the function and arguments are extracted from its docstring automatically, which should be well-formatted in Google style. Otherwise, their descriptions in the returned dictionary will be empty.

Suggestions:

1. The name of the service function should be self-explanatory, so that the agent can understand the function and use it properly. 2. The typing of the arguments should be provided when defining the function (e.g. def func(a: int, b: str, c: bool)), so that the agent can specify the arguments properly.

Example

def bing_search(query: str, api_key: str, num_results: int=10):
    '''Search the query in Bing search engine.

    Args:
        query (str):
            The string query to search.
        api_key (str):
            The API key for Bing search.
        num_results (int):
            The number of results to return, default to 10.
    '''
    pass
parse_and_call_func(tool_calls: ToolUseBlock | list[ToolUseBlock], tools_api_mode: bool = False, raise_exception: bool = False) Msg[source]

Execute the tool functions with the given arguments, and return the execution results.

Parameters:
  • tool_calls (Union[ToolUseBlock, list[ToolUseBlock]]) – A or a list of tool use blocks indicating the function calls.

  • tools_api_mode (bool, defaults to False) – If False, the execution results will be combined into a string content. If True, the results will be ContentBlock objects.

  • raise_exception (bool, defaults to False) – Whether to raise exceptions when the function call fails. If set to False, the error message will be wrapped in the ToolResultBlock and returned.

Returns:

A list of tool result blocks indicating the results of the function calls.

Return type:

list[ToolResultBlock]

property json_schemas: dict

The json schema descriptions of the processed service funcs.

service_funcs: dict[str, ServiceFunction]

The registered functions in the service toolkit.

property tools_calling_format: str

The calling format of the tool functions.

property tools_instruction: str

The instruction of the tool functions.