Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.

next
py 122 lines 3.92 KB
Raw
1 """Run a read-only tool (or --multi batch), asking for approval in the terminal."""
2
3 import argparse
4 import os
5 import uuid
6 from collections.abc import Callable
7 from typing import TypeVar
8
9 from composio import Composio
10 from composio.core.models.tool_router_session import (
11 ToolRouterInputResponse,
12 ToolRouterSession,
13 )
14 from composio.exceptions import ToolInputRequest, ToolInputRequiredError
15 from jsonschema import validate
16
17 TOOL = "HACKERNEWS_GET_USER"
18 APPROVAL_TOOLS = [TOOL, "HACKERNEWS_GET_MAX_ITEM_ID"]
19 ARGUMENTS = {"username": "pg"}
20 MULTI_ARGUMENTS = {
21 "tools": [
22 {"tool_slug": TOOL, "arguments": ARGUMENTS},
23 {"tool_slug": "HACKERNEWS_GET_MAX_ITEM_ID", "arguments": {}},
24 ],
25 "sync_response_to_workbench": False,
26 }
27 T = TypeVar("T")
28
29
30 def ask_for_approval(
31 question: ToolInputRequest, read: Callable[[str], str] = input
32 ) -> ToolRouterInputResponse:
33 """Support approval decision forms; a general UI should render the full schema."""
34 if question["mode"] != "form":
35 raise ValueError("This example supports form elicitation only")
36 schema = question["requested_schema"]
37 field = schema["properties"]["decision"]
38 choices = [choice["const"] for choice in field.get("oneOf", [])] or field.get(
39 "enum", []
40 )
41 if not choices:
42 raise ValueError("Approval form has no decision choices")
43 print(question["message"])
44 while True:
45 try:
46 answer = read(f"Decision ({'/'.join(choices)}; decline/cancel): ").strip()
47 except (EOFError, KeyboardInterrupt):
48 return {"action": "cancel"}
49 if answer == "decline":
50 return {"action": "decline"}
51 if answer == "cancel":
52 return {"action": "cancel"}
53 if answer in choices:
54 content: dict[str, object | None] = {"decision": answer}
55 validate(content, schema)
56 return {"action": "accept", "content": content}
57 print("Choose one of the displayed answers.")
58
59
60 def run_with_approvals(
61 execute: Callable[..., T],
62 ask_user: Callable[[ToolInputRequest], ToolRouterInputResponse],
63 ) -> T:
64 answers = {}
65 while True:
66 try:
67 return execute(**answers)
68 except ToolInputRequiredError as error:
69 # Ask every question before resuming, preserving IDs and opaque state.
70 responses = {
71 question_id: ask_user(question)
72 for question_id, question in error.input_requests.items()
73 }
74 answers = {
75 "input_responses": responses,
76 "request_state": error.request_state,
77 }
78
79
80 def create_composio() -> Composio:
81 api_key = os.environ.get("COMPOSIO_API_KEY")
82 if not api_key:
83 raise RuntimeError("Set COMPOSIO_API_KEY before running this example")
84 return Composio(api_key=api_key)
85
86
87 def create_approval_session(composio: Composio) -> ToolRouterSession:
88 return composio.create(
89 user_id=f"approvals-example-{uuid.uuid4()}",
90 toolkits=["hackernews"],
91 tools={
92 "hackernews": {"enable": APPROVAL_TOOLS, "require_approval": APPROVAL_TOOLS}
93 },
94 sandbox={"enable": False},
95 )
96
97
98 def main():
99 parser = argparse.ArgumentParser(description=__doc__)
100 parser.add_argument(
101 "--multi", action="store_true", help="Ask about a batch of two tools"
102 )
103 args = parser.parse_args()
104 composio = create_composio()
105 session = create_approval_session(composio)
106 try:
107
108 def execute(**answers):
109 if args.multi:
110 return session.execute_meta(
111 "COMPOSIO_MULTI_EXECUTE_TOOL", arguments=MULTI_ARGUMENTS, **answers
112 )
113 return session.execute(TOOL, arguments=ARGUMENTS, **answers)
114
115 result = run_with_approvals(execute, ask_for_approval)
116 print(result.model_dump_json(indent=2))
117 finally:
118 composio.sessions.delete(session.session_id)
119
120
121 if __name__ == "__main__":
122 main()