precommit run all (#134)

This commit is contained in:
liukuikun
2024-01-31 21:09:19 +08:00
committed by GitHub
parent 190fb731be
commit d61dc03079
28 changed files with 233 additions and 222 deletions

View File

@@ -22,7 +22,8 @@ English | [简体中文](README_zh-CN.md) | [日本語](README_ja_JP.md) | [ह
<div align="center">
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
</div>
## Getting Started
@@ -69,7 +70,8 @@ Lagent is a lightweight open-source framework that allows users to efficiently b
</a>
### All Thanks To Our Contributors:
<a href="https://github.com/InternLM/lagent/graphs/contributors">
<a href="https://github.com/InternLM/lagent/graphs/contributors">
<img src="https://contrib.rocks/image?repo=InternLM/lagent" />
</a>

View File

@@ -18,7 +18,8 @@ English | [简体中文](README_zh-CN.md) | [日本語](README_ja_JP.md) | [ह
<div align="center">
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
</div>
## 시작하기
@@ -64,4 +65,5 @@ Lagent는 사용자가 효율적으로 대규모 언어 모델(LLM) 기반 에
## 라이선스
이 프로젝트는 [Apache 2.0](LICENSE) 하에 공개되었습니다.
<p align="right"><a href="#top">🔼 Back to top</a></p>

View File

@@ -14,7 +14,8 @@ English | [简体中文](README_zh-CN.md) | [日本語](README_ja_JP.md) | [ह
<div align="center">
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
</div>
## शुरू करना
@@ -46,4 +47,5 @@ Lagent एक हल्का ओपन-सोर्स फ्रेमवर्
## लाइसेंस
यह प्रोजेक्ट [Apache 2.0 license](LICENSE) के तहत जारी किया गया है।
<p align="right"><a href="#top">🔼 Back to top</a></p>

View File

@@ -18,9 +18,9 @@ English | [简体中文](README_zh-CN.md) | [日本語](README_ja_JP.md) | [ह
<div align="center">
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
</div>
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
</div>
## শুরু করা

View File

@@ -18,7 +18,8 @@ English | [简体中文](README_zh-CN.md) | [日本語](README_ja_JP.md) | [ह
<div align="center">
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
</div>
## はじめに
@@ -51,4 +52,5 @@ Lagent は、大規模言語モデル(LLM)ベースのエージェントを効
## ライセンス
このプロジェクトは [Apache 2.0 license](LICENSE) の下でリリースされています。
<p align="right"><a href="#top">🔼 Back to top</a></p>

View File

@@ -18,7 +18,8 @@ English | [简体中文](README_zh-CN.md) | [日本語](README_ja_JP.md) | [ह
<div align="center">
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
[![Alt text](https://img.youtube.com/vi/YAelRLi0Zak/0.jpg)](https://www.youtube.com/watch?v=YAelRLi0Zak)
</div>
[English](README.md) | 简体中文
@@ -75,4 +76,5 @@ Lagent 是一个轻量级、开源的基于大语言模型的智能体agent
## 开源许可证
该项目采用[Apache 2.0 开源许可证](LICENSE)。
<p align="right"><a href="#top">🔼 Back to top</a></p>

View File

@@ -6,7 +6,7 @@ This page contains auto-generated API reference documentation.
.. toctree::
:titlesonly:
:maxdepth: 3
{% for page in pages %}
{% if page.top_level_object and page.display %}
{{ page.include_path }}

View File

@@ -8,8 +8,8 @@ Actions, also called **tools**, provide a suite of functions LLM-driven agents c
There are two categories of tools:
* tool: provide only one API to call.
* toolkit: implement multiple APIs that undertake different sub-tasks.
- tool: provide only one API to call.
- toolkit: implement multiple APIs that undertake different sub-tasks.
### Tool Description
@@ -36,7 +36,6 @@ In some situations there may be optional `return_data`, `parameter_description`
`parameter_description` is usually inserted into the tool description automatically by the action's parser. It will be introduced in [Interface Design](#interface-design) .
```
For toolkits, the description is very similar but nest submethods
```python
@@ -171,39 +170,41 @@ Only Google style Python docstrings is currently supported.
`BaseAction(description=None, parser=JsonParser, enable=True)` is the base class all actions should inherit from. It takes three initialization arguments
* **description**: a tool description dictionary, used set instance attribute `description`. Mostly you don't need explicitly pass this argument since the meta class of `BaseAction` will search methods decorated by `tool_api` and assemble their `api_description` as a class attribute `__tool_description__`, and if the initial `description` is left null, then `__tool_description__` will be copied as `description`.
* **parser**: `BaseParser` class. It will instantialize a parser used to validate the arguments of APIs in `description`.
- **description**: a tool description dictionary, used set instance attribute `description`. Mostly you don't need explicitly pass this argument since the meta class of `BaseAction` will search methods decorated by `tool_api` and assemble their `api_description` as a class attribute `__tool_description__`, and if the initial `description` is left null, then `__tool_description__` will be copied as `description`.
For example, `JsonParser` requires arguments passed in the format of JSON or `dict`. To make LLMs aware of this, It inserts a field `parameter_description` into the `description`.
- **parser**: `BaseParser` class. It will instantialize a parser used to validate the arguments of APIs in `description`.
```python
from lagent import BaseAction
For example, `JsonParser` requires arguments passed in the format of JSON or `dict`. To make LLMs aware of this, It inserts a field `parameter_description` into the `description`.
action = BaseAction(
{
'name': 'bold',
'description': 'a function used to make text bold',
'parameters': [
{
'name': 'text', 'type': 'STRING', 'description': 'input content'
}
],
'required': ['text']
}
)
action.description
```
```python
from lagent import BaseAction
```python
{'name': 'bold',
'description': 'a function used to make text bold',
'parameters': [{'name': 'text',
'type': 'STRING',
'description': 'input content'}],
'required': ['text'],
'parameter_description': '如果调用该工具你必须使用Json格式 {key: value} 传参其中key为参数名称'}
```
* **enable**: specify whether the tool is available.
action = BaseAction(
{
'name': 'bold',
'description': 'a function used to make text bold',
'parameters': [
{
'name': 'text', 'type': 'STRING', 'description': 'input content'
}
],
'required': ['text']
}
)
action.description
```
```python
{'name': 'bold',
'description': 'a function used to make text bold',
'parameters': [{'name': 'text',
'type': 'STRING',
'description': 'input content'}],
'required': ['text'],
'parameter_description': '如果调用该工具你必须使用Json格式 {key: value} 传参其中key为参数名称'}
```
- **enable**: specify whether the tool is available.
### Custom Action
@@ -215,7 +216,7 @@ A simple tool must have its `run` method implemented, while APIs of toolkits sho
```python
class Bold(BaseAction):
def run(self, text: str):
"""make text bold
@@ -254,7 +255,7 @@ class PhraseEmphasis(BaseAction):
"""
return '*' + text + '*'
# Inspect the default description
# Inspect the default description
# Bold.__tool_description__, PhraseEmphasis.__tool_description__
```
@@ -283,6 +284,7 @@ list_tools()
'Bold',
'PhraseEmphasis']
```
Create a `PhraseEmphasis` object
```python
@@ -309,24 +311,23 @@ action.description
'parameter_description': '如果调用该工具你必须使用Json格式 {key: value} 传参其中key为参数名称'}]}
```
## Tool Calling
### Run a Tool
`__call__` method of `Action` takes two arguments
* `inputs`: It depends on the action's parser. Often a string in specific formats generated by LLMs.
+ `JsonParser`: Allow passing arguements in the format of JSON string or Python `dict`.
+ `TupleParser`: Allow passing arguments in the format of tuple string format or Python `tuple`.
* `name`: Which API to call. Default is `run`.
- `inputs`: It depends on the action's parser. Often a string in specific formats generated by LLMs.
- `JsonParser`: Allow passing arguments in the format of JSON string or Python `dict`.
- `TupleParser`: Allow passing arguments in the format of tuple string format or Python `tuple`.
- `name`: Which API to call. Default is `run`.
It returns an `ActionReturn` object which encapsulates calling details
* `args`: Dictionary of action inputs.
* `type`: Action name.
* `result`: List of dicts. Each contains two keys: 'type' and 'content'. when errors occur, it is `None`.
* `errmsg`: Error message. Default is `None`.
- `args`: Dictionary of action inputs.
- `type`: Action name.
- `result`: List of dicts. Each contains two keys: 'type' and 'content'. when errors occur, it is `None`.
- `errmsg`: Error message. Default is `None`.
Below is an example

View File

@@ -6,7 +6,7 @@ This page contains auto-generated API reference documentation.
.. toctree::
:titlesonly:
:maxdepth: 3
{% for page in pages %}
{% if page.top_level_object and page.display %}
{{ page.include_path }}

View File

@@ -8,8 +8,8 @@
有两种类型的工具:
* 简单工具: 只提供一个API接口供调用。
* 工具包: 实现多个API接口承担不同的子任务。
- 简单工具: 只提供一个API接口供调用。
- 工具包: 实现多个API接口承担不同的子任务。
### 工具描述
@@ -29,6 +29,7 @@ TOOL_DESCRIPTION = {
'required': ['text'], # 指定必需的参数名
}
```
在某些情况下,可能还包含 `return_data``parameter_description` 字段,分别描述返回内容及参数传递格式。
```{attention}
@@ -169,38 +170,39 @@ def list_args(a: str, b: int, c: float = 0.0) -> dict:
`BaseAction(description=None, parser=JsonParser, enable=True)` 是所有动作应该继承的基类,它接收三个初始化参数:
* **description**:一个工具描述的字典,用于设置实例属性 `description`。通常不需要显式地传递这个参数,因为 `BaseAction` 的元类将查找被 `tool_api` 装饰的方法,并组装它们的 `api_description` 构造一个类属性 `__tool_description__`,如果实例化时 `description` 为空,那么该实例属性将置为 `__tool_description__`。
* **parser**`BaseParser` 类,用于实例化一个动作解析器校验 `description` 所描述的工具的参数。例如,`JsonParser` 会要求模型在调用工具时传入一个 JSON 格式字符串或者 Python 字典,为了让 LLM 感知到该指令,它会在 `description` 中插入一个 `parameter_description` 字段。
- **description**:一个工具描述的字典,用于设置实例属性 `description`。通常不需要显式地传递这个参数,因为 `BaseAction` 的元类将查找被 `tool_api` 装饰的方法,并组装它们的 `api_description` 构造一个类属性 `__tool_description__`,如果实例化时 `description` 为空,那么该实例属性将置为 `__tool_description__`。
```python
from lagent import BaseAction
- **parser**`BaseParser` 类,用于实例化一个动作解析器校验 `description` 所描述的工具的参数。例如,`JsonParser` 会要求模型在调用工具时传入一个 JSON 格式字符串或者 Python 字典,为了让 LLM 感知到该指令,它会在 `description` 中插入一个 `parameter_description` 字段。
action = BaseAction(
{
'name': 'bold',
'description': 'a function used to make text bold',
'parameters': [
{
'name': 'text', 'type': 'STRING', 'description': 'input content'
}
],
'required': ['text']
}
)
action.description
```
```python
from lagent import BaseAction
```python
{'name': 'bold',
'description': 'a function used to make text bold',
'parameters': [{'name': 'text',
'type': 'STRING',
'description': 'input content'}],
'required': ['text'],
'parameter_description': '如果调用该工具你必须使用Json格式 {key: value} 传参其中key为参数名称'}
```
action = BaseAction(
{
'name': 'bold',
'description': 'a function used to make text bold',
'parameters': [
{
'name': 'text', 'type': 'STRING', 'description': 'input content'
}
],
'required': ['text']
}
)
action.description
```
* **enable**: 指明该动作是否生效。
```python
{'name': 'bold',
'description': 'a function used to make text bold',
'parameters': [{'name': 'text',
'type': 'STRING',
'description': 'input content'}],
'required': ['text'],
'parameter_description': '如果调用该工具你必须使用Json格式 {key: value} 传参其中key为参数名称'}
```
- **enable**: 指明该动作是否生效。
### 自定义动作
@@ -212,7 +214,7 @@ def list_args(a: str, b: int, c: float = 0.0) -> dict:
```python
class Bold(BaseAction):
def run(self, text: str):
"""make text bold
@@ -307,24 +309,23 @@ action.description
'parameter_description': '如果调用该工具你必须使用Json格式 {key: value} 传参其中key为参数名称'}]}
```
## 工具调用
### 执行工具
`Action` 的 `__call__` 方法需要传入两个参数
* `inputs`: 其类型与动作绑定的 `BaseParser` 相关,通常是由大语言模型生成的字符串。
+ `JsonParser`: 允许传入 JSON 格式字符串或 Python 字典。
+ `TupleParser`: 允许传入字面量为元组的字符串或 Python 元组。
* `name`: 调用哪个 API默认为 `run`。
- `inputs`: 其类型与动作绑定的 `BaseParser` 相关,通常是由大语言模型生成的字符串。
- `JsonParser`: 允许传入 JSON 格式字符串或 Python 字典。
- `TupleParser`: 允许传入字面量为元组的字符串或 Python 元组。
- `name`: 调用哪个 API默认为 `run`。
工具会返回一个封装了调用细节的 `ActionReturn` 对象。
* `args`: 一个字典,表示该动作的入参。
* `type`: 动作名称。
* `result`: 以字典为成员的列表,每个字典包含两个键——'type' 和 'content',发生异常时该字段为 `None`。
* `errmsg`: 错误信息,默认为 `None`。
- `args`: 一个字典,表示该动作的入参。
- `type`: 动作名称。
- `result`: 以字典为成员的列表,每个字典包含两个键——'type' 和 'content',发生异常时该字段为 `None`。
- `errmsg`: 错误信息,默认为 `None`。
以下是一个例子:

View File

@@ -23,10 +23,10 @@ __all__ = [
def list_tools(with_class: bool = False):
"""List available tools
"""List available tools.
Args:
with_class (bool): whether to return the action class along
with_class (bool): whether to return the action class along
with its name. Defaults to ``False``.
Returns:
@@ -37,7 +37,7 @@ def list_tools(with_class: bool = False):
def get_tool_cls(specifier: str) -> Type[BaseAction]:
"""Get the action class
"""Get the action class.
Args:
specifier (:class:`str`): tool name
@@ -49,7 +49,7 @@ def get_tool_cls(specifier: str) -> Type[BaseAction]:
def get_tool(specifier: str, *args, **kwargs) -> BaseAction:
"""Instantiate an action
"""Instantiate an action.
Args:
specifier (str): tool name

View File

@@ -28,60 +28,60 @@ def tool_api(func: Optional[Callable] = None,
explode_return: bool = False,
returns_named_value: bool = False,
**kwargs):
"""Turn functions into tools. It will parse typehints as well as docstrings
to build the tool description and attach it to functions via an attribute
"""Turn functions into tools. It will parse typehints as well as docstrings
to build the tool description and attach it to functions via an attribute
``api_description``.
Examples:
.. code-block:: python
# typehints has higher priority than docstrings
from typing import Annotated
@tool_api
def add(a: Annotated[int, 'augend'], b: Annotated[int, 'addend'] = 1):
'''Add operation
Args:
x (int): a
y (int): b
'''
return a + b
print(add.api_description)
Args:
func (Optional[Callable]): function to decorate. Defaults to ``None``.
explode_return (bool): whether to flatten the dictionary or tuple return
as the ``return_data`` field. When enabled, it is recommended to
explode_return (bool): whether to flatten the dictionary or tuple return
as the ``return_data`` field. When enabled, it is recommended to
annotate the member in docstrings. Defaults to ``False``.
.. code-block:: python
@tool_api(explode_return=True)
def foo(a, b):
'''A simple function
Args:
a (int): a
b (int): b
Returns:
dict: information of inputs
* x: value of a
* y: value of b
'''
return {'x': a, 'y': b}
print(foo.api_description)
returns_named_value (bool): whether to parse ``thing: Description`` in
returns sections as a name and description, rather than a type and
description. When true, type must be wrapped in parentheses:
``(int): Description``. When false, parentheses are optional but
returns_named_value (bool): whether to parse ``thing: Description`` in
returns sections as a name and description, rather than a type and
description. When true, type must be wrapped in parentheses:
``(int): Description``. When false, parentheses are optional but
the items cannot be named: ``int: Description``. Defaults to ``False``.
Returns:
Callable: wrapped function or partial decorator
@@ -208,7 +208,7 @@ def tool_api(func: Optional[Callable] = None,
class ToolMeta(ABCMeta):
"""Metaclass of tools"""
"""Metaclass of tools."""
def __new__(mcs, name, base, attrs):
is_toolkit, tool_desc = True, dict(
@@ -260,21 +260,21 @@ class BaseAction(metaclass=AutoRegister(TOOL_REGISTRY, ToolMeta)):
action's inputs and outputs. Defaults to :class:`JsonParser`.
enable (:class:`bool`): Whether the action is enabled. Defaults to
``True``.
Examples:
* simple tool
.. code-block:: python
class Bold(BaseAction):
'''Make text bold'''
def run(self, text: str):
'''
Args:
text (str): input text
Returns:
str: bold text
'''
@@ -285,31 +285,31 @@ class BaseAction(metaclass=AutoRegister(TOOL_REGISTRY, ToolMeta)):
* toolkit with multiple APIs
.. code-block:: python
class Calculator(BaseAction):
'''Calculator'''
@tool_api
def add(self, a, b):
'''Add operation
Args:
a (int): augend
b (int): addend
Returns:
int: sum
'''
return a + b
@tool_api
@tool_api
def sub(self, a, b):
'''Subtraction operation
Args:
a (int): minuend
b (int): subtrahend
Returns:
int: difference
'''
@@ -376,7 +376,7 @@ class BaseAction(metaclass=AutoRegister(TOOL_REGISTRY, ToolMeta)):
@property
def description(self) -> dict:
"""Description of the tool"""
"""Description of the tool."""
return self._description
def __repr__(self):

View File

@@ -9,7 +9,7 @@ from lagent.actions.parser import BaseParser, JsonParser
class BINGMap(BaseAction):
"""BING Map plugin for looking up map information"""
"""BING Map plugin for looking up map information."""
def __init__(self,
key: Optional[str] = None,
@@ -84,7 +84,7 @@ class BINGMap(BaseAction):
location (:class:`str`): the location need to get coordinates.
Returns:
:class:`dict`: coordinates information
:class:`dict`: coordinates information
* latitude (float): the latitude of the location.
* longitude (float): the longitude of the location.
"""
@@ -102,10 +102,10 @@ class BINGMap(BaseAction):
places: str = 'unknown',
latitude: float = 0.0,
longitude: float = 0.0,
radius: int = 5000) -> dict: # radius in meters
radius: int = 5000) -> dict:
"""Search for places nearby a location, within a given radius, and \
return the results into a list. You can use either the places name or the \
latitude and longitude.
return the results into a list. You can use either the places name or
the \\ latitude and longitude.
Args:
search_term (:class:`str`): the place name.

View File

@@ -9,7 +9,7 @@ from .parser import BaseParser, JsonParser
class GoogleScholar(BaseAction):
"""Plugin for google scholar search
"""Plugin for google scholar search.
Args:
api_key (str): API KEY to use serper google search API,
@@ -52,7 +52,8 @@ class GoogleScholar(BaseAction):
filter: Optional[str] = None,
as_vis: Optional[str] = None,
) -> dict:
"""Search for scholarly articles based on a query according to the google scholar
"""Search for scholarly articles based on a query according to the
google scholar.
Args:
query (str): The query to search for.
@@ -132,7 +133,8 @@ class GoogleScholar(BaseAction):
no_cache: Optional[bool] = None,
async_req: Optional[bool] = None,
output: Optional[str] = None) -> dict:
"""Search for an author's information by author's id provided by get_author_id.
"""Search for an author's information by author's id provided by
get_author_id.
Args:
author_id (str): Required. The ID of an author.
@@ -190,7 +192,8 @@ class GoogleScholar(BaseAction):
no_cache: Optional[bool] = None,
async_: Optional[bool] = None,
output: Optional[str] = 'json') -> dict:
"""Function to get MLA citation format by an identification of organic_result's id provided by search_google_scholar.
"""Function to get MLA citation format by an identification of
organic_result's id provided by search_google_scholar.
Args:
q (str): ID of an individual Google Scholar organic search result.
@@ -230,20 +233,26 @@ class GoogleScholar(BaseAction):
no_cache: Optional[bool] = False,
_async: Optional[bool] = False,
output: Optional[str] = 'json') -> dict:
"""The getAuthorId function is used to get the author's id by his or her name.
"""The getAuthorId function is used to get the author's id by his or
her name.
Args:
mauthors (str): Defines the author you want to search for.
hl (Optional[str]): Defines the language to use for the Google Scholar Profiles search. It's a two-letter language code. (e.g., 'en' for English, 'es' for Spanish, or 'fr' for French). Defaults to 'en'.
after_author (Optional[str]): Defines the next page token. It is used for retrieving the next page results. The parameter has the precedence over before_author parameter. Defaults to None.
before_author (Optional[str]): Defines the previous page token. It is used for retrieving the previous page results. Defaults to None.
no_cache (Optional[bool]): Will force SerpApi to fetch the Google Scholar Profiles results even if a cached version is already present. Defaults to False.
_async (Optional[bool]): Defines the way you want to submit your search to SerpApi. Defaults to False.
output (Optional[str]): Defines the final output you want. It can be set to 'json' (default) to get a structured JSON of the results, or 'html' to get the raw html retrieved. Defaults to 'json'.
Args:
mauthors (str): Defines the author you want to search for.
hl (Optional[str]): Defines the language to use for the Google Scholar Profiles search. It's a two-letter \
language code. (e.g., 'en' for English, 'es' for Spanish, or 'fr' for French). Defaults to 'en'.
after_author (Optional[str]): Defines the next page token. It is used for retrieving the next page \
results. The parameter has the precedence over before_author parameter. Defaults to None.
before_author (Optional[str]): Defines the previous page token. It is used for retrieving the previous \
page results. Defaults to None.
no_cache (Optional[bool]): Will force SerpApi to fetch the Google Scholar Profiles results even if a \
cached version is already present. Defaults to False.
_async (Optional[bool]): Defines the way you want to submit your search to SerpApi. Defaults to False.
output (Optional[str]): Defines the final output you want. It can be set to 'json' (default) to get a \
structured JSON of the results, or 'html' to get the raw html retrieved. Defaults to 'json'.
Returns:
:class:`dict`: author id
* author_id: the author_id of the author
Returns:
:class:`dict`: author id
* author_id: the author_id of the author
"""
params = {
'mauthors': mauthors,

View File

@@ -56,7 +56,7 @@ class GoogleSearch(BaseAction):
@tool_api
def run(self, query: str, k: int = 10) -> ActionReturn:
"""一个可以从谷歌搜索结果的API。当你需要对于一个特定问题找到简短明了的回答时可以使用它。输入应该是一个搜索查询。
Args:
query (str): the search content
k (int): select first k results in the search results as response

View File

@@ -15,14 +15,14 @@ from .parser import BaseParser, JsonParser
class Status(str, Enum):
"""Execution status"""
"""Execution status."""
SUCCESS = 'success'
FAILURE = 'failure'
@dataclass
class ExecutionResult:
"""Execution result"""
"""Execution result."""
status: Status
value: Optional[str] = None
msg: Optional[str] = None
@@ -37,7 +37,7 @@ class IPythonInteractive(BaseAction):
max_out_len (int): maximum output length. No truncation occurs if negative.
Defaults to ``2048``.
use_signals (bool): whether signals should be used for timing function out
or the multiprocessing. Set to ``False`` when not running in the main
or the multiprocessing. Set to ``False`` when not running in the main
thread, e.g. web applications. Defaults to ``True``
description (dict): The description of the action. Defaults to ``None``.
parser (Type[BaseParser]): The parser class to process the
@@ -62,7 +62,7 @@ class IPythonInteractive(BaseAction):
self._use_signals = use_signals
def reset(self):
"""Clear the context"""
"""Clear the context."""
self._executor.reset()
@tool_api
@@ -71,7 +71,7 @@ class IPythonInteractive(BaseAction):
Args:
command (:class:`str`): Python code snippet
timeout (:class:`Optional[int]`): timeout for execution. This
timeout (:class:`Optional[int]`): timeout for execution. This
argument only works in the main thread. Defaults to ``None``.
"""
tool_return = ActionReturn(args={'text': command}, type=self.name)
@@ -87,7 +87,7 @@ class IPythonInteractive(BaseAction):
return tool_return
def exec(self, code: str) -> ExecutionResult:
"""Run Python scripts in IPython shell
"""Run Python scripts in IPython shell.
Args:
code (:class:`str`): code block
@@ -110,9 +110,8 @@ class IPythonInteractive(BaseAction):
if 'TimeoutError' in out:
return ExecutionResult(
Status.FAILURE,
msg=
'The code interpreter encountered an unexpected error.'
)
msg=('The code interpreter encountered '
'an unexpected error.'))
err_idx = i
break
else:
@@ -125,7 +124,7 @@ class IPythonInteractive(BaseAction):
)
async def async_exec(self, code: str) -> ExecutionResult:
"""Asynchronously run Python scripts in IPython shell
"""Asynchronously run Python scripts in IPython shell.
Args:
code (:class:`str`): code block
@@ -149,9 +148,8 @@ class IPythonInteractive(BaseAction):
if 'TimeoutError' in out:
return ExecutionResult(
Status.FAILURE,
msg=
'The code interpreter encountered an unexpected error.'
)
msg=('The code interpreter encountered an '
'unexpected error.'))
err_idx = i
break
else:
@@ -165,7 +163,7 @@ class IPythonInteractive(BaseAction):
@staticmethod
def extract_code(text: str) -> str:
"""Extract Python code from markup languages
"""Extract Python code from markup languages.
Args:
text (:class:`str`): Markdown-formatted text

View File

@@ -40,7 +40,7 @@ class IPythonInterpreter(BaseAction):
user_data_dir (str, optional): Specified the user data directory for files
loading. If set to `ENV`, use `USER_DATA_DIR` environment variable.
Defaults to `ENV`.
work_dir (str, optional): Specify which directory to save output images to.
work_dir (str, optional): Specify which directory to save output images to.
Defaults to ``'./work_dir/tmp_dir'``.
description (dict): The description of the action. Defaults to ``None``.
parser (Type[BaseParser]): The parser class to process the
@@ -207,11 +207,12 @@ class IPythonInterpreter(BaseAction):
@tool_api
def run(self, command: str, timeout: Optional[int] = None) -> ActionReturn:
"""When you send a message containing Python code to python, it will be \
executed in a stateful Jupyter notebook environment. python will respond with \
the output of the execution or time out after 60.0 seconds. The drive at '/mnt/data' \
can be used to save and persist user files. Internet access for this session is \
disabled. Do not make external web requests or API calls as they will fail.
r"""When you send a message containing Python code to python, it will be
\ executed in a stateful Jupyter notebook environment. python will
respond with \ the output of the execution or time out after 60.0
seconds. The drive at '/mnt/data' \ can be used to save and persist
user files. Internet access for this session is \ disabled. Do not make
external web requests or API calls as they will fail.
Args:
command (:class:`str`): Python code
@@ -223,15 +224,15 @@ disabled. Do not make external web requests or API calls as they will fail.
if succeed:
text = result['text']
image = result.get('image', [])
resp = [dict(type="text", content=text)]
resp = [dict(type='text', content=text)]
if image:
resp.extend([dict(type="image", content=im) for im in image])
resp.extend([dict(type='image', content=im) for im in image])
tool_return.result = resp
# tool_return.result = dict(
# text=result['text'], image=result.get('image', [])[0])
tool_return.state = ActionStatusCode.SUCCESS
else:
tool_return.errmsg = result.get("text", "") if isinstance(
tool_return.errmsg = result.get('text', '') if isinstance(
result, dict) else result
tool_return.state = ActionStatusCode.API_ERROR
return tool_return

View File

@@ -5,7 +5,7 @@ from typing import Any, List, Union
class ParseError(Exception):
"""Parsing exception class"""
"""Parsing exception class."""
def __init__(self, err_msg: str):
self.err_msg = err_msg
@@ -47,11 +47,11 @@ class BaseParser:
self._api2required[api_name] = api['required']
def parse_inputs(self, inputs: str, name: str = 'run') -> dict:
"""parse inputs LLMs generate for the action
"""Parse inputs LLMs generate for the action.
Args:
inputs (:class:`str`): input string extracted from responses
Returns:
:class:`dict`: processed input
"""
@@ -59,13 +59,13 @@ class BaseParser:
return inputs
def parse_outputs(self, outputs: Any) -> List[dict]:
"""parser outputs returned by the action
"""Parser outputs returned by the action.
Args:
outputs (:class:`Any`): raw output of the action
Returns:
:class:`List[dict]`: processed output of which each member is a
:class:`List[dict]`: processed output of which each member is a
dictionary with two keys - 'type' and 'content'.
"""
if isinstance(outputs, dict):

View File

@@ -16,7 +16,8 @@ THEME_MAPPING = {
class PPT(BaseAction):
"""Plugin to create ppt slides with text, paragraph, images in good looking styles"""
"""Plugin to create ppt slides with text, paragraph, images in good looking
styles."""
def __init__(self,
theme_mapping: Optional[Dict[str, dict]] = None,
@@ -30,7 +31,7 @@ class PPT(BaseAction):
@tool_api(explode_return=True)
def create_file(self, theme: str, abs_location: str) -> dict:
"""Create a pptx file with specific themes
"""Create a pptx file with specific themes.
Args:
theme (:class:`str`): the theme used
@@ -74,7 +75,7 @@ class PPT(BaseAction):
@tool_api(explode_return=True)
def add_text_page(self, title: str, bullet_items: str) -> dict:
"""Add text page of ppt
"""Add text page of ppt.
Args:
title (:class:`str`): the title of the page
@@ -105,7 +106,7 @@ class PPT(BaseAction):
@tool_api(explode_return=True)
def add_text_image_page(self, title: str, bullet_items: str,
image: str) -> dict:
"""Add a text page with one image. Image should be a path
"""Add a text page with one image. Image should be a path.
Args:
title (:class:`str`): the title of the page

View File

@@ -65,20 +65,11 @@ class PythonInterpreter(BaseAction):
@tool_api
def run(self, command: str) -> ActionReturn:
"""用来执行Python代码。代码必须是一个函数函数名必须得是 'solution',代码对应你的思考过程。代码实例格式如下:
```python
# import 依赖包
import xxx
def solution():
# 初始化一些变量
variable_names_with_real_meaning = xxx
# 步骤一
mid_variable = func(variable_names_with_real_meaning)
# 步骤 x
mid_variable = func(mid_variable)
# 最后结果
final_answer = func(mid_variable)
return final_answer
```
```python # import 依赖包 import xxx def solution(): # 初始化一些变量
variable_names_with_real_meaning = xxx # 步骤一 mid_variable =
func(variable_names_with_real_meaning) # 步骤 x mid_variable =
func(mid_variable) # 最后结果 final_answer = func(mid_variable) return
final_answer ```
Args:
command (:class:`str`): Python code snippet

View File

@@ -220,7 +220,7 @@ class AutoGPTProtocol:
return formatted_data
def format_response(self, action_return) -> dict:
"""format the final response at current step.
"""Format the final response at current step.
Args:
action_return (ActionReturn): return value of the current action.

View File

@@ -170,7 +170,7 @@ class ReActProtocol:
return thought, action.strip(), action_input.strip().strip('"')
def format_response(self, action_return: ActionReturn) -> dict:
"""format the final response at current step.
"""Format the final response at current step.
Args:
action_return (ActionReturn): return value of the current action.

View File

@@ -130,8 +130,7 @@ class TritonClient(BaseModel):
tuple(Status, str, int): status, text/chat completion,
generated token number
"""
from lmdeploy.serve.turbomind.chatbot import (Session, StatusCode,
get_logger)
from lmdeploy.serve.turbomind.chatbot import Session, StatusCode, get_logger
assert isinstance(session_id, int), \
f'INT session id is required, but got {type(session_id)}'

View File

@@ -1,7 +1,8 @@
from typing import List, Optional, Union
def filter_suffix(response: Union[str, List[str]], suffixes: Optional[List[str]] = None) -> str:
def filter_suffix(response: Union[str, List[str]],
suffixes: Optional[List[str]] = None) -> str:
"""Filter response with suffixes.
Args:

View File

@@ -1,13 +1,13 @@
astroid<3.0.0
docutils==0.18.1
markdown>=3.4.0
myst-nb
# -e git+https://github.com/open-mmlab/pytorch_sphinx_theme.git#egg=pytorch_sphinx_theme
# sphinx==4.0.2
sphinx==6.1.0
sphinx-autoapi
sphinx-rtd-theme==1.3.0
sphinx-tabs
sphinx_copybutton
sphinx_markdown_tables>=0.0.16
sphinx-rtd-theme==1.3.0
tabulate
astroid<3.0.0
sphinx-autoapi

View File

@@ -1,16 +1,16 @@
arxiv
distro
func_timeout
google-search-results
griffe
json5
jsonschema
jupyter
jupyter_client
phx-class-registry
pillow
python-pptx
requests
tiktoken
timeout_decorator
griffe
phx-class-registry
jupyter
jupyter_client
json5
pillow
typing-extensions
arxiv
google-search-results
python-pptx

View File

@@ -18,8 +18,8 @@ SPLIT_BEFORE_EXPRESSION_AFTER_OPENING_PAREN = true
[codespell]
skip = *.ipynb
quiet-level = 3
ignore-words-list = patten,nd,ty,mot,hist,formating,winn,gool,datas,wan,confids,TOOD,tood,ba,warmup,nam,DOTA,dota,conveyer
ignore-words-list = patten,nd,ty,mot,hist,formating,winn,gool,datas,wan,confids,TOOD,tood,ba,warmup,nam,DOTA,dota,conveyer,astroid
[flake8]
per-file-ignores = ftdp/configs/*: F401,F403,F405
max-line-length = 120
max-line-length = 200

View File

@@ -1,7 +1,6 @@
from unittest import TestCase
from lagent.actions.builtin_actions import (FinishAction, InvalidAction,
NoAction)
from lagent.actions.builtin_actions import FinishAction, InvalidAction, NoAction
from lagent.schema import ActionStatusCode