Skip to content

Conversation

TensorNull
Copy link

@TensorNull TensorNull commented Sep 3, 2025

WHY

CometAPI is a powerful AI API service that provides access to 578+ AI models from multiple families including GPT, Claude, Gemini, Grok, DeepSeek, and Qwen. This integration enables Pipedream users to leverage these diverse AI capabilities directly in their workflows without needing to manage multiple API keys or endpoints.

Business Value

  • Unified AI Access: Single integration point for 578+ AI models across major providers
  • Workflow Enhancement: Enables AI-powered automation for chat, text generation, and content creation
  • Developer Experience: Simplified API interface with comprehensive error handling and validation
  • Cost Efficiency: Competitive pricing through CometAPI's aggregated model access

WHAT

This PR introduces a complete CometAPI integration for Pipedream with the following components:

Core Components

  • Main App Component (cometapi.app.mjs): Authentication and API client with 578 model support
  • Package Configuration (package.json): Dependencies and metadata
  • Documentation (README.md): User guide and setup instructions

Actions Implemented

  1. Send Chat Completion Request (send-chat-completion-request):

    • Conversational AI interactions with message history support
    • Role-based conversations (system, user, assistant)
    • Comprehensive input validation and error handling
  2. Send Completion Request (send-completion-request):

    • Text generation and completion capabilities
    • Configurable parameters (temperature, max_tokens, etc.)
    • Support for all available model families
  3. Retrieve Available Models (retrieve-available-models):

    • Dynamic model discovery and listing
    • Real-time access to CometAPI's model catalog
    • Easy model selection for users

Utilities

  • Common Utils (common/utils.mjs): JSON parsing and data sanitization
  • Constants (common/constants.mjs): API endpoints and configuration

Key Features

  • 578+ AI Models: Support for GPT-4, Claude-3, Gemini, Grok, DeepSeek, Qwen families
  • Bearer Token Authentication: Secure API key management
  • Comprehensive Validation: Input validation with detailed error messages
  • Error Handling: Robust error handling with ConfigurationError support
  • Type Safety: Proper prop definitions and data type validation
  • ESLint Compliant: Follows Pipedream coding standards

HOW

Implementation Details

  • Built following Pipedream's component architecture patterns
  • Analyzed existing integrations (OpenAI, Anthropic) for consistency
  • Implemented comprehensive testing including API connectivity and runtime simulation
  • Added proper error handling with user-friendly messages
  • Included input validation to prevent common user errors

Testing Performed

  • ✅ Direct API connectivity testing with real API key
  • ✅ Pipedream runtime environment simulation
  • ✅ User scenario validation (chat, completion, model retrieval)
  • ✅ Error handling verification
  • ✅ ESLint compliance verification

Breaking Changes

None - this is a new integration with no existing dependencies.

Migration Guide

Not applicable - new integration.

Security Considerations

  • API keys are handled securely through Pipedream's authentication system
  • Input sanitization prevents XSS and injection attacks
  • Bearer token authentication follows industry standards

Summary by CodeRabbit

  • New Features

    • Added CometAPI integration for Pipedream with actions to retrieve models, send chat completions, and send text completions.
    • Supports major model families (GPT, Claude, Gemini, Grok, DeepSeek, Qwen).
    • Configurable generation settings: model, max tokens, temperature, top-p/k, penalties, seed, stop sequences, streaming.
    • Built-in validation and user-friendly errors (authentication, rate limits, invalid input) with timeout protection.
  • Documentation

    • New README with setup/authentication steps, usage examples, supported models, configuration options, rate limit info, and support resources.

TensorNull and others added 4 commits September 3, 2025 18:08
- Add main CometAPI app component with 578 model support
- Implement send-chat-completion-request action for conversational AI
- Implement send-completion-request action for text generation
- Implement retrieve-available-models action for model discovery
- Add comprehensive error handling and input validation
- Include utility functions and constants
- Support for GPT, Claude, Gemini, Grok, DeepSeek, Qwen model families
- Bearer token authentication with proper security
- Fix model data access path (response.data.data)
- Add comprehensive JSDoc documentation
- Set default values for all optional parameters
- Improve async options functionality for model selection
- Ensure 100% Pipedream component guidelines compliance
- Verify 578+ models working correctly with real API testing
- Fix model options destructuring syntax error
- Add 5-minute timeout configuration for API requests
- Enhance error handling with status code messages
- Change messages prop type from string[] to object[]
- Improve numeric validation using Number.isFinite
- Add model requirement validation
- Fix syntax errors and eslint violations
- Enhance parameter validation with proper type checking

All suggestions from CodeRabbitAI review have been implemented
to ensure production-ready code quality. API tested and working.
@adolfo-pd adolfo-pd added the User submitted Submitted by a user label Sep 3, 2025
Copy link

vercel bot commented Sep 3, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

2 Skipped Deployments
Project Deployment Preview Comments Updated (UTC)
pipedream-docs Ignored Ignored Sep 9, 2025 3:20pm
pipedream-docs-redirect-do-not-edit Ignored Ignored Sep 9, 2025 3:20pm

Copy link
Contributor

coderabbitai bot commented Sep 3, 2025

Important

Review skipped

Review was skipped due to path filters

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml

CodeRabbit blocks several paths by default. You can override this behavior by explicitly including those paths in the path filters. For example, including **/dist/** will override the default block on the dist directory, by removing the pattern from both the lists.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

Introduces a new Pipedream integration for CometAPI, adding an app definition, two completion actions (chat and text), a model-listing action, shared utilities/constants, a package manifest, and documentation. The app wraps CometAPI endpoints, provides auth, dynamic model options, parameter prop definitions, request helpers with error handling, and 5-minute timeouts.

Changes

Cohort / File(s) Summary
Docs
components/cometapi/README.md
New README describing features, auth, supported models, usage examples, parameters, errors, rate limits, support, and license.
CometAPI App & Package
components/cometapi/cometapi.app.mjs, components/cometapi/package.json
New Pipedream app for CometAPI with prop definitions, auth headers, request helper, and methods: listModels, sendChatCompletionRequest, sendCompletionRequest. Adds package metadata and dependency on @pipedream/platform.
Actions — Models
components/cometapi/actions/retrieve-available-models/retrieve-available-models.mjs
New action to list available models via cometapi.listModels, summarizing count and returning the response.
Actions — Chat Completion
components/cometapi/actions/send-chat-completion-request/send-chat-completion-request.mjs
New chat completion action with input validation, numeric normalization, payload construction (messages, sampling/penalties, stop/stream/seed), undefined-stripping, API call, and success summary.
Actions — Text Completion
components/cometapi/actions/send-completion-request/send-completion-request.mjs
New text completion action validating model/prompt, normalizing/bounding params, trimming prompt, building payload, calling API, and exporting a summary.
Common Utilities
components/cometapi/common/utils.mjs, components/cometapi/common/constants.mjs
Adds parseObject and sanitizeString helpers; adds EFFORT_OPTIONS constant ["high","medium","low"].

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant PD as Pipedream Action
  participant App as CometAPI App
  participant API as CometAPI HTTP API

  rect rgb(245,248,255)
  note over User,PD: Retrieve Available Models
  User->>PD: Run "Retrieve Available Models"
  PD->>App: listModels({ $ })
  App->>API: GET /v1/models with Authorization
  API-->>App: 200 JSON (models[])
  App-->>PD: models[]
  PD-->>User: Summary: N models
  end
Loading
sequenceDiagram
  autonumber
  actor User
  participant PD as Pipedream Action
  participant App as CometAPI App
  participant API as CometAPI HTTP API

  rect rgb(245,255,245)
  note over User,PD: Send Chat Completion
  User->>PD: Provide model, messages, params
  PD->>PD: Validate inputs & normalize params
  PD->>App: sendChatCompletionRequest({ $, payload })
  App->>API: POST /v1/chat/completions
  alt 200 OK
    API-->>App: response
    App-->>PD: response
    PD-->>User: Summary + response
  else 4xx/5xx
    API-->>App: error
    App-->>PD: standardized error
    PD-->>User: Error surfaced
  end
  end
Loading
sequenceDiagram
  autonumber
  actor User
  participant PD as Pipedream Action
  participant App as CometAPI App
  participant API as CometAPI HTTP API

  rect rgb(255,250,240)
  note over User,PD: Send Text Completion
  User->>PD: Provide model, prompt, params
  PD->>PD: Validate prompt & normalize params
  PD->>App: sendCompletionRequest({ $, payload })
  App->>API: POST /v1/completions
  API-->>App: response or error
  App-->>PD: response/error
  PD-->>User: Summary or error
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I thump the keys with comet speed,
New routes for chats and texts I read—
Models line up, neat and bright,
I twitch an ear: “All clear, take flight!”
With streams or stops, I hop along,
Five-minute burrow, swift and strong.
Carrots cached; requests belong.

✨ Finishing Touches
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pipedream-component-development
Copy link
Collaborator

Thank you so much for submitting this! We've added it to our backlog to review, and our team has been notified.

@pipedream-component-development
Copy link
Collaborator

Thanks for submitting this PR! When we review PRs, we follow the Pipedream component guidelines. If you're not familiar, here's a quick checklist:

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (19)
components/cometapi/common/constants.mjs (1)

1-5: Confirm usage or remove dead export

EFFORT_OPTIONS isn't referenced elsewhere in the provided changes. If unused, drop it to avoid dead exports; if planned, add a brief JSDoc on intended consumers.

-export const EFFORT_OPTIONS = [
-  "high",
-  "medium",
-  "low",
-];
+// Future-use? If not referenced, remove this export.
+export const EFFORT_OPTIONS = Object.freeze([
+  "high",
+  "medium",
+  "low",
+]);
components/cometapi/common/utils.mjs (2)

4-13: Optional: Preserve original error as cause

Include the original error as a cause to aid debugging.

-    } catch (err) {
-      throw new Error(`Invalid JSON: ${err.message}`);
-    }
+    } catch (err) {
+      throw new Error(`Invalid JSON: ${err.message}`, { cause: err });
+    }

15-22: Sanitization is narrow; broaden protocol stripping and tag removal

Current regex removes only <script> blocks and javascript: substrings. Consider dropping other dangerous protocols (vbscript:, data:) and optionally strip all tags if HTML isn’t expected.

 export function sanitizeString(str) {
   if (typeof str !== "string") return str;

-  // Remove any potential script tags or dangerous content
-  return str.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "")
-    .replace(/javascript:/gi, "")
-    .trim();
+  // Remove script blocks, any HTML tags (optional), and dangerous protocols
+  return str
+    .replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, "")
+    .replace(/<[^>]+>/g, "") // drop all tags if plain text expected
+    .replace(/\b(?:javascript|vbscript|data):/gi, "")
+    .trim();
 }

If HTML must be preserved, skip the <[^>]+> removal and apply a vetted sanitizer upstream.

components/cometapi/README.md (3)

21-43: Avoid hard-coding model IDs; point users to dynamic list

These IDs can drift. Recommend instructing users to select models from the action’s dynamic “Model” prop instead of maintaining static lists here.

-## Supported Models
-...
-### GPT Series
-...
-### Other Models
-...
+## Supported Models
+Models are discovered dynamically from CometAPI at run time. In Pipedream, use the “Model” dropdown to see the current list exposed by your account.

47-65: Show full action usage context

Add a minimal Pipedream step example (component import + props) so users can copy/paste into a workflow.


79-83: Clarify streaming support

The code doesn’t implement SSE handling; streaming likely won’t surface incremental tokens in Pipedream. Clarify that stream: true returns a streamed payload as a single response body, or state it’s not supported yet.

components/cometapi/cometapi.app.mjs (5)

31-38: Consider consistent numeric typing

maxTokens is integer, but related numeric props (e.g., temperature, topP, penalties) are strings. If the API expects numbers, coerce before sending to avoid type surprises.

Example helper (to be used in actions or here before POST):

+normalizeGenParams(params) {
+  const floatKeys = ["temperature","topP","frequencyPenalty","presencePenalty","repetitionPenalty"];
+  const intKeys = ["maxTokens","topK","seed"];
+  const out = { ...params };
+  floatKeys.forEach(k => out[k] = out[k] != null ? parseFloat(out[k]) : out[k]);
+  intKeys.forEach(k => out[k] = out[k] != null ? parseInt(out[k], 10) : out[k]);
+  return out;
+},

115-120: Minor: add User-Agent for observability

Including a UA helps CometAPI support identify traffic origin.

     _getHeaders() {
       return {
         "Authorization": `Bearer ${this.$auth.api_key}`,
         "Content-Type": "application/json",
+        "User-Agent": "Pipedream-CometAPI/1.0",
       };
     },

139-155: Expand error normalization and surface non-response errors

Handle 403 and fallback message when error.response is absent (network issues).

-      }).catch((error) => {
+      }).catch((error) => {
         // Enhanced error handling for common API issues
         if (error.response) {
           const {
             status, data,
           } = error.response;
           if (status === 401) {
             throw new Error("[401] Authentication failed. Please check your CometAPI key.");
           }
           if (status === 429) {
             throw new Error("[429] Rate limit exceeded. Please wait before making another request.");
           }
-          if (status === 400 && data?.error?.message) {
-            throw new Error(`[400] CometAPI Error: ${data.error.message}`);
-          }
+          if (status === 403) {
+            throw new Error("[403] Forbidden. Your API key lacks permission for this resource.");
+          }
+          const msg = data?.error?.message || data?.message;
+          if (status === 400 && msg) {
+            throw new Error(`[400] CometAPI Error: ${msg}`);
+          }
         }
-        throw error;
+        // Network / timeout / unknown
+        throw new Error(error.message || "Request failed without a response from CometAPI.");
       });

158-170: Docstring mismatch

Comment mentions “with pagination handling” but no pagination is implemented (and likely not needed). Update the doc to avoid confusion.

-  * List all available models from CometAPI with pagination handling
+  * List all available models from CometAPI

94-100: Streaming caveat

stream: true won’t yield incremental tokens without SSE handling. If unsupported, consider validating and rejecting stream: true at the action level or document the behavior.

Also applies to: 179-206

components/cometapi/package.json (2)

2-6: Add repository and license metadata to avoid npm warnings.

Recommend adding "repository" and "license" fields for discoverability and compliance.

Apply this diff:

   "name": "@pipedream/cometapi",
   "version": "0.0.1",
   "description": "Pipedream CometAPI Components",
   "main": "cometapi.app.mjs",
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/PipedreamHQ/pipedream.git"
+  },
+  "license": "MIT",
   "keywords": [

Also applies to: 14-21


19-21: Bump @pipedream/platform to ^3.1.0. v3.1.0 is available on npm—update to include the latest fixes.

components/cometapi/actions/send-completion-request/send-completion-request.mjs (3)

22-27: Mark Prompt required at the UI layer.

You validate at runtime; also expose as required for better UX.

     prompt: {
       type: "string",
       label: "Prompt",
+      optional: false,
       description: "The text prompt to complete. This can be a question, partial sentence, " +

143-156: Ensure stream is boolean and keep payload tidy.

-  const data = {
+  const data = {
     model: this.model,
     prompt: this.prompt.trim(),
-    stream: this.stream || false,
+    stream: Boolean(this.stream),

165-171: Optional: enrich errors and summary.

Wrap the API call to add a clearer summary on failures; Pipedream will still surface the error.

-  const response = await this.cometapi.sendCompletionRequest({
-    $,
-    data,
-  });
-
-  $.export("$summary", `Successfully sent completion request using model ${this.model}`);
-  return response;
+  try {
+    const response = await this.cometapi.sendCompletionRequest({ $, data });
+    $.export("$summary", `Sent completion request using model ${this.model}`);
+    return response;
+  } catch (err) {
+    $.export("$summary", `Failed completion request for model ${this.model}`);
+    throw err;
+  }
components/cometapi/actions/retrieve-available-models/retrieve-available-models.mjs (1)

3-18: Implement client-side filtering for listModels results
The CometAPI listModels endpoint always returns all models in one response and does not support server-side filtering or pagination; apply basic client-side filters (e.g. search, family) on response.data before exporting.

components/cometapi/actions/send-chat-completion-request/send-chat-completion-request.mjs (2)

177-190: Ensure stream is boolean and trim message content.

Boolean cast avoids truthy surprises; trimming protects against accidental whitespace-only messages.

-  const data = {
+  const cleaned = messages.map((m) => ({ ...m, content: m.content.trim() }));
+  const data = {
     model: this.model,
-    messages,
-    stream: this.stream || false,
+    messages: cleaned,
+    stream: Boolean(this.stream),

199-206: Optional: add try/catch for clearer summaries on failure.

-  const response = await this.cometapi.sendChatCompletionRequest({
-    $,
-    data,
-  });
-
-  $.export("$summary", `Successfully sent chat completion request using model ${this.model}`);
-  return response;
+  try {
+    const response = await this.cometapi.sendChatCompletionRequest({ $, data });
+    $.export("$summary", `Sent chat completion request using model ${this.model}`);
+    return response;
+  } catch (err) {
+    $.export("$summary", `Failed chat completion request for model ${this.model}`);
+    throw err;
+  }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 9b23afd and f4c4059.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • components/cometapi/README.md (1 hunks)
  • components/cometapi/actions/retrieve-available-models/retrieve-available-models.mjs (1 hunks)
  • components/cometapi/actions/send-chat-completion-request/send-chat-completion-request.mjs (1 hunks)
  • components/cometapi/actions/send-completion-request/send-completion-request.mjs (1 hunks)
  • components/cometapi/cometapi.app.mjs (1 hunks)
  • components/cometapi/common/constants.mjs (1 hunks)
  • components/cometapi/common/utils.mjs (1 hunks)
  • components/cometapi/package.json (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2024-12-12T19:23:09.039Z
Learnt from: jcortes
PR: PipedreamHQ/pipedream#14935
File: components/sailpoint/package.json:15-18
Timestamp: 2024-12-12T19:23:09.039Z
Learning: When developing Pipedream components, do not add built-in Node.js modules like `fs` to `package.json` dependencies, as they are native modules provided by the Node.js runtime.

Applied to files:

  • components/cometapi/package.json
🧬 Code graph analysis (1)
components/cometapi/common/utils.mjs (1)
components/akeneo/akeneo.app.mjs (1)
  • JSON (99-110)
🪛 LanguageTool
components/cometapi/README.md

[grammar] ~3-~3: There might be a mistake here.
Context: ...ng GPT, Claude, Gemini, Grok, DeepSeek, and Qwen series. ## Features - **Retrieve...

(QB_NEW_EN)


[grammar] ~39-~39: There might be a mistake here.
Context: ...-gemini-2.0-flash ### Other Models - Grok series (grok-4-0709, grok-3`) - ...

(QB_NEW_EN)


[grammar] ~40-~40: There might be a mistake here.
Context: ... - Grok series (grok-4-0709, grok-3) - DeepSeek series (deepseek-v3.1, `deeps...

(QB_NEW_EN)


[grammar] ~41-~41: There might be a mistake here.
Context: ...eries (deepseek-v3.1, deepseek-chat) - Qwen series (qwen3-30b-a3b) ## Usage ...

(QB_NEW_EN)


[grammar] ~69-~69: There might be a mistake here.
Context: ...iguration Options ### Common Parameters - Model: Choose from available CometAPI ...

(QB_NEW_EN)


[grammar] ~79-~79: There might be a mistake here.
Context: ...inistic outputs ### Advanced Parameters - Stop: Array of stop sequences - **Stre...

(QB_NEW_EN)


[grammar] ~80-~80: There might be a mistake here.
Context: ...ters - Stop: Array of stop sequences - Stream: Enable streaming responses (de...

(QB_NEW_EN)


[grammar] ~81-~81: There might be a mistake here.
Context: ...ble streaming responses (default: false) - Repetition Penalty: Additional repetit...

(QB_NEW_EN)


[grammar] ~86-~86: There might be a mistake here.
Context: ...n includes comprehensive error handling: - Authentication errors with clear message...

(QB_NEW_EN)


[grammar] ~87-~87: There might be a mistake here.
Context: ...uthentication errors with clear messages - API rate limit handling - Invalid parame...

(QB_NEW_EN)


[grammar] ~88-~88: There might be a mistake here.
Context: ...clear messages - API rate limit handling - Invalid parameter validation - Network t...

(QB_NEW_EN)


[grammar] ~89-~89: There might be a mistake here.
Context: ... handling - Invalid parameter validation - Network timeout protection (5-minute def...

(QB_NEW_EN)


[grammar] ~98-~98: There might be a mistake here.
Context: ...# Support For CometAPI-specific issues: - [CometAPI Documentation](https://api.come...

(QB_NEW_EN)


[grammar] ~99-~99: There might be a mistake here.
Context: ...ecific issues: - CometAPI Documentation - [CometAPI Website](https://www.cometapi.c...

(QB_NEW_EN)


[grammar] ~102-~102: There might be a mistake here.
Context: ...com/) For Pipedream integration issues: - [Pipedream Community](https://pipedream.c...

(QB_NEW_EN)


[grammar] ~103-~103: There might be a mistake here.
Context: ...tegration issues: - Pipedream Community - [Pipedream Documentation](https://pipedre...

(QB_NEW_EN)

🔇 Additional comments (5)
components/cometapi/README.md (1)

15-18: Verify console/docs links

Confirm these URLs and paths before publishing; they tend to change.

components/cometapi/package.json (1)

1-22: Manifest looks solid and minimal.

Scoped name, main entry, public publish config, and dependency on @pipedream/platform are correct.

components/cometapi/actions/send-completion-request/send-completion-request.mjs (1)

1-3: Imports are correct and align with Pipedream patterns.

components/cometapi/actions/retrieve-available-models/retrieve-available-models.mjs (1)

1-19: LGTM.

Straightforward action that delegates to app.listModels and surfaces a concise summary.

components/cometapi/actions/send-chat-completion-request/send-chat-completion-request.mjs (1)

1-4: Verify parseObject behavior before parsing arrays
I couldn’t locate the parseObject implementation—please confirm it returns array inputs unchanged. If it doesn’t, guard against double-parsing:

const messages = Array.isArray(this.messages)
  ? this.messages
  : parseObject(this.messages);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
User submitted Submitted by a user
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants