Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

5.3 KB
Raw Blame
import { perplexityAiAuth } from '../auth';
import {
  createAction,
  isNil,
  Property,
} from '@activepieces/pieces-framework';

import { HttpMethod, propsValidation } from '@activepieces/pieces-common';

import * as z from 'zod/mini'
import { perplexityAiClient } from '../common/client';
import type { PerplexityAiChatCompletion, PerplexityAiMessage } from '../common/types';
import { askAiOutputSchema } from '../output-schemas';

export const createChatCompletionAction = createAction({
  audience: 'both',
  auth: perplexityAiAuth,
  name: 'ask-ai',
  outputSchema: askAiOutputSchema,
  classification: 'READ',
  displayName: 'Ask AI',
  description:
    'Ask a question and get an answer sourced from the live web.',
  aiMetadata: { description: 'Sends a question to a Perplexity Sonar model, which answers from a live web search with source citations rather than model memory alone, choosing between the plain sonar models for fast grounded answers and the sonar-reasoning models for step-by-step reasoning. Pick it for a quick cited answer; use Create Agent Response to choose any catalogued model or tools, and Search the Web for raw results without an answer. Runs stateless - earlier turns must be supplied in the optional roles array, which alternates user and assistant after any system message; requires a model and a question, and is not idempotent: each call runs a new search and produces a fresh completion.', idempotent: false },
  propertyGroups: [
    { key: 'settings', display: 'section', label: 'Settings', icon: 'sliders', props: ['model', 'max_tokens'] },
    { key: 'message', display: 'section', label: 'Message', icon: 'text', props: ['prompt'] },
  ],
  props: {
    model: Property.StaticDropdown({
      displayName: 'Model',
      description:
        'Pro models dig deeper and Reasoning models think before answering.',
      required: true,
      defaultValue:'sonar-pro',
      options: {
        disabled: false,
        options: [
          {
            label:'Sonar',
            value:'sonar'
          },
          {
            label:'Sonar Pro',
            value:'sonar-pro'
          },
          {
            label:'Sonar Reasoning Pro',
            value:'sonar-reasoning-pro'
          }
        ],
      },
    }),
    prompt: Property.LongText({
      displayName: 'Question',
      description: 'What you want the model to answer or do.',
      placeholder: "e.g. Summarize this week's news about electric cars",
      required: true,
    }),
    temperature: Property.Number({
      displayName: 'Temperature',
      required: false,
      advanced: true,
      description:
        'From 0 to 2. Lower is more focused, higher is more varied.',
      defaultValue: 0.2,
    }),
    max_tokens: Property.Number({
      displayName: 'Maximum Tokens',
      required: false,
      description: 'Longest reply in tokens, about 4 characters each.',
    }),
    top_p: Property.Number({
      displayName: 'Top P',
      required: false,
      advanced: true,
      description:
        'From 0 to 1. Adjust this or Temperature, not both.',
      defaultValue: 0.9,
    }),
    presence_penalty: Property.Number({
      displayName: 'Presence Penalty',
      required: false,
      advanced: true,
      description:
        'Higher values push the model toward new topics.',
      defaultValue: 0,
    }),
    frequency_penalty: Property.Number({
      displayName: 'Frequency Penalty',
      required: false,
      advanced: true,
      description:
        'Higher values make the model repeat itself less.',
      defaultValue: 1.0,
    }),
    roles: Property.Json({
      displayName: 'Roles',
      required: false,
      advanced: true,
      description:
        'Messages sent before the question, such as a system instruction.',
      defaultValue: [
        { role: 'system', content: 'You are a helpful assistant.' },
      ],
    }),
  },
  async run(context) {
    await propsValidation.validateZod(context.propsValue, {
      temperature: z.optional(z.number().check(z.minimum(0), z.maximum(2))),
      max_tokens: z.nullish(z.int().check(z.minimum(1))),
    });
    const maxTokens = context.propsValue.max_tokens;

    const rolesArray = z
      .array(z.object({ role: z.string(), content: z.unknown() }))
      .parse(context.propsValue.roles ? context.propsValue.roles : []);
    const roles: PerplexityAiMessage[] = rolesArray.map((item) => {
      const rolesEnum = ['system', 'user', 'assistant'];
      if (!rolesEnum.includes(item.role)) {
        throw new Error(
          'The only available roles are: [system, user, assistant]'
        );
      }

      return {
        role: item.role,
        content: item.content,
      };
    });

    roles.push({ role: 'user', content: context.propsValue.prompt });

    const response = await perplexityAiClient.request<PerplexityAiChatCompletion>({
      auth: context.auth,
      method: HttpMethod.POST,
      path: '/chat/completions',
      body: {
        model: context.propsValue.model,
        messages: roles,
        ...(isNil(maxTokens) ? {} : { max_tokens: maxTokens }),
        temperature: context.propsValue.temperature,
        top_p: context.propsValue.top_p,
        presence_penalty: context.propsValue.presence_penalty,
        frequency_penalty: context.propsValue.frequency_penalty,
      },
    });

    return {
      result: response.choices[0].message.content,
      citations: response.citations,
    };
  },
});