Composio 통합
Composio 통합
Composio의 통합 API 플랫폼을 통해 AI 에이전트용 500개 이상의 도구와 통합에 접근할 수 있습니다. OAuth 처리, 이벤트 기반 워크플로, 다중 사용자 지원을 제공합니다.
Composio는 GitHub, Slack, Notion 등 널리 쓰이는 애플리케이션 전반에서 500개 이상의 도구에 접근할 수 있게 해주는 통합 플랫폼입니다. AI 에이전트가 통합 API를 통해 외부 서비스와 상호작용하도록 하며, 인증, 권한, 이벤트 기반 워크플로를 처리합니다.
개요
통합 상세
| Class | Package | Serializable | Python 지원 | Version |
|---|---|---|---|---|
| Composio | @composio/langchain | ❌ | ✅ |
도구 기능
- 500개 이상의 도구 접근: GitHub, Slack, Gmail, Jira, Notion 등 사전 구축된 통합
- 인증 관리: OAuth 플로우, API 키, 인증 상태 처리
- 이벤트 기반 워크플로: 외부 이벤트(새 Slack 메시지, GitHub 이슈 등)에 따라 에이전트 트리거
- 세분화된 권한: 사용자별 도구 접근 및 데이터 노출 제어
- 커스텀 도구 지원: 독점 API와 내부 도구 추가
설정
이 통합은 @composio/langchain 패키지에 포함되어 있습니다.
npm install @composio/langchain @composio/core
다른 패키지 매니저를 사용하는 경우:
yarn add @composio/langchain @composio/core
# or
pnpm add @composio/langchain @composio/core
자격 증명
Composio API 키가 필요합니다. composio.dev에서 무료로 가입하여 API 키를 받으세요.
import * as dotenv from 'dotenv';
dotenv.config();
// Set your Composio API key
process.env.COMPOSIO_API_KEY = 'your_api_key_here';
추적(tracing)을 위해 LangSmith를 설정하는 것도 도움이 됩니다:
// process.env.LANGSMITH_API_KEY = 'your_langsmith_key';
// process.env.LANGSMITH_TRACING = 'true';
인스턴스화
LangChain 프로바이더로 Composio를 초기화하고 특정 툴킷에서 도구를 가져옵니다. 각 툴킷은 하나의 서비스(예: GitHub, Slack)를 나타내며, 여러 도구(수행할 수 있는 작업)를 포함합니다.
import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
// Initialize Composio with LangChain provider
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
provider: new LangchainProvider(),
});
// Get tools from specific toolkits
const tools = await composio.tools.get('default', 'GITHUB');
console.log(`Loaded ${tools.length} tools from GitHub toolkit`);
사용 가능한 툴킷
Composio는 다양한 서비스용 툴킷을 제공합니다:
생산성(Productivity): GitHub, Slack, Gmail, Jira, Notion, Asana, Trello, ClickUp 커뮤니케이션(Communication): Discord, Telegram, WhatsApp, Microsoft Teams 개발(Development): GitLab, Bitbucket, Linear, Sentry 데이터 및 분석(Data & Analytics): Google Sheets, Airtable, HubSpot, Salesforce 그 외 100개 이상...
호출
여러 툴킷에서 도구 가져오기
여러 서비스에서 도구를 로드할 수 있습니다:
// Get tools from multiple toolkits
const tools = await composio.tools.get('default', ['GITHUB', 'SLACK', 'GMAIL']);
특정 도구 가져오기
전체 툴킷 대신 특정 도구를 로드할 수 있습니다:
// Get specific tools by name
const tools = await composio.tools.get('default', {
tools: ['GITHUB_CREATE_ISSUE', 'SLACK_SEND_MESSAGE']
});
사용자별 도구
Composio는 사용자별 인증을 통한 다중 사용자 시나리오를 지원합니다:
// Get tools for a specific user
// This user must have authenticated their accounts first
const tools = await composio.tools.get('user_123', 'GITHUB');
에이전트 내에서 사용
다음은 LangGraph 에이전트와 함께 Composio 도구를 사용해 HackerNews와 상호작용하는 완전한 예제입니다:
import { ChatOpenAI } from '@langchain/openai';
import { HumanMessage, AIMessage } from '@langchain/core/messages';
import { ToolNode } from '@langchain/langgraph/prebuilt';
import { StateGraph, MessagesAnnotation } from '@langchain/langgraph';
import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
// Initialize Composio
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
provider: new LangchainProvider(),
});
// Fetch the tools
console.log('🔄 Fetching the tools...');
const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
// Define the tools for the agent to use
const toolNode = new ToolNode(tools);
// Create a model and give it access to the tools
const model = new ChatOpenAI({
model: 'gpt-5',
}).bindTools(tools);
// Define the function that determines whether to continue or not
function shouldContinue({ messages }: typeof MessagesAnnotation.State) {
const lastMessage = messages[messages.length - 1] as AIMessage;
// If the LLM makes a tool call, then we route to the "tools" node
if (lastMessage.tool_calls?.length) {
return 'tools';
}
// Otherwise, we stop (reply to the user)
return '__end__';
}
// Define the function that calls the model
async function callModel(state: typeof MessagesAnnotation.State) {
console.log('🔄 Calling the model...');
const response = await model.invoke(state.messages);
return { messages: [response] };
}
// Define a new graph
const workflow = new StateGraph(MessagesAnnotation)
.addNode('agent', callModel)
.addEdge('__start__', 'agent')
.addNode('tools', toolNode)
.addEdge('tools', 'agent')
.addConditionalEdges('agent', shouldContinue);
// Compile the graph
const app = workflow.compile();
// Use the agent
const finalState = await app.invoke({
messages: [new HumanMessage('Find the details of the user `pg` on HackerNews')]
});
console.log('✅ Message received from the model');
console.log(finalState.messages[finalState.messages.length - 1].content);
// Continue the conversation
const nextState = await app.invoke({
messages: [...finalState.messages, new HumanMessage('what about haxzie')]
});
console.log('✅ Message received from the model');
console.log(nextState.messages[nextState.messages.length - 1].content);
GitHub 툴킷 사용하기
GitHub 저장소에 스타(star)를 다는 예제입니다:
import { ChatOpenAI } from '@langchain/openai';
import { createReactAgent } from '@langchain/langgraph/prebuilt';
import { Composio } from '@composio/core';
import { LangchainProvider } from '@composio/langchain';
// Initialize Composio
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY,
provider: new LangchainProvider(),
});
// Get GitHub tools
const tools = await composio.tools.get('default', 'GITHUB');
// Create model
const model = new ChatOpenAI({
model: 'gpt-5',
});
// Create agent
const agent = createReactAgent({
llm: model,
tools: tools,
});
// Execute task
const result = await agent.invoke({
messages: [
{
role: 'user',
content: 'Star the repository composiohq/composio on GitHub'
}
]
});
console.log(result.messages[result.messages.length - 1].content);
인증 설정
인증이 필요한 도구를 사용하기 전에 사용자는 계정을 연결해야 합니다:
import { Composio } from '@composio/core';
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY
});
// Get authentication URL for a user
const authConnection = await composio.integrations.create({
userId: 'user_123',
integration: 'github'
});
console.log(`Authenticate at: ${authConnection.redirectUrl}`);
// After authentication, the user's connected account will be available
// and tools will work with their credentials
다중 사용자 시나리오
여러 사용자가 있는 애플리케이션의 경우:
// Each user authenticates their own accounts
const toolsUser1 = await composio.tools.get('user_1', 'GITHUB');
const toolsUser2 = await composio.tools.get('user_2', 'GITHUB');
// Tools will use the respective user's credentials
// User 1's agent will act on User 1's GitHub account
const agent1 = createAgent({ model, tools: toolsUser1 });
// User 2's agent will act on User 2's GitHub account
const agent2 = createAgent({ model, tools: toolsUser2 });
이벤트 기반 워크플로
Composio는 외부 이벤트에 기반해 에이전트를 트리거하는 것을 지원합니다. 연결된 앱(예: 새 GitHub 커밋, Slack 메시지)에서 이벤트가 발생하면 트리거가 자동으로 구조화된 페이로드를 애플리케이션에 전송합니다.
트리거 만들기
먼저 모니터링하려는 이벤트에 대한 트리거를 만듭니다:
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
const userId = 'user_123';
// Check what configuration is required for the trigger
const triggerType = await composio.triggers.getType('GITHUB_COMMIT_EVENT');
console.log(triggerType.config);
// Create trigger with required configuration
const trigger = await composio.triggers.create(
userId,
'GITHUB_COMMIT_EVENT',
{
triggerConfig: {
owner: 'composiohq',
repo: 'composio'
}
}
);
console.log(`Trigger created: ${trigger.triggerId}`);
트리거 구독하기 (개발 환경)
로컬 개발과 프로토타이핑을 위해 트리거에 직접 구독할 수 있습니다:
import { Composio } from '@composio/core';
const composio = new Composio({ apiKey: process.env.COMPOSIO_API_KEY });
// Subscribe to trigger events
composio.triggers.subscribe(
(data) => {
console.log(`New commit detected:`, data);
// Process the event with your agent
// ... invoke your agent with the task
},
{
triggerId: 'your_trigger_id',
// You can also filter by:
// userId: '[email protected]',
// toolkits: ['github', 'slack'],
// triggerSlug: ["GITHUB_COMMIT_EVENT"],
// authConfigId: "ac_1234567890"
}
);
// Note: For production, use webhooks instead
타입 안전한 트리거 처리
더 나은 타입 안전성을 위해 페이로드 타입을 정의하세요:
import { TriggerEvent } from '@composio/core';
// Define type-safe payload
export type GitHubStarAddedEventPayload = {
action: 'created';
repository_id: number;
repository_name: string;
repository_url: string;
starred_at: string;
starred_by: string;
};
// Type-safe handler
function handleGitHubStarAddedEvent(event: TriggerEvent<GitHubStarAddedEventPayload>) {
console.log(`⭐ ${event.data.repository_name} starred by ${event.data.starred_by}`);
}
웹훅 (프로덕션)
프로덕션에서는 Composio 대시보드에서 웹훅을 구성하세요:
import type { NextApiRequest, NextApiResponse } from 'next';
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== 'POST') {
return res.status(405).json({ error: 'Method not allowed' });
}
try {
const payload = req.body;
console.log('Received trigger event:', payload);
// Process the event with your agent
if (payload.triggerSlug === 'GITHUB_COMMIT_EVENT') {
const commitData = payload.payload;
// ... invoke your agent with commitData
}
res.status(200).json({ status: 'success' });
} catch (error) {
console.error('Error processing webhook:', error);
res.status(500).json({ error: 'Internal server error' });
}
}
자세한 내용은 Composio Triggers 문서를 참조하세요.
고급 기능
커스텀 도구
Composio는 내장 도구와 함께 사용할 수 있는 커스텀 도구를 만들 수 있게 해줍니다. 두 가지 유형이 있습니다:
독립형 도구 (Standalone tools)
인증이 필요 없는 간단한 도구:
import { Composio } from '@composio/core';
import { z } from 'zod';
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY
});
const tool = await composio.tools.createCustomTool({
slug: 'CALCULATE_SQUARE',
name: 'Calculate Square',
description: 'Calculates the square of a number',
inputParams: z.object({
number: z.number().describe('The number to calculate the square of'),
}),
execute: async input => {
const { number } = input;
return {
data: { result: number * number },
error: null,
successful: true,
};
},
});
// Use with your agent
const allTools = [...tools, tool];
툴킷 기반 도구
인증이 필요하고 툴킷 자격 증명을 사용할 수 있는 도구:
import { Composio } from '@composio/core';
import { z } from 'zod';
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY
});
const tool = await composio.tools.createCustomTool({
slug: 'GITHUB_STAR_COMPOSIOHQ_REPOSITORY',
name: 'Github star composio repositories',
toolkitSlug: 'github',
description: 'Star any specified repo of `composiohq` user',
inputParams: z.object({
repository: z.string().describe('The repository to star'),
page: z.number().optional().describe('Pagination page number'),
customHeader: z.string().optional().describe('Custom header'),
}),
execute: async (input, connectionConfig, executeToolRequest) => {
// This method makes authenticated requests to the relevant API
// Composio will automatically inject the baseURL
const result = await executeToolRequest({
endpoint: `/user/starred/composiohq/${input.repository}`,
method: 'PUT',
body: {},
// Add custom headers or query parameters
parameters: [
// Add query parameters
{
name: 'page',
value: input.page?.toString() || '1',
in: 'query',
},
// Add custom headers
{
name: 'x-custom-header',
value: input.customHeader || 'default-value',
in: 'header',
},
],
});
return result;
},
});
커스텀 도구 실행:
import { Composio } from '@composio/core';
const composio = new Composio({
apiKey: process.env.COMPOSIO_API_KEY
});
const result = await composio.tools.execute('TOOL_SLUG', {
arguments: {
// Tool input parameters
},
userId: 'user-id',
connectedAccountId: 'optional-account-id', // Required for toolkit-based tools
});
자세한 내용은 Composio Custom Tools 문서를 참조하세요.
세분화된 권한
도구가 수행할 수 있는 작업을 제어하세요:
// Get tools with specific permissions
const tools = await composio.tools.get('default', 'GITHUB', {
// Limit to read-only operations
permissions: ['read']
});
API 참고 자료
모든 Composio 기능과 구성에 대한 자세한 문서는 다음을 참조하세요:
출처: 문서