@devries-cameron20 / composio-1 / commits / 30ba4d293
Fork 0

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

feat(openai): add executable provider example (#3798)

This PR: - builds on top of https://github.com/ComposioHQ/composio/pull/3790 - makes the OpenAI example executable in direct-tools, Tool Router, smoke, and Cloudflare Workers modes - keeps direct and Tool Router agents in separate files so each execution model is explicit and readable - requires a successful Composio tool execution before either agent can accept a final model response - adds OpenAI to the nightly staging matrix without weakening the existing Mastra coverage - updates two stale experimental OpenAI usages so the complete example package typechecks against current SDK APIs ## Testing - `pnpm --filter openai-example run typecheck` - `pnpm --filter openai-example run lint` (0 errors; 4 pre-existing warnings) - `pnpm --filter openai-example run smoke` (staging: 5 direct tools and 6 Tool Router tools) - `pnpm --filter openai-example run cf:dry-run` - `pnpm run typecheck` - `./node_modules/.bin/eslint ts/packages --ext .ts,.tsx` - `pnpm run typecheck:examples` - `pnpm run lint:examples` - `pnpm exec turbo cf:dry-run --filter='./ts/examples/*'` - [branch nightly](https://github.com/ComposioHQ/composio/actions/runs/29079263571): OpenAI and Mastra both passed smoke, direct-tools, and Tool Router against staging ## Post-deploy validation - dispatch `ts.examples-nightly.yml` on `next` after merge and confirm both matrix legs stay green - healthy runs finish within the 20-minute job budget and log successful tool-backed responses for both agent modes - revert this PR if the OpenAI leg blocks the nightly; examples maintainers own the first post-merge run and the next 06:00 UTC schedule --- [![Compound Engineering](https://img.shields.io/badge/Built_with-Compound_Engineering-6366f1)](https://github.com/EveryInc/compound-engineering-plugin) ![Codex](https://img.shields.io/badge/GPT--5-000000)

Alberto Schiabel committed Jul 10, 2026 at 13:41 UTC 30ba4d29300a16d9bc53c5cb413133abb3a58886
15 files changed +462 -80
.github/workflows/ts.examples-nightly.yml
+8 -7
@@ -25,10 +25,11 @@ jobs:
25 examples-staging:
26 name: ${{ matrix.provider }} examples against staging
27 runs-on: ubuntu-latest
28 + timeout-minutes: 20
29 strategy:
30 fail-fast: false
31 matrix:
31 - provider: [mastra]
32 + provider: [mastra, openai]
33
34 steps:
35 - name: Checkout Code
@@ -45,13 +46,13 @@ jobs:
46 - name: Build SDK packages
47 run: pnpm run build:packages
48
48 - # On the schedule the secret must be present. Without this, a rotated/renamed/
49 - # empty COMPOSIO_API_KEY would make smoke self-skip (exit 0) and every LLM step
50 - # no-op, leaving the whole "regression net" green while testing nothing.
51 - - name: Require COMPOSIO_API_KEY on scheduled runs
52 - if: ${{ github.event_name == 'schedule' && env.COMPOSIO_API_KEY == '' }}
49 + # Both secrets must be present for scheduled and manually dispatched
50 + # validation. Otherwise smoke can self-skip and the LLM steps can no-op,
51 + # leaving the whole regression net green while testing nothing.
52 + - name: Require staging credentials
53 + if: ${{ env.COMPOSIO_API_KEY == '' || env.OPENAI_API_KEY == '' }}
54 run: |
54 - echo "::error::COMPOSIO_API_KEY is empty on a scheduled run — smoke would no-op and mask regressions."
55 + echo "::error::COMPOSIO_API_KEY and OPENAI_API_KEY are required for examples validation."
56 exit 1
57
58 # Deterministic regression net — needs only COMPOSIO_API_KEY, no LLM.
pnpm-lock.yaml
+6
@@ -885,12 +885,18 @@ importers:
885 specifier: 'catalog:'
886 version: 3.25.2(zod@4.4.3)
887 devDependencies:
888 + '@cloudflare/workers-types':
889 + specifier: 'catalog:'
890 + version: 4.20260702.1
891 '@types/bun':
892 specifier: 'catalog:'
893 version: 1.3.14
894 typescript:
895 specifier: 'catalog:'
896 version: 6.0.3
897 + wrangler:
898 + specifier: 'catalog:'
899 + version: 4.107.0(@cloudflare/workers-types@4.20260702.1)
900
901 ts/examples/session-management:
902 dependencies:
ts/examples/openai/README.md new
+47
@@ -0,0 +1,47 @@
1 +# OpenAI × Composio
2 +
3 +Runnable references for using Composio tools with OpenAI Chat Completions. The
4 +canonical examples use the unauthenticated `HACKERNEWS` toolkit, so no connected
5 +account is required.
6 +
7 +These examples double as tests: the package is typechecked and linted on every
8 +PR, and its smoke and agent entries run nightly against the staging backend.
9 +
10 +## Setup
11 +
12 +```bash
13 +pnpm install
14 +cp ts/examples/openai/.env.example ts/examples/openai/.env
15 +```
16 +
17 +Set `COMPOSIO_API_KEY` and `OPENAI_API_KEY` in `.env` before running an agent.
18 +
19 +## Canonical examples
20 +
21 +| File | What it shows | Run |
22 +| -------------------- | ---------------------------------------------------------------- | ------------------------------------------ |
23 +| `src/index.ts` | Direct tools with a bounded OpenAI function-calling loop | `pnpm --filter openai-example start` |
24 +| `src/tool-router.ts` | Tool Router tools executed through the session that created them | `pnpm --filter openai-example tool-router` |
25 +| `src/smoke.ts` | Provider and Tool Router wrapping without an OpenAI request | `pnpm --filter openai-example run smoke` |
26 +| `src/cloudflare.ts` | The Tool Router agent on the Cloudflare Workers runtime | `pnpm --filter openai-example run cf:dev` |
27 +
28 +The direct and Tool Router agents are separate modules under
29 +`src/hackernews-agent/`. Each loop is capped at ten model turns and rejects an
30 +empty final response.
31 +
32 +## Existing examples
33 +
34 +The existing Chat Completions, Responses API, OpenAI Agents SDK, and MCP
35 +experiments remain under `src/` and keep their existing package scripts.
36 +
37 +## Cloudflare Workers
38 +
39 +The Worker reads credentials from its `env` binding rather than `process.env`.
40 +Configure both secrets before deployment:
41 +
42 +```bash
43 +pnpm --filter openai-example exec wrangler secret put COMPOSIO_API_KEY
44 +pnpm --filter openai-example exec wrangler secret put OPENAI_API_KEY
45 +```
46 +
47 +CI validates the Worker bundle with `wrangler deploy --dry-run`.
ts/examples/openai/package.json
+13 -3
@@ -2,11 +2,19 @@
2 "name": "openai-example",
3 "private": true,
4 "version": "0.1.10-alpha.0",
5 - "description": "",
6 - "main": "index.js",
5 + "type": "module",
6 + "description": "Runnable OpenAI examples for Composio tools and Tool Router",
7 + "main": "src/index.ts",
8 "scripts": {
9 "clean": "git clean -xdf node_modules",
10 "start": "bun src/index.ts",
11 + "tool-router": "bun src/tool-router.ts",
12 + "smoke": "bun src/smoke.ts",
13 + "dev": "bun --watch src/index.ts",
14 + "cf:dev": "wrangler dev",
15 + "cf:dry-run": "wrangler deploy --dry-run --outdir dist-worker",
16 + "typecheck": "tsc --noEmit -p ./tsconfig.json && tsc --noEmit -p ./tsconfig.worker.json",
17 + "lint": "eslint src --ext .ts,.tsx",
18 "start:chat-completion": "bun src/chat-completions.ts",
19 "start:assistant": "bun src/assistants.ts",
20 "start:agents": "bun src/agents-api/index.ts",
@@ -29,7 +37,9 @@
37 "zod-to-json-schema": "catalog:"
38 },
39 "devDependencies": {
40 + "@cloudflare/workers-types": "catalog:",
41 "@types/bun": "catalog:",
33 - "typescript": "catalog:"
42 + "typescript": "catalog:",
43 + "wrangler": "catalog:"
44 }
45 }
ts/examples/openai/src/agents-api/experiment.tool-router.ts
+17 -15
@@ -13,9 +13,12 @@ const composio = new Composio({
13
14 const externalUserId = 'default';
15
16 -// 2. Create an tool router session
17 -const mcpSession = await composio.experimental.toolRouter.createSession(externalUserId, {
18 - toolkits: ["gmail", "github"],
16 +// 2. Create a tool router session.
17 +// HACKERNEWS is unauthenticated, so it works with the repository's shared
18 +// staging key without requiring a connected Gmail or GitHub account.
19 +const session = await composio.sessions.create(externalUserId, {
20 + toolkits: ['hackernews'],
21 + mcp: true,
22 });
23
24 // 3. Retrieve the MCP server instance for the tool router
@@ -23,10 +26,10 @@ const mcpSession = await composio.experimental.toolRouter.createSession(external
26 const tools: HostedMCPTool[] = [
27 hostedMcpTool({
28 serverLabel: 'composio tool router',
26 - serverUrl: mcpSession.url,
29 + serverUrl: session.mcp.url,
30 requireApproval: {
31 never: {
29 - toolNames: ['GMAIL_FETCH_EMAILS'],
32 + toolNames: ['HACKERNEWS_GET_USER_BY_USERNAME'],
33 },
34 },
35 }),
@@ -34,26 +37,25 @@ const tools: HostedMCPTool[] = [
37
38 // 4. Pass tools to OpenAI-specific Agent.
39 const agent = new OpenAIAgent({
37 - name: 'Gmail Assistant',
40 + name: 'HackerNews Assistant',
41 instructions: `
39 - You are a helpful Gmail assistant that fetches and summarizes emails.
40 - When fetching emails, provide a clear summary of the results including sender, subject, and date.
41 - Be concise and provide actionable information based on the email content.
42 + You are a helpful HackerNews assistant that looks up user profiles.
43 + Be concise and summarize the user's HackerNews profile clearly.
44 `,
45 model: 'gpt-4o-mini',
46 tools: tools,
47 });
48
49 // 5. Execute the OpenAI-specific agent.
48 -// Fetch and summarize recent emails
49 -console.log('\n=== Fetching and Summarizing Recent Emails ===');
50 -const emailResponse = await run(
50 +// Fetch a HackerNews user profile.
51 +console.log('\n=== Fetching HackerNews User Profile ===');
52 +const response = await run(
53 agent,
52 - 'Fetch the latest 2 emails and provide a detailed summary with sender, subject, date, and brief content overview for each email'
54 + 'Look up the HackerNews user `pg` and summarize their profile.'
55 );
54 -console.log('\n📬 Email Summary:');
56 +console.log('\n📰 HackerNews Profile:');
57
56 -const output = emailResponse.output.filter(({ type }) => type === 'message').at(0);
58 +const output = response.output.filter(({ type }) => type === 'message').at(0);
59
60 // @ts-ignore
61 console.log(output?.content[0].text);
ts/examples/openai/src/cloudflare.ts new
+22
@@ -0,0 +1,22 @@
1 +/**
2 + * OpenAI × Composio — Cloudflare Workers
3 + *
4 + * Runs the same Tool Router agent path used by the Node entrypoint with
5 + * credentials supplied through Worker bindings.
6 + */
7 +import {
8 + runToolRouterHackerNewsAgent,
9 + type ToolRouterHackerNewsAgentEnvironment,
10 +} from './hackernews-agent/tool-router';
11 +
12 +export type Env = Required<ToolRouterHackerNewsAgentEnvironment>;
13 +
14 +export default {
15 + async fetch(_request: Request, env: Env): Promise<Response> {
16 + const text = await runToolRouterHackerNewsAgent(env);
17 +
18 + return new Response(text, {
19 + headers: { 'content-type': 'text/plain; charset=utf-8' },
20 + });
21 + },
22 +};
ts/examples/openai/src/hackernews-agent/direct.ts new
+97
@@ -0,0 +1,97 @@
1 +import { Composio } from '@composio/core';
2 +import { OpenAIProvider } from '@composio/openai';
3 +import OpenAI from 'openai';
4 +
5 +const MODEL = 'gpt-5-mini';
6 +const USER_ID = 'example-user';
7 +const MAX_STEPS = 10;
8 +
9 +interface DirectHackerNewsAgentEnvironment {
10 + COMPOSIO_API_KEY?: string;
11 + OPENAI_API_KEY?: string;
12 +}
13 +
14 +function requireKey(
15 + env: DirectHackerNewsAgentEnvironment,
16 + name: keyof DirectHackerNewsAgentEnvironment
17 +): string {
18 + const value = env[name];
19 + if (!value) {
20 + throw new Error(`${name} is required to run the HackerNews agent.`);
21 + }
22 +
23 + return value;
24 +}
25 +
26 +export async function runDirectHackerNewsAgent(
27 + env: DirectHackerNewsAgentEnvironment
28 +): Promise<string> {
29 + const composioApiKey = requireKey(env, 'COMPOSIO_API_KEY');
30 + const openaiApiKey = requireKey(env, 'OPENAI_API_KEY');
31 + const openai = new OpenAI({
32 + apiKey: openaiApiKey,
33 + maxRetries: 1,
34 + timeout: 60_000,
35 + });
36 + const composio = new Composio({
37 + apiKey: composioApiKey,
38 + provider: new OpenAIProvider(),
39 + });
40 + const tools = await composio.tools.get(USER_ID, 'HACKERNEWS_GET_USER_BY_USERNAME');
41 + const messages: OpenAI.ChatCompletionMessageParam[] = [
42 + {
43 + role: 'system',
44 + content: 'You are a helpful assistant that looks up HackerNews users.',
45 + },
46 + { role: 'user', content: 'Tell me about the HackerNews user `pg`.' },
47 + ];
48 + let hasSuccessfulToolExecution = false;
49 +
50 + for (let step = 0; step < MAX_STEPS; step += 1) {
51 + let toolChoice: 'auto' | 'required' = 'auto';
52 + if (!hasSuccessfulToolExecution) {
53 + toolChoice = 'required';
54 + }
55 +
56 + const response = await openai.chat.completions.create({
57 + model: MODEL,
58 + messages,
59 + tools,
60 + tool_choice: toolChoice,
61 + });
62 + const message = response.choices[0]?.message;
63 + if (!message) {
64 + throw new Error('OpenAI returned no assistant message.');
65 + }
66 +
67 + messages.push(message);
68 + if (!message.tool_calls?.length) {
69 + if (!hasSuccessfulToolExecution) {
70 + throw new Error('Agent returned without successfully executing a Composio tool.');
71 + }
72 +
73 + const text = message.content?.trim();
74 + if (!text) {
75 + throw new Error('Agent returned empty output — expected a non-empty response.');
76 + }
77 + return text;
78 + }
79 +
80 + const toolMessages = await composio.provider.handleToolCalls(USER_ID, response, undefined, {
81 + beforeExecute: ({ toolSlug, params }) => {
82 + console.log(`🔧 executing ${toolSlug} with ${JSON.stringify(params.arguments)}`);
83 + return params;
84 + },
85 + afterExecute: ({ toolSlug, result }) => {
86 + if (result.successful) {
87 + hasSuccessfulToolExecution = true;
88 + }
89 + console.log(`✅ ${toolSlug} finished`);
90 + return result;
91 + },
92 + });
93 + messages.push(...toolMessages);
94 + }
95 +
96 + throw new Error(`Agent exceeded the ${MAX_STEPS}-step tool-call budget.`);
97 +}
ts/examples/openai/src/hackernews-agent/tool-router.ts new
+108
@@ -0,0 +1,108 @@
1 +import { Composio, normalizeToolArguments } from '@composio/core';
2 +import { OpenAIProvider } from '@composio/openai';
3 +import OpenAI from 'openai';
4 +
5 +const MODEL = 'gpt-5-mini';
6 +const USER_ID = 'example-user';
7 +const MAX_STEPS = 10;
8 +
9 +export interface ToolRouterHackerNewsAgentEnvironment {
10 + COMPOSIO_API_KEY?: string;
11 + OPENAI_API_KEY?: string;
12 +}
13 +
14 +function requireKey(
15 + env: ToolRouterHackerNewsAgentEnvironment,
16 + name: keyof ToolRouterHackerNewsAgentEnvironment
17 +): string {
18 + const value = env[name];
19 + if (!value) {
20 + throw new Error(`${name} is required to run the HackerNews agent.`);
21 + }
22 +
23 + return value;
24 +}
25 +
26 +export async function runToolRouterHackerNewsAgent(
27 + env: ToolRouterHackerNewsAgentEnvironment
28 +): Promise<string> {
29 + const composioApiKey = requireKey(env, 'COMPOSIO_API_KEY');
30 + const openaiApiKey = requireKey(env, 'OPENAI_API_KEY');
31 + const openai = new OpenAI({
32 + apiKey: openaiApiKey,
33 + maxRetries: 1,
34 + timeout: 60_000,
35 + });
36 + const composio = new Composio({
37 + apiKey: composioApiKey,
38 + provider: new OpenAIProvider(),
39 + });
40 + const session = await composio.sessions.create(USER_ID, {
41 + toolkits: ['hackernews'],
42 + });
43 + const tools = await session.tools();
44 + const messages: OpenAI.ChatCompletionMessageParam[] = [
45 + {
46 + role: 'system',
47 + content:
48 + 'You are a helpful assistant. Use the available Composio tools to search for and read HackerNews data before answering.',
49 + },
50 + {
51 + role: 'user',
52 + content: 'What are the current top 3 HackerNews stories? Give me their titles.',
53 + },
54 + ];
55 + let hasSuccessfulToolExecution = false;
56 +
57 + for (let step = 0; step < MAX_STEPS; step += 1) {
58 + let toolChoice: 'auto' | 'required' = 'auto';
59 + if (!hasSuccessfulToolExecution) {
60 + toolChoice = 'required';
61 + }
62 +
63 + const response = await openai.chat.completions.create({
64 + model: MODEL,
65 + messages,
66 + tools,
67 + tool_choice: toolChoice,
68 + });
69 + const message = response.choices[0]?.message;
70 + if (!message) {
71 + throw new Error('OpenAI returned no assistant message.');
72 + }
73 +
74 + messages.push(message);
75 + if (!message.tool_calls?.length) {
76 + if (!hasSuccessfulToolExecution) {
77 + throw new Error('Agent returned without successfully executing a Composio tool.');
78 + }
79 +
80 + const text = message.content?.trim();
81 + if (!text) {
82 + throw new Error('Agent returned empty output — expected a non-empty response.');
83 + }
84 + return text;
85 + }
86 +
87 + for (const toolCall of message.tool_calls) {
88 + if (toolCall.type !== 'function') {
89 + throw new Error(`Unsupported OpenAI tool call type: ${toolCall.type}`);
90 + }
91 +
92 + const result = await session.execute(
93 + toolCall.function.name,
94 + normalizeToolArguments(toolCall.function.arguments, toolCall.function.name)
95 + );
96 + if (!result.error) {
97 + hasSuccessfulToolExecution = true;
98 + }
99 + messages.push({
100 + role: 'tool',
101 + tool_call_id: toolCall.id,
102 + content: JSON.stringify(result),
103 + });
104 + }
105 + }
106 +
107 + throw new Error(`Agent exceeded the ${MAX_STEPS}-step tool-call budget.`);
108 +}
ts/examples/openai/src/index.ts
+16 -53
@@ -1,58 +1,21 @@
1 -import { Composio } from '@composio/core';
2 -import { OpenAI } from 'openai';
3 -
4 -const openai = new OpenAI({
5 - apiKey: process.env.OPENAI_API_KEY,
6 -});
7 -
1 /**
9 - * Initialize Composio
10 - * OpenAI Provider is automatically installed and initialized
2 + * OpenAI × Composio — direct tools
3 + *
4 + * Fetches a Composio tool in OpenAI function-calling format and runs a bounded
5 + * Chat Completions tool loop.
6 + *
7 + * Prerequisites:
8 + * - COMPOSIO_API_KEY (https://app.composio.dev)
9 + * - OPENAI_API_KEY
10 + *
11 + * Run:
12 + * bun ts/examples/openai/src/index.ts
13 */
12 -const composio = new Composio({
13 - apiKey: process.env.COMPOSIO_API_KEY,
14 -});
14 +import 'dotenv/config';
15
16 -/**
17 - * Get the tools
18 - * This tool is automatically typed and wrapped with the OpenAI Provider
19 - */
20 -const tools = await composio.tools.get('default', 'HACKERNEWS_GET_USER');
21 -/**
22 - * Define a task for the assistant based on the tools in hand
23 - */
24 -const task = "Fetch the details of the user 'haxzie'";
16 +import { runDirectHackerNewsAgent } from './hackernews-agent/direct';
17
26 -/**
27 - * Define the messages for the assistant
28 - */
29 -const messages: OpenAI.ChatCompletionMessageParam[] = [
30 - { role: 'system', content: 'You are a helpful assistant that can help with tasks.' },
31 - { role: 'user', content: task },
32 -];
33 -
34 -/**
35 - * Create a chat completion
36 - */
37 -const response = await openai.chat.completions.create({
38 - model: 'gpt-4o-mini',
39 - messages,
40 - tools: tools,
41 - tool_choice: 'auto',
42 -});
18 +const text = await runDirectHackerNewsAgent(process.env);
19
44 -/**
45 - * If the assistant has tool calls, execute them and log the result
46 - */
47 -if (
48 - response.choices[0].message.tool_calls &&
49 - response.choices[0].message.tool_calls[0].type === 'function'
50 -) {
51 - console.log(JSON.stringify(response, null, 2));
52 - const toolCall = response.choices[0].message.tool_calls[0];
53 - if (toolCall.type === 'function') {
54 - console.log(`✅ Calling tool ${response.choices[0].message.tool_calls[0].function.name}`);
55 - }
56 - const result = await composio.provider.handleToolCalls('default', response);
57 - console.log(result);
58 -}
20 +console.log('\n🤖 Agent response:\n');
21 +console.log(text);
ts/examples/openai/src/responses-api/index.ts
+2 -1
@@ -41,7 +41,8 @@ console.log(`🔄 Submitting tool outputs to OpenAI...`);
41 console.log(JSON.stringify(modelInputs, null, 2));
42 const finalResponse = await openai.responses.create({
43 model: 'gpt-4.1',
44 - input: [...initialResponse.output, ...modelInputs],
44 + previous_response_id: initialResponse.id,
45 + input: modelInputs,
46 tools,
47 });
48
ts/examples/openai/src/smoke.ts new
+68
@@ -0,0 +1,68 @@
1 +/**
2 + * Deterministic smoke test for the OpenAI example.
3 + *
4 + * Exercises direct provider wrapping and Tool Router session wrapping against
5 + * a real backend without making an LLM request. It needs only
6 + * COMPOSIO_API_KEY and skips cleanly when that key is absent.
7 + *
8 + * Run: bun ts/examples/openai/src/smoke.ts
9 + */
10 +import { Composio } from '@composio/core';
11 +import { OpenAIProvider } from '@composio/openai';
12 +import type OpenAI from 'openai';
13 +import 'dotenv/config';
14 +
15 +const TOOLKIT = 'hackernews';
16 +const USER_ID = 'examples-smoke';
17 +
18 +function assert(condition: unknown, message: string): asserts condition {
19 + if (!condition) {
20 + throw new Error(`SMOKE FAIL: ${message}`);
21 + }
22 +}
23 +
24 +function assertJsonSerializable(value: unknown, source: string): void {
25 + try {
26 + JSON.stringify(value);
27 + } catch {
28 + throw new Error(`SMOKE FAIL: ${source} is not JSON-serializable`);
29 + }
30 +}
31 +
32 +function assertOpenAITools(
33 + tools: unknown,
34 + source: string
35 +): asserts tools is OpenAI.ChatCompletionTool[] {
36 + assert(Array.isArray(tools), `${source} did not return an array`);
37 + assert(tools.length > 0, `${source} returned 0 tools`);
38 +
39 + for (const tool of tools) {
40 + assert(tool.type === 'function', `${source} returned a non-function tool`);
41 + assert(tool.function.name.length > 0, `${source} returned a tool without a name`);
42 + assert(tool.function.parameters != null, `${source} tool ${tool.function.name} has no schema`);
43 + assertJsonSerializable(tool.function.parameters, `${source} tool ${tool.function.name} schema`);
44 + }
45 +}
46 +
47 +if (!process.env.COMPOSIO_API_KEY) {
48 + console.log('⏭️ COMPOSIO_API_KEY not set — skipping OpenAI smoke.');
49 + process.exit(0);
50 +}
51 +
52 +console.log(`Backend: ${process.env.COMPOSIO_BASE_URL ?? '(default/production)'}`);
53 +
54 +const composio = new Composio({
55 + apiKey: process.env.COMPOSIO_API_KEY,
56 + provider: new OpenAIProvider(),
57 +});
58 +
59 +const wrapped = await composio.tools.get(USER_ID, { toolkits: [TOOLKIT] });
60 +assertOpenAITools(wrapped, 'openai direct wrapping');
61 +console.log(` ✓ direct wrapping: ${wrapped.length} tools`);
62 +
63 +const session = await composio.sessions.create(USER_ID, { toolkits: [TOOLKIT] });
64 +const sessionTools = await session.tools();
65 +assertOpenAITools(sessionTools, 'openai session.tools()');
66 +console.log(` ✓ tool-router session: ${sessionTools.length} tools`);
67 +
68 +console.log('\n✅ OpenAI smoke passed.');
ts/examples/openai/src/tool-router.ts new
+21
@@ -0,0 +1,21 @@
1 +/**
2 + * OpenAI × Composio — Tool Router
3 + *
4 + * Creates a HackerNews-scoped session, gives the session's router tools to
5 + * OpenAI, and executes every model-requested tool through that same session.
6 + *
7 + * Prerequisites:
8 + * - COMPOSIO_API_KEY (https://app.composio.dev)
9 + * - OPENAI_API_KEY
10 + *
11 + * Run:
12 + * bun ts/examples/openai/src/tool-router.ts
13 + */
14 +import 'dotenv/config';
15 +
16 +import { runToolRouterHackerNewsAgent } from './hackernews-agent/tool-router';
17 +
18 +const text = await runToolRouterHackerNewsAgent(process.env);
19 +
20 +console.log('\n🤖 Agent response:\n');
21 +console.log(text);
ts/examples/openai/tsconfig.json
+2 -1
@@ -12,5 +12,6 @@
12 "moduleResolution": "bundler",
13 "skipLibCheck": true
14 },
15 - "include": ["src"]
15 + "include": ["src"],
16 + "exclude": ["src/cloudflare.ts"]
17 }
ts/examples/openai/tsconfig.worker.json new
+15
@@ -0,0 +1,15 @@
1 +{
2 + "compilerOptions": {
3 + "target": "es2022",
4 + "lib": ["es2022"],
5 + "module": "esnext",
6 + "moduleResolution": "bundler",
7 + "strict": true,
8 + "esModuleInterop": true,
9 + "skipLibCheck": true,
10 + "resolveJsonModule": true,
11 + "noEmit": true,
12 + "types": ["@cloudflare/workers-types"]
13 + },
14 + "include": ["src/cloudflare.ts"]
15 +}
ts/examples/openai/wrangler.jsonc new
+20
@@ -0,0 +1,20 @@
1 +/**
2 + * Wrangler config for the OpenAI × Composio Workers example.
3 + * https://developers.cloudflare.com/workers/wrangler/configuration/
4 + */
5 +{
6 + "$schema": "node_modules/wrangler/config-schema.json",
7 + "name": "openai-composio-example",
8 + "main": "src/cloudflare.ts",
9 + "compatibility_date": "2025-06-20",
10 + "compatibility_flags": ["nodejs_compat"],
11 + "observability": {
12 + "enabled": true,
13 + },
14 + /**
15 + * COMPOSIO_API_KEY and OPENAI_API_KEY are provided as Worker secrets, not
16 + * committed here:
17 + * wrangler secret put COMPOSIO_API_KEY
18 + * wrangler secret put OPENAI_API_KEY
19 + */
20 +}