Skip to content

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

docs: python snippets 2 (#1634)

Virajebeee43e4ba5
diff --git a/fern/pages/authentication/custom-auth-configs.mdx b/fern/pages/authentication/custom-auth-configs.mdx
index 6cc0e10dd..9aa6aa136 100644
--- a/fern/pages/authentication/custom-auth-configs.mdx
+++ b/fern/pages/authentication/custom-auth-configs.mdx
@@ -143,7 +143,7 @@ https://yourdomain.com/api/composio-redirect
</Step>
<Step title="Create a redirect logic">
-Create a redirect logic, either through your DNS or in your application to redirect that endpoint to `https://backend.composio.dev/api/v1/auth-apps/add`
+Create a redirect logic, either through your DNS or in your application to redirect that endpoint to `https://backend.composio.dev/api/v3/toolkits/callback`
**Example: API Route for OAuth Redirect**
@@ -153,7 +153,7 @@ import type { NextApiRequest, NextApiResponse } from 'next';
export default function handler(req: NextApiRequest, res: NextApiResponse) {
// The target Composio endpoint that handles OAuth callbacks
- const composioEndpoint = 'https://backend.composio.dev/api/v1/auth-apps/add';
+ const composioEndpoint = 'https://backend.composio.dev/api/v3/toolkits/callback';
// Extract and preserve all query parameters
const queryParams = new URLSearchParams();
diff --git a/fern/pages/authentication/programmatic-auth-configs.mdx b/fern/pages/authentication/programmatic-auth-configs.mdx
index f33911b73..f29a22015 100644
--- a/fern/pages/authentication/programmatic-auth-configs.mdx
+++ b/fern/pages/authentication/programmatic-auth-configs.mdx
@@ -52,7 +52,7 @@ You can also provide your own authentication details. The required `credentials`
## Using Custom Auth
### Create the auth config
-If you know the required authentication fields for your toolkit, you can directly create the auth config. OAuth2 is the most common auth type for apps. When using your own OAuth developer app, you must ensure to set the **authorized redirect URI** in the OAuth configuration to `https://backend.composio.dev/api/v1/auth-apps/add`.
+If you know the required authentication fields for your toolkit, you can directly create the auth config. OAuth2 is the most common auth type for apps. When using your own OAuth developer app, you must ensure to set the **authorized redirect URI** in the OAuth configuration to `https://backend.composio.dev/api/v3/toolkits/callback`.
This is the URI that captures the OAuth code that is returned to the app.
@@ -66,7 +66,7 @@ const authConfig = await composio.authConfigs.create("NOTION", {
credentials: {
client_id: "1234567890",
client_secret: "1234567890",
- oauth_redirect_uri: "https://backend.composio.dev/api/v1/auth-apps/add",
+ oauth_redirect_uri: "https://backend.composio.dev/api/v3/toolkits/callback",
},
authScheme: "OAUTH2",
});
@@ -84,7 +84,7 @@ auth_config = composio.auth_configs.create(
"credentials": {
"client_id": "1234567890",
"client_secret": "1234567890",
- "oauth_redirect_uri": "https://backend.composio.dev/api/v1/auth-apps/add",
+ "oauth_redirect_uri": "https://backend.composio.dev/api/v3/toolkits/callback",
},
},
)
@@ -111,8 +111,12 @@ const authFields = toolkits.authConfigDetails?.flatMap(
console.log("Required auth config fields:", authFields);
```
-{/* TODO: implement method which returns required fields for a toolkit with given auth scheme */}
```python Python maxLines=60 wordWrap
+required_fields = composio.auth_configs.get_required_fields(
+ toolkit="NOTION",
+ auth_scheme="OAUTH2",
+)
+print(required_fields)
```
</CodeGroup>
@@ -156,8 +160,33 @@ const authConfig = await composio.authConfigs.create("NOTION", {
),
});
```
- {/* TODO: add once the above todo is addressed */}
```python Python maxLines=60 wordWrap
+import os
+
+from composio import Composio
+
+composio = Composio()
+
+# Get required fields
+required_fields = [
+ field.name for field in composio.auth_configs.get_required_fields(
+ toolkit="NOTION",
+ auth_scheme="OAUTH2",
+ )
+]
+
+# Read required fields as environment variables
+auth_config = composio.auth_configs.create(
+ toolkit="notion",
+ options={
+ "name": "Notion Auth",
+ "type": "use_custom_auth",
+ "auth_scheme": "OAUTH2",
+ "credentials": {
+ field: os.getenv(f"NOTION_{field.upper()}") for field in required_fields
+ },
+ },
+)
```
</CodeGroup>
</Accordion>
\ No newline at end of file
diff --git a/fern/pages/tool-calling/authenticating-tools.mdx b/fern/pages/tool-calling/authenticating-tools.mdx
index ad98bf7cb..28cf6e4c9 100644
--- a/fern/pages/tool-calling/authenticating-tools.mdx
+++ b/fern/pages/tool-calling/authenticating-tools.mdx
@@ -177,10 +177,14 @@ detail => detail.fields.connectedAccountInitiation
);
console.log(fieldNames); // e.g. ["apiKey"]
-````
+```
```python Python maxLines=60 wordWrap
-
+required_fields = composio.connected_accounts.get_required_fields(
+ toolkit="NOTION",
+ auth_scheme="API_KEY",
+)
+print(required_fields)
````
</CodeGroup>
@@ -266,9 +270,33 @@ data: authData,
console.log("Connection request ID:", connectionRequest.id);
-````
+```
```python Python maxLines=60 wordWrap
+import os
+from composio import Composio
+
+composio = Composio()
+# Get required fields
+required_fields = [
+ field.name for field in composio.connected_accounts.get_required_fields(
+ toolkit="NOTION",
+ auth_scheme="API_KEY",
+ )
+]
+print("required_fields: ", required_fields)
+
+# Create a new connected account (API Key)
+connection_request = composio.connected_accounts.initiate(
+ user_id="1234567890",
+ auth_config_id="1234567890",
+ config=auth_scheme.api_key(
+ options={
+ field: os.getenv(f"NOTION_{field.upper()}") for field in required_fields
+ },
+ ),
+)
+print(connection_request)
````
</CodeGroup>
diff --git a/fern/pages/tool-calling/custom-tools.mdx b/fern/pages/tool-calling/custom-tools.mdx
index 95bfa61ce..f6b9508b8 100644
--- a/fern/pages/tool-calling/custom-tools.mdx
+++ b/fern/pages/tool-calling/custom-tools.mdx
@@ -37,8 +37,30 @@ const tool = await composio.tools.createCustomTool({
});
```
```python Python maxLines=60 wordWrap
+from pydantic import BaseModel, Field
-````
+from composio import Composio
+from composio.types import ExecuteRequestFn
+
+composio = Composio()
+
+
+class AddTwoNumbersInput(BaseModel):
+ a: int = Field(
+ ...,
+ description="The first number to add",
+ )
+ b: int = Field(
+ ...,
+ description="The second number to add",
+ )
+
+# function name will be used as slug
+def add_two_numbers(request: AddTwoNumbersInput) -> int:
+ """Add two numbers."""
+ return request.a + request.b
+```
</CodeGroup>
### Toolkit-based Tool
@@ -86,10 +108,40 @@ const tool = await composio.tools.createCustomTool({
return result;
},
});
-````
+```
```python Python maxLines=60 wordWrap
+class GetIssueInfoInput(BaseModel):
+ issue_number: int = Field(
+ ...,
+ description="The number of the issue to get information about",
+ )
+# function name will be used as slug
[email protected]_tool(toolkit="github")
+def get_issue_info(
+ request: GetIssueInfoInput,
+ execute_request: ExecuteRequestFn,
+ auth_credentials: dict,
+) -> dict:
+ """Get information about a GitHub issue."""
+ response = execute_request(
+ endpoint=f"/repos/composiohq/composio/issues/{request.issue_number}",
+ method="GET",
+ parameters=[
+ {
+ "name": "Accept",
+ "value": "application/vnd.github.v3+json",
+ "type": "header",
+ },
+ {
+ "name": "Authorization",
+ "value": f"Bearer {auth_credentials['access_token']}",
+ "type": "header",
+ },
+ ],
+ )
+ return {"data": response.data}
```
</CodeGroup>
@@ -123,9 +175,26 @@ const tool = await composio.tools.createCustomTool({
},
});
-````
+```
```python Python maxLines=60 wordWrap
-````
+import requests
+
[email protected]_tool(toolkit="github")
+def get_issue_info_direct(
+ request: GetIssueInfoInput,
+ execute_request: ExecuteRequestFn,
+ auth_credentials: dict,
+) -> dict:
+ """Get information about a GitHub issue."""
+ response = requests.get(
+ f"https://api.github.com/repos/composiohq/composio/issues/{request.issue_number}",
+ headers={
+ "Accept": "application/vnd.github.v3+json",
+ "Authorization": f"Bearer {auth_credentials['access_token']}",
+ },
+ )
+ return {"data": response.json()}
+```
</CodeGroup>
@@ -179,6 +248,35 @@ const tool = await composio.tools.createCustomTool({
});
```
```python Python maxLines=60 wordWrap
[email protected]_tool(toolkit="github")
+def get_issue_info(
+ request: GetIssueInfoInput,
+ execute_request: ExecuteRequestFn,
+ auth_credentials: dict,
+) -> dict:
+ """Get information about a GitHub issue."""
+ response = execute_request(
+ endpoint=f"/repos/composiohq/composio/issues/{request.issue_number}",
+ method="GET",
+ parameters=[
+ {
+ "name": "Accept",
+ "value": "application/vnd.github.v3+json",
+ "type": "header",
+ },
+ {
+ "name": "Authorization",
+ "value": f"Bearer {auth_credentials['access_token']}",
+ "type": "header",
+ },
+ {
+ "name": 'X-Custom-Header',
+ "value": 'custom-value',
+ "type": 'header',
+ },
+ ],
+ )
+ return {"data": response.data}
```
</CodeGroup>
@@ -197,6 +295,11 @@ const result = await composio.tools.execute('TOOL_SLUG', {
});
```
```python Python maxLines=60 wordWrap
+response = composio.tools.execute(
+ user_id="default",
+ slug="TOOL_SLUG", # For the tool above you can use `get_issue_info.slug`
+ arguments={"issue_number": 1},
+)
```
</CodeGroup>
diff --git a/fern/pages/tool-calling/executing-tools.mdx b/fern/pages/tool-calling/executing-tools.mdx
index ff1834693..2d0cfb23c 100644
--- a/fern/pages/tool-calling/executing-tools.mdx
+++ b/fern/pages/tool-calling/executing-tools.mdx
@@ -49,7 +49,32 @@ console.log(result);
```
```python Python (Google) maxLines=60
+import anthropic
+from composio import Composio
+from composio_anthropic import AnthropicProvider
+
+
+# Initialize tools.
+anthropic_client = anthropic.Anthropic()
+composio = Composio(provider=AnthropicProvider())
+
+# Get GitHub tools that are pre-configured
+tools = composio.tools.get(user_id="default", toolkits=["GITHUB_GET_THE_ZEN_OF_GITHUB"])
+
+# Get response from the LLM
+response = anthropic_client.messages.create(
+ model="claude-3-opus-20240229",
+ max_tokens=1024,
+ tools=tools,
+ messages=[
+ {"role": "user", "content": "gimme me some zen"},
+ ],
+)
+
+# Execute the function calls.
+result = composio.provider.handle_tool_calls(user_id="default", response=response)
+print(result)
```
</CodeGroup>
@@ -191,7 +216,18 @@ const { data } = await composio.tools.proxyExecute({
console.log(data);
```
```python Python maxLines=60 wordWrap
-
+response = composio.tools.proxy(
+ endpoint="/repos/composiohq/composio/issues/1",
+ method="GET",
+ connected_account_id="ac_1234", # use connected account for github
+ parameters=[
+ {
+ "name": "Accept",
+ "value": "application/vnd.github.v3+json",
+ "type": "header",
+ },
+ ],
+)
```
</CodeGroup>
diff --git a/fern/pages/triggers/using-triggers.mdx b/fern/pages/triggers/using-triggers.mdx
index a40d5fcb9..201ee23f3 100644
--- a/fern/pages/triggers/using-triggers.mdx
+++ b/fern/pages/triggers/using-triggers.mdx
@@ -52,7 +52,15 @@ const createResponse = await composio.triggers.create("GITHUB_STAR_ADDED_EVENT",
});
```
```python Python
-
+instance = composio.triggers.create(
+ slug="GITHUB_COMMIT_EVENT",
+ connected_account_id="ca_abc1234",
+ trigger_config={
+ "repo": "composio",
+ "owner": "composiohq",
+ },
+)
+print(instance)
```
</CodeGroup>
@@ -75,7 +83,25 @@ const createResponse = await composio.triggers.create("GITHUB_STAR_ADDED_EVENT",
});
```
```python Python
-
+# Fetch connected account for user
+user_id = "[email protected]"
+connected_accounts = composio.connected_accounts.list(user_ids=[user_id], limit=1).items
+if len(connected_accounts) == 0:
+ raise ValueError("No connected account found")
+
+# Get the first connected account
+connected_account = connected_accounts[0]
+
+# Create a trigger instance
+instance = composio.triggers.create(
+ slug="GITHUB_COMMIT_EVENT",
+ connected_account_id=connected_account.id,
+ trigger_config={
+ "repo": "composio",
+ "owner": "composiohq",
+ },
+)
+print(instance)
```
</CodeGroup>
@@ -100,7 +126,13 @@ await composio.triggers.subscribe(
)
```
```python Python
+# Subscribe to a trigger
+subscription = composio.triggers.subscribe()
+# Define a handler
[email protected](toolkit="GITHUB", user_id=user_id)
+def handle_github_event(data):
+ print(data)
```
</CodeGroup>
@@ -114,7 +146,9 @@ const triggerType = await composio.triggers.getType("GITHUB_STAR_ADDED_EVENT");
console.log(triggerType.payload);
```
```python Python
-
+# Get a trigger by id
+trigger = composio.triggers.get_type(slug="GITHUB_COMMIT_EVENT")
+print(trigger.payload)
```
</CodeGroup>
@@ -131,18 +165,12 @@ The dashboard will show you the trigger configuration to fill in.
```typescript TypeScript
const triggerType = await composio.triggers.getType("GITHUB_STAR_ADDED_EVENT");
-console.log(triggerType.config.properties);
-
-await composio.triggers.create("GITHUB_STAR_ADDED_EVENT", {
- connectedAccountId: "ca_1DirCHFzH7v4",
- triggerConfig: {
- owner: "composiohq",
- repo: "composio",
- },
-});
+console.log(triggerType.config);
```
```python Python
-
+# Get a trigger by id
+trigger = composio.triggers.get_type(slug="GITHUB_COMMIT_EVENT")
+print(trigger.config)
```
</CodeGroup>
@@ -158,6 +186,14 @@ await composio.triggers.create("GITHUB_PULL_REQUEST_EVENT", {
});
```
```python Python
+instance = composio.triggers.create(
+ slug="GITHUB_PULL_REQUEST_EVENT",
+ connected_account_id="ca_abc1234",
+ trigger_config={
+ "repo": "composio",
+ "owner": "composiohq",
+ },
+)
```
</CodeGroup>
@@ -170,7 +206,9 @@ In cases where the trigger isn't required for the system, it can be disabled.
await composio.triggers.disable("ti_So9EQf8XnAcy");
```
```python Python
-
+# Disable a trigger instance
+disabled_instance = composio.triggers.disable(trigger_id="ti_So9EQf8XnAcy")
+print(disabled_instance)
```
</CodeGroup>
@@ -181,7 +219,8 @@ If needed, the trigger can be enabled again.
await composio.triggers.enable("ti_So9EQf8XnAcy");
```
```python Python
-
+# Enable a trigger instance
+enabled_instance = composio.triggers.enable(trigger_id="ti_So9EQf8XnAcy")
+print(enabled_instance)
```
</CodeGroup>
-