agentscope.service

Import all service-related modules in the package.

class agentscope.service.ServiceResponse(status: ServiceExecStatus, content: Any)[源代码]

基类:dict

Used to wrap the execution results of the services

__init__(status: ServiceExecStatus, content: Any)[源代码]

Constructor of ServiceResponse

参数:
  • status (ServiceExeStatus) – The execution status of the service.

  • content (Any) – If the argument`status` is SUCCESS, content is the response. We use object here to support various objects, e.g. str, dict, image, video, etc. Otherwise, content is the error message.

class agentscope.service.ServiceExecStatus(value)[源代码]

基类:IntEnum

Enum for service execution status.

SUCCESS = 1
ERROR = -1
class agentscope.service.ServiceToolkit[源代码]

基类:object

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

__init__() None[源代码]

Initialize the service toolkit with a list of service functions.

service_funcs: dict[str, ServiceFunction]

The registered functions in the service toolkit.

add(service_func: Callable[[...], Any], **kwargs: Any) None[源代码]

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.

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

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

返回:

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

返回类型:

Tuple(Callable[…, Any], dict)

备注

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.

示例

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)
property json_schemas: dict

The json schema descriptions of the processed service funcs.

property tools_calling_format: str

The calling format of the tool functions.

property tools_instruction: str

The instruction of the tool functions.

parse_and_call_func(text_cmd: list[dict] | str) str[源代码]

Parse, check the text and call the function.

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

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.

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

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

返回:

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

返回类型:

Tuple(Callable[…, Any], dict)

备注

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.

示例

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
agentscope.service.get_help() None[源代码]

Get help message.

agentscope.service.execute_python_code(code: str, timeout: float | int | None = 300, use_docker: bool | str | None = None, maximum_memory_bytes: int | None = None) ServiceResponse[源代码]

Execute a piece of python code.

This function can run Python code provided in string format. It has the option to execute the code within a Docker container to provide an additional layer of security, especially important when running untrusted code.

WARNING: If use_docker is set to False, the code will be run directly in the host system’s environment. This poses a potential security risk if the code is untrusted. Only disable Docker if you are confident in the safety of the code being executed.

参数:
  • code (str, optional) – The Python code to be executed.

  • timeout (Optional[Union[int, float]], defaults to 300) – The maximum time (in seconds) allowed for the code to run. If the code execution time exceeds this limit, it will be terminated. Set to None for no time limit. Default is 300.

  • use_docker (Optional[Union[bool, str]], defaults to None) – Determines whether to execute the code within a Docker container. If False, the system’s native Python environment is used. When set to None, the function checks for Docker’s availability and uses it if present. When set to some string, will use the docker with string as the image name. Default is None.

  • maximum_memory_bytes (Optional[int], defaults to None) – The memory limit in bytes for the code execution. If not specified, there is no memory limit imposed.

返回:

A ServiceResponse containing two elements: output and error. Both output and error are strings that capture the standard output and standard error of the code execution, respectively.

返回类型:

ServiceResponse

备注

IPython-specific operations such as plt.show() for displaying matplotlib plots are currently not supported. This limitation stems from the non-interactive nature of the execution environment.

The argument timeout is not available in Windows OS, since the since signal.setitimer is only available in Unix.

agentscope.service.execute_shell_command(command: str) ServiceResponse[源代码]

Executes a given shell command.

参数:

command (str) – The shell command to execute.

返回:

Contains either the output from the shell command as a string if sucessful, or an error message include the error type.

返回类型:

ServiceResponse

备注

Use any bash/shell commands you want (e.g. find, grep, cat, ls), but note that : 1. interactive session commands (e.g. python, vim) or commands that change current state (e.g. cd that change the current directory) are NOT supported yet, so please do not invoke them. 2. be VERY CAREFUL when using commands that will change/edit the files current directory (e.g. rm, sed).

agentscope.service.create_file(file_path: str, content: str = '') ServiceResponse[源代码]

Create a file and write content to it.

参数:
  • file_path (str) – The path where the file will be created.

  • content (str) – Content to write into the file.

返回:

Where the boolean indicates success, and the str contains an error message if any, including the error type.

返回类型:

ServiceResponse

agentscope.service.delete_file(file_path: str) ServiceResponse[源代码]

Delete a file specified by the file path.

参数:

file_path (str) – The path of the file to be deleted.

返回:

Where the boolean indicates success, and the str contains an error message if any, including the error type.

返回类型:

ServiceResponse

agentscope.service.move_file(source_path: str, destination_path: str) ServiceResponse[源代码]

Move a file from a source path to a destination path.

参数:
  • source_path (str) – The current path of the file.

  • destination_path (str) – The new path for the file.

返回:

Where the boolean indicates success, and the str contains an error message if any, including the error type.

返回类型:

ServiceResponse

agentscope.service.create_directory(directory_path: str) ServiceResponse[源代码]

Create a directory at the specified path.

参数:

directory_path (str) – The path where the directory will be created.

返回:

where the boolean indicates success, and the str contains an error message if any, including the error type.

返回类型:

ServiceResponse

agentscope.service.delete_directory(directory_path: str) ServiceResponse[源代码]

Delete a directory and all of its contents.

参数:

directory_path (str) – The path of the directory to be deleted.

返回:

Where the boolean indicates success, and the str contains an error message if any, including the error type.

返回类型:

ServiceResponse

agentscope.service.move_directory(source_path: str, destination_path: str) ServiceResponse[源代码]

Move a directory from a source path to a destination path.

参数:
  • source_path (str) – The current path of the directory.

  • destination_path (str) – The new path for the directory.

返回:

Where the boolean indicates success, and the str contains an error message if any, including the error type.

返回类型:

ServiceResponse

agentscope.service.list_directory_content(directory_path: str) ServiceResponse[源代码]

List the contents of a directory. i.e. ls -a

参数:

directory_path (str) – The path of the directory to show.

返回:

The results contain a list of direcotry contents, or an error message if any, including the error type.

返回类型:

ServiceResponse

agentscope.service.get_current_directory() ServiceResponse[源代码]

Get the current working directory path.

返回:

The current working directory path, or an error message if any, including the error type.

返回类型:

ServiceResponse

agentscope.service.read_text_file(file_path: str) ServiceResponse[源代码]

Read the content of the text file.

参数:

file_path (str) – The path to the text file to be read.

返回:

A tuple (bool, str) where the boolean indicates success, and the str contains the file content or an error message if any, including the error type.

返回类型:

ServiceResponse

agentscope.service.write_text_file(file_path: str, content: str, overwrite: bool = False) ServiceResponse[源代码]

Write content to a text file.

参数:
  • file_path (str) – The path to the file where content will be written.

  • content (str) – Content to write into the file.

  • overwrite (bool, defaults to False) – Whether to overwrite the file if it already exists.

返回:

where the boolean indicates success, and the str contains an error message if any, including the error type.

返回类型:

ServiceResponse

agentscope.service.read_json_file(file_path: str) ServiceResponse[源代码]

Read and parse a JSON file.

参数:

file_path (str) – The path to the JSON file to be read.

返回:

Where the boolean indicates success, the Any is the parsed JSON content (typically a dict), and the str contains an error message if any, including the error type.

返回类型:

ServiceResponse

agentscope.service.write_json_file(file_path: str, data: Any, overwrite: bool = False) ServiceResponse[源代码]

Serialize data to a JSON file.

参数:
  • file_path (str) – The path to the file where the JSON data will be written.

  • data (Any) – The data to serialize to JSON.

  • overwrite (bool) – Whether to overwrite the file if it already exists.

返回:

where the boolean indicates success, and the str contains an error message if any, including the error type.

返回类型:

ServiceResponse

Search question in Bing Search API and return the searching results

参数:
返回:

A dictionary with two variables: status and content. The status variable is from the ServiceExecStatus enum, and content is a list of search results or error information, which depends on the status variable. For each searching result, it is a dictionary with keys ‘title’, ‘link’, and ‘snippet’.

返回类型:

ServiceResponse

示例

results = bing_search(question="What is an agent?",
                     bing_api_key="your bing api key",
                     num_results=2,
                     mkt="en-US")
print(results)

It returns the following dict.

{
    'status': <ServiceExecStatus.SUCCESS: 1>,
    'content': [
        {
            'title': 'What Is an Agent? Definition, Types of
                Agents, and Examples - Investopedia',
            'link':
            'https://www.investopedia.com/terms/a/agent.asp',
            'snippet': "An agent is someone that is given
                permission (either explicitly or assumed) to act
                on an individual's behalf and may do so in a
                variety of capacities. This could include
                selling a home, executing..."},
        {
            'title': 'AGENT Definition & Usage Examples |
                        Dictionary.com',
            'link': 'https://www.dictionary.com/browse/agent',
            'snippet': 'noun. a person who acts on behalf of
                another person, group, business, government,
                etc; representative. a person or thing that acts
                or has the power to act. a phenomenon,
                substance, or organism that exerts some force or
                effect: a chemical agent.'
        }
    ]
}

Search question in Google Search API and return the searching results

参数:
  • question (str) – The search query string.

  • api_key (str) – The API key provided for authenticating with the Google Custom Search JSON API.

  • cse_id (str) – The unique identifier of a programmable search engine to use.

  • num_results (int, defaults to 10) – The number of search results to return.

  • **kwargs (Any) – Additional keyword arguments to be included in the search query. For more details, please refer to https://developers.google.com/custom-search/v1/reference/rest/v1/cse/list

返回:

A dictionary with two variables: status and content. The status variable is from the ServiceExecStatus enum, and content is a list of search results or error information, which depends on the status variable. For each searching result, it is a dictionary with keys ‘title’, ‘link’, and ‘snippet’.

返回类型:

ServiceResponse

示例

results = google_search(
    'Python programming',
    'your_google_api_key',
    'your_cse_id',
    num_results=2
)
if results.status == ServiceExecStatus.SUCCESS:
    for result in results.content:
        print(result['title'], result['link'], result['snippet'])

Search arXiv paper by a given query string.

参数:
  • search_query (str) – The query string, supporting prefixes “all:”, “ti:”, “au:”, “abs:”, “co:”, “jr:”, “cat:”, and “rn:”, boolean operators “AND”, “OR” and “ANDNOT”. For example, searching for papers with title “Deep Learning” and author “LeCun” by a search_query ti:”Deep Learning” AND au:”LeCun”

  • id_list (List[str], defaults to None) – A list of arXiv IDs to search.

  • start (int, defaults to 0) – The index of the first search result to return.

  • max_results (Optional[int], defaults to None) – The maximum number of search results to return.

返回:

A dictionary with two variables: status and content. The status variable is from the ServiceExecStatus enum, and content is a list of search results or error information, which depends on the status variable.

返回类型:

ServiceResponse

agentscope.service.query_mysql(database: str, query: str, host: str, user: str, password: str, port: int, allow_change_data: bool = False, maxcount_results: int | None = None, **kwargs: Any) ServiceResponse[源代码]

Execute query within MySQL database.

参数:
  • database (str) – The name of the database to use.

  • query (str) – SQL query to execute.

  • host (str) – The host name or IP address of the MySQL server, e.g. “localhost”.

  • user (str) – The username of the MySQL account to use.

  • password (str) – The password of the MySQL account to use.

  • port (str) – The port number of the MySQL server, e.g. 3306.

  • allow_change_data (bool, defaults to False) – Whether to allow changing data in the database. Defaults to False to avoid accidental changes to the database.

  • maxcount_results (int, defaults to None) – The maximum number of results to return. Defaults to 100 to avoid too many results.

返回:

A ServiceResponse object that contains execution results or error message.

返回类型:

ServiceResponse

agentscope.service.query_sqlite(database: str, query: str, allow_change_data: bool = False, maxcount_results: int | None = None, **kwargs: Any) ServiceResponse[源代码]

Executes query within sqlite database.

参数:
  • database (str) – The name of the database to use.

  • query (str) – The query to execute.

  • allow_change_data (bool, defaults to False) – Whether to allow changing data in the database. Defaults to False to avoid accidental changes to the database.

  • maxcount_results (int, defaults to None) – The maximum number of results to return.

返回:

A ServiceResponse object that contains execution results or error message.

返回类型:

ServiceResponse

agentscope.service.query_mongodb(database: str, collection: str, query: dict, host: str, port: int, maxcount_results: int | None = None, **kwargs: Any) ServiceResponse[源代码]

Execute query within MongoDB database.

参数:
  • database (str) – The name of the database to use.

  • collection (str) – The name of the collection to use in mongodb.

  • query (dict) – The mongodb query to execute.

  • host (str) – The hostname or IP address of the MongoDB server.

  • port (int) – The port number of MongoDB server.

  • maxcount_results (int, defaults to None) – The maximum number of results to return. Defaults to 100 to avoid too many results.

  • **kwargs

返回:

A ServiceResponse object that contains execution results or error message.

返回类型:

ServiceResponse

备注

MongoDB is a little different from mysql and sqlite, for its operations corresponds to different functions. Now we only support find query and leave other operations in the future.

agentscope.service.cos_sim(a: list[Number], b: list[Number]) ServiceResponse[源代码]

Compute the cosine similarity between two different embeddings

参数:
  • a (Embedding) – Embedding

  • b (Embedding) – Embedding

返回:

A float.

返回类型:

ServiceResponse

agentscope.service.summarization(model: ModelWrapperBase, text: str, system_prompt: str = '\nYou are a helpful agent to summarize the text.\nYou need to keep all the key information of the text in the summary.\n', max_return_token: int = -1, token_limit_prompt: str = '\nSummarize the text after TEXT in less than {} tokens:\n') ServiceResponse[源代码]

Summarize the input text.

Summarization function (Notice: current version of token limitation is built with Open AI API)

参数:
  • model (ModelWrapperBase) – Model used to summarize provided text.

  • text (str) – Text to be summarized by the model.

  • system_prompt (str, defaults to _DEFAULT_SYSTEM_PROMPT) – Prompts as instruction for the system, will be as an instruction for the model.

  • max_return_token (int, defaults to -1) – Whether provide additional prompting instruction to limit the number of tokens in summarization returned by the model.

  • token_limit_prompt (str, defaults to _DEFAULT_TOKEN_LIMIT_PROMPT) – Prompt to instruct the model follow token limitation.

返回:

If the model successfully summarized the text, and the summarization satisfies the provided token limitation, return ServiceResponse with ServiceExecStatus.SUCCESS; otherwise return ServiceResponse with ServiceExecStatus.ERROR (if the summary is return successfully but exceed the token limits, the content contains the summary as well).

返回类型:

ServiceResponse

Example:

The default message with text to be summarized:

[
    {
        "role": "system",
        "name": "system",
        "content": "You are a helpful agent to summarize the text.\
        You need to keep all the key information of the text in the\
        summary."
    },
    {
        "role": "user",
        "name": "user",
        "content": text
    },
]

Messages will be processed by model.format() before feeding to models.

agentscope.service.retrieve_from_list(query: Any, knowledge: Sequence, score_func: Callable[[Any, Any], float], top_k: int | None = None, embedding_model: ModelWrapperBase | None = None, preserve_order: bool = True) ServiceResponse[源代码]

Retrieve data in a list.

Memory retrieval with user-defined score function. The score function is expected to take the query and one of the element in ‘knowledge’ (a list). This function retrieves top-k elements in ‘knowledge’ with HIGHEST scores. If the ‘query’ is a dict but has no embedding, we use the embedding model to embed the query.

参数:
  • query (Any) – A message to be retrieved.

  • knowledge (Sequence) – Data/knowledge to be retrieved from.

  • score_func (Callable[[Any, Any], float]) – User-defined function for comparing two messages.

  • top_k (int, defaults to None) – Maximum number of messages returned.

  • embedding_model (Optional[ModelWrapperBase], defaults to None) – A model to embed the query/message.

  • preserve_order (bool, defaults to True) – Whether to preserve the original order of the retrieved data. Defaults to True.

返回:

The top-k retrieved messages with HIGHEST scores.

返回类型:

ServiceResponse

agentscope.service.digest_webpage(web_text_or_url: str, model: ModelWrapperBase | None = None, html_selected_tags: Sequence[str] = ('h', 'p', 'li', 'div', 'a'), digest_prompt: str = "You're a web page analyser. You job is to extract importantand useful information from html or webpage description.\n") ServiceResponse[源代码]

Digest the given webpage.

参数:
  • web_text_or_url (str) – preprocessed web text or url to the web page

  • model (ModelWrapperBase) – the model to digest the web content

  • html_selected_tags (Sequence[str]) – the text in elements of html_selected_tags will be extracted and feed to the model

  • digest_prompt (str) – system prompt for the model to digest the web content

返回:

If successful, ServiceResponse object is returned with content field filled with the model output.

返回类型:

ServiceResponse

agentscope.service.load_web(url: str, keep_raw: bool = True, html_selected_tags: Sequence[str] | None = None, self_parse_func: Callable[[Response], Any] | None = None, timeout: int = 5) ServiceResponse[源代码]

Function for parsing and digesting the web page.

参数:
  • url (str) – the url of the web page

  • keep_raw (bool) – Whether to keep raw HTML. If True, the content is stored with key “raw”.

  • html_selected_tags (Optional[Sequence[str]]) – the text in elements of html_selected_tags will be extracted and stored with “html_to_text” key in return.

  • self_parse_func (Optional[Callable]) – if “self_parse_func” is not None, then the function will be invoked with the requests.Response as input. The result is stored with self_define_func key

  • timeout (int) – timeout parameter for requests.

返回:

If successful, ServiceResponse object is returned with content field is a dict, where keys are subset of:

”raw”: exists if keep_raw is True, store raw HTML content`;

”self_define_func”: exists if self_parse_func is provided, store the return of self_define_func;

”html_to_text”: exists if html_selected_tags is provided and not empty;

”json”: exists if url links to a json webpage, then it is parsed as json.

For example, ServiceResponse.content field is

{
    "raw": xxxxx,
    "selected_tags_text": xxxxx
}

返回类型:

ServiceResponse

agentscope.service.parse_html_to_text(html_text: str, html_selected_tags: Sequence[str] | None = None) str[源代码]

Parse the obtained HTML file.

参数:
  • html_text (str) – HTML source code

  • html_selected_tags (Optional[Sequence[str]]) – the text in elements of html_selected_tags will be extracted and returned.

返回:

If successful, ServiceResponse object is returned with content field is processed text content of the selected tags,

返回类型:

ServiceResponse

agentscope.service.download_from_url(url: str, filepath: str, timeout: int = 120, retries: int = 3) ServiceResponse[源代码]

Download file from the given url to the specified location.

参数:
  • url (str) – The URL of the file to download.

  • filepath (str) – The path to save the downloaded file.

  • timeout (int, defaults to 120) – The timeout for the download request.

  • retries (int, defaults to 3) – The number of retries for the download request.

返回:

A ServiceResponse object that contains execution results or error message.

返回类型:

ServiceResponse

agentscope.service.dblp_search_publications(question: str, num_results: int = 30, start: int = 0, num_completion: int = 10) ServiceResponse[源代码]

Search publications in the DBLP database.

参数:
  • question (str) – The search query string.

  • num_results (int, defaults to 30) – The number of search results to return.

  • start (int, defaults to 0) – The index of the first search result to return.

  • num_completion (int, defaults to 10) – The number of completions to generate.

返回:

A dictionary containing status and content. The status attribute is from the ServiceExecStatus enum, indicating success or error. The content is a list of parsed publication data if successful, or an error message if failed. Each item in the list contains publication information includes title, authors, venue, pages, year, type, DOI, and URL.

返回类型:

ServiceResponse

示例

It returns the following structure:

{
    'status': <ServiceExecStatus.SUCCESS: 1>,
    'content': [
        {
            'title': 'Power transformers fault diagnosis
            based on a meta-learning approach to kernel
            extreme learning machine with opposition-based
            learning sparrow search algorithm.',
            'venue': 'J. Intell. Fuzzy Syst.',
            'pages': '455-466',
            'year': '2023',
            'type': 'Journal Articles',
            'doi': '10.3233/JIFS-211862',
            'url': 'https://dblp.org/rec/journals/jifs/YuTZTCH23',
            'authors': 'Song Yu, Weimin Tan, Chengming Zhang,
            Chao Tang, Lihong Cai, Dong Hu'
        },
        {
            'title': 'Performance comparison of Extreme Learning
            Machinesand other machine learning methods
            on WBCD data set.',
            'venue': 'SIU',
            'pages': '1-4',
            'year': '2021',
            'type': 'Conference and Workshop Papers',
            'doi': '10.1109/SIU53274.2021.9477984',
            'url': 'https://dblp.org/rec/conf/siu/KeskinDAY21',
            'authors': 'Ömer Selim Keskin, Akif Durdu,
            Muhammet Fatih Aslan, Abdullah Yusefi'
        }
    ]
}
agentscope.service.dblp_search_authors(question: str, num_results: int = 30, start: int = 0, num_completion: int = 10) ServiceResponse[源代码]

Search for author information in the DBLP database.

参数:
  • question (str) – The search query string.

  • num_results (int, defaults to 30) – The number of search results to return.

  • start (int, defaults to 0) – The index of the first search result to return.

  • num_completion (int, defaults to 10) – The number of completions to generate.

返回:

A dictionary containing status and content. The status attribute is from the ServiceExecStatus enum, indicating the success or error of the search. The content is a list of parsed author data if successful, or an error message if failed. Each item in the list contains author information including their name, URL, and affiliations.

返回类型:

ServiceResponse

示例

search_results = dblp_search_authors(question="Liu ZiWei",
                                     num_results=3,
                                     results_per_page=1,
                                     num_completion=1)
print(search_results)

It returns the following structure:

{
    'status': <ServiceExecStatus.SUCCESS: 1>,
    'content': [
        {
            'author': 'Ziwei Liu 0001',
            'url': 'https://dblp.org/pid/05/6300-1',
            'affiliations': 'Advantech Singapore Pte Ltd,
            Singapore;
            National University of Singapore,
            Department of Computer Science, Singapore'
        },
        {
            'author': 'Ziwei Liu 0002',
            'url': 'https://dblp.org/pid/05/6300-2',
            'affiliations': 'Nanyang Technological University,
            S-Lab, Singapore;
            Chinese University of Hong Kong,
            Department of Information Engineering,
            Hong Kong'
        }
    ]
}
agentscope.service.dblp_search_venues(question: str, num_results: int = 30, start: int = 0, num_completion: int = 10) ServiceResponse[源代码]

Search for venue information in the DBLP database.

参数:
  • question (str) – The search query string.

  • num_results (int, defaults to 30) – The number of search results to return.

  • start (int, defaults to 0) – The index of the first search result to return.

  • num_completion (int, defaults to 10) – The number of completions to generate.

返回:

A dictionary containing status and content. The status attribute is from the ServiceExecStatus enum, indicating the success or error of the search. The content is a list of parsed venue data if successful, or an error message if failed. Each item in the list contains venue information including its name, acronym, type, and URL.

返回类型:

ServiceResponse

示例

search_results = dblp_search_venues(question="AAAI",
                                     num_results=1,
                                     results_per_page=1,
                                     num_completion=1)
print(search_results)

It returns the following structure:

{
    'status': <ServiceExecStatus.SUCCESS: 1>,
    'content': [
        {
            'venue': 'AAAI Conference on Artificial Intelligence
            (AAAI)',
            'acronym': 'AAAI',
            'type': 'Conference or Workshop',
            'url': 'https://dblp.org/db/conf/aaai/'
        },
        {
            'venue': ''AAAI Fall Symposium Series',
            'acronym': 'No acronym available',
            'type': 'Conference or Workshop',
            'url': 'https://dblp.org/db/conf/aaaifs/'
        }
    ]
}
class agentscope.service.ServiceFactory[源代码]

基类:object

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

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

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.

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

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

返回:

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

返回类型:

Tuple(Callable[…, Any], dict)

备注

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.

示例

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