Skip to content

Commit

Permalink
Changes from OpenAPI spec refactor (#341)
Browse files Browse the repository at this point in the history
  • Loading branch information
angrybayblade authored Jul 31, 2024
1 parent e623db6 commit cb8b214
Show file tree
Hide file tree
Showing 44 changed files with 4,452 additions and 3,443 deletions.
2 changes: 1 addition & 1 deletion README-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ composio_tool_set = ComposioToolSet()

# 获取预配置的 GitHub 工具
actions = composio_tool_set.get_actions(
actions=[Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER]
actions=[Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER]
)

my_task = "Star a repo composiodev/composio on GitHub"
Expand Down
2 changes: 1 addition & 1 deletion README-JP.md
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ composio_tool_set = ComposioToolSet()

# 事前に設定されたGitHubツールを取得
actions = composio_tool_set.get_actions(
actions=[Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER]
actions=[Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER]
)

my_task = "GitHubでcomposiodev/composioリポジトリにスターを付ける"
Expand Down
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ composio_tool_set = ComposioToolSet()

# Get GitHub tools that are pre-configured
actions = composio_tool_set.get_actions(
actions=[Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER]
actions=[Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER]
)

my_task = "Star a repo composiodev/composio on GitHub"
Expand Down
2 changes: 1 addition & 1 deletion docs/framework/llamaindex.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ Converse with your LlamaIndex agent, and it will use the provoded tool(s) as nec
<CodeGroup>
```bash Filter Specific Action
# To restrict agents from using all the actions, filter specific actions
tools = composio_toolset.get_actions(actions=[Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER])
tools = composio_toolset.get_actions(actions=[Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER])
```
</CodeGroup>

2 changes: 1 addition & 1 deletion docs/framework/lyzr.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ These commands prepare your environment for seamless interaction between Lyzr an
prompt_persona="You are AI agent that is responsible for taking actions on Github on users behalf. You need to take action on Github using Github APIs",
)

composio_toolset = ComposioToolSet().get_lyzr_tool(Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER)
composio_toolset = ComposioToolSet().get_lyzr_tool(Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER)

task = Task(
name="Github Starring",
Expand Down
4 changes: 2 additions & 2 deletions docs/framework/openai.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ These steps prepare your environment to enable interactions between OpenAI and G
```python python
# Get GitHub tools that are pre-configured
# Retrieve actions
actions = composio_toolset.get_actions(actions=[Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER])
actions = composio_toolset.get_actions(actions=[Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER])
```
```javascript javascript
// Get GitHub tools that are pre-configured
Expand Down Expand Up @@ -159,7 +159,7 @@ These steps prepare your environment to enable interactions between OpenAI and G
<CodeGroup>
```bash Filter Specific Action
# To restrict agents from executing any actions, filter specific actions
actions = composio_toolset.get_actions(actions=[Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER])
actions = composio_toolset.get_actions(actions=[Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER])
```
</CodeGroup>

Expand Down
2 changes: 1 addition & 1 deletion docs/introduction/intro/quickstart.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -213,7 +213,7 @@ composio_toolset = ComposioToolSet(api_key="**\*\***COMPOSIO_API_KEY**\*\***")

## Step 4
# Get GitHub tools that are pre-configured
actions = composio_toolset.get_actions(actions=[Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER])
actions = composio_toolset.get_actions(actions=[Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER])


## Step 5
Expand Down
2 changes: 1 addition & 1 deletion python/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ composio_tool_set = ComposioToolSet()

# Get GitHub tools that are pre-configured
actions = composio_tool_set.get_actions(
actions=[Action.GITHUB_ACTIVITY_STAR_REPO_FOR_AUTHENTICATED_USER]
actions=[Action.GITHUB_STAR_A_REPOSITORY_FOR_THE_AUTHENTICATED_USER]
)

my_task = "Star a repo composiodev/composio on GitHub"
Expand Down
2 changes: 1 addition & 1 deletion python/composio/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,4 @@
"action",
)

__version__ = "0.3.30"
__version__ = "0.4.0"
132 changes: 104 additions & 28 deletions python/composio/cli/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,19 +161,25 @@ def _update_apps(apps: t.List[AppModel]) -> None:

def _update_actions(apps: t.List[AppModel], actions: t.List[ActionModel]) -> None:
"""Get Action enum."""
enums.base.ACTIONS_CACHE.mkdir(exist_ok=True)
deprecated = {}
action_names = []
enums.base.ACTIONS_CACHE.mkdir(
exist_ok=True,
)
for app in sorted(apps, key=lambda x: x.key):
for action in actions:
if action.appKey != app.key:
continue
action_names.append(
get_enum_key(
name=action.name,
)
)

if (
action.description is not None
and "<<DEPRECATED use " in action.description
):
_, newact = action.description.split("<<DEPRECATED use ", maxsplit=1)
deprecated[get_enum_key(name=action.name)] = (
action.appKey.lower() + "_" + newact.replace(">>", "")
).upper()
else:
action_names.append(get_enum_key(name=action.name))

enums.base.ActionData(
name=action.name,
app=app.key,
Expand Down Expand Up @@ -205,6 +211,7 @@ def _update_actions(apps: t.List[AppModel], actions: t.List[ActionModel]) -> Non
_update_annotations(
cls=enums.Action,
attributes=action_names,
deprecated=deprecated,
)


Expand All @@ -222,12 +229,8 @@ def _update_tags(apps: t.List[AppModel], actions: t.List[ActionModel]) -> None:
tag_names = ["DEFAULT"]
for app_name in sorted(tag_map):
for tag in sorted(tag_map[app_name]):
tag_name = get_enum_key(
name=f"{app_name}_{tag}",
)
tag_names.append(
tag_name,
)
tag_name = get_enum_key(name=f"{app_name}_{tag}")
tag_names.append(tag_name)
enums.base.TagData(
app=app_name,
value=tag,
Expand Down Expand Up @@ -269,25 +272,37 @@ def _update_triggers(
)


def _update_annotations(cls: t.Type, attributes: t.List[str]) -> None:
def _update_annotations(
cls: t.Type,
attributes: t.List[str],
deprecated: t.Optional[t.Dict[str, str]] = None,
) -> None:
"""Update annontations for `cls`"""
console = get_context().console
file = Path(inspect.getmodule(cls).__file__) # type: ignore

annotations = []
for attribute in sorted(attributes):
annotations.append(
ast.AnnAssign(
target=ast.Name(
id=attribute,
),
annotation=ast.Constant(
value=f"{cls.__name__}",
),
target=ast.Name(id=attribute),
annotation=ast.Constant(value=f"{cls.__name__}"),
simple=1,
),
)

_deprecated = []
_deprecated_names = []
deprecated = deprecated or {}
for old, new in deprecated.items():
if old.lower() == new.lower():
continue

if new.upper() not in attributes:
continue

_deprecated.append(_build_deprecated_node(old=old, new=new))
_deprecated_names.append(old.upper())

tree = ast.parse(file.read_text(encoding="utf-8"))
for node in tree.body:
if not isinstance(node, ast.ClassDef):
Expand All @@ -299,20 +314,81 @@ def _update_annotations(cls: t.Type, attributes: t.List[str]) -> None:
child.target.id # type: ignore
for child in node.body[1:]
if isinstance(child, ast.AnnAssign)
and child.target.id != "_deprecated" # type: ignore
]
if set(cls_attributes) == set(attributes):
console.print(
f"[yellow]⚠️ {cls.__name__}s does not require update[/yellow]"
)
return

node.body = (
node.body[:1]
+ annotations
+ [child for child in node.body[1:] if not isinstance(child, ast.AnnAssign)]
)
def _filter(child: ast.AST) -> bool:
if isinstance(child, ast.AnnAssign) and child.target.id == "_deprecated": # type: ignore
child.value = ast.Dict(
keys=list(map(ast.Constant, deprecated.keys())), # type: ignore
values=list(map(ast.Constant, deprecated.values())), # type: ignore
)
return True
if isinstance(child, ast.AnnAssign):
return False
if isinstance(child, ast.FunctionDef) and child.name in _deprecated_names:
return False
if "@te.deprecated" in ast.unparse(child):
return False
return True

body = [child for child in node.body[1:] if _filter(child=child)]
node.body = node.body[:1] + annotations + _deprecated + body
break

code = ast.unparse(tree)
code = code.replace(
"@classmethod",
"@classmethod # type: ignore",
)
code = code.replace(
"import typing as t",
"\n# pylint: disable=too-many-public-methods, unused-import\n\nimport typing as t"
"\nimport typing_extensions as te # noqa: F401",
)
with file.open("w", encoding="utf-8") as fp:
fp.write(ast.unparse(tree))
fp.write(code)
console.print(f"[green]✔ {cls.__name__}s updated[/green]")


def _build_deprecated_node(old: str, new: str) -> ast.FunctionDef:
"""Function definition."""
return ast.FunctionDef(
name=old.upper(),
args=ast.arguments(
posonlyargs=[],
args=[ast.arg(arg="cls")],
kwonlyargs=[],
kw_defaults=[],
defaults=[],
),
body=[
ast.Return(
value=ast.Attribute(
value=ast.Name(id="cls", ctx=ast.Load()),
attr=new.upper(),
ctx=ast.Load(),
)
)
],
decorator_list=[
ast.Name(id="classmethod", ctx=ast.Load()),
ast.Name(id="property", ctx=ast.Load()),
ast.Call(
func=ast.Attribute(
value=ast.Name(id="te", ctx=ast.Load()),
attr="deprecated",
ctx=ast.Load(),
),
args=[ast.Constant(value=f"Use {new.upper()} instead.")],
keywords=[],
),
],
returns=ast.Constant(value="Action"),
lineno=0,
)
21 changes: 11 additions & 10 deletions python/composio/client/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -926,16 +926,22 @@ def get( # type: ignore

if limit is not None:
queries["limit"] = str(limit)

response = self._raise_if_required(
response=self.client.http.get(
url=str(self.endpoint(queries=queries)),
url=str(
self.endpoint(
queries=queries,
)
)
)
)

response_json = response.json()
items = [self.model(**action) for action in response_json.get("items")]
if len(actions) > 0:
required_triggers = [t.cast(Action, action).name for action in actions]
items = [item for item in items if item.name in required_triggers]
required = [t.cast(Action, action).name for action in actions]
items = [item for item in items if item.name in required]

if len(tags) > 0:
required_tags = [tag.app if isinstance(tag, Tag) else tag for tag in tags]
Expand Down Expand Up @@ -975,14 +981,9 @@ def execute(
:return: A dictionary containing the response from the executed action.
"""
if action.is_local:
return self.client.local.execute_action(
action=action,
request_data=params,
)
return self.client.local.execute_action(action=action, request_data=params)

actions = self.get(
actions=[action],
)
actions = self.get(actions=[action])
if len(actions) == 0:
raise ComposioClientError(f"Action {action} not found")

Expand Down
Loading

0 comments on commit cb8b214

Please sign in to comment.