This guide demonstrates how to implement the Growth Strategist agent in your Agentic Templates application.

Implementation Guide

Follow these steps to implement the Growth Strategist agent.

1. UI Implementation

First, create the Growth Strategist configuration in your dashboard project:

// src/lib/agents/growthStrategist.agent.ts
import type { AgentConfig, OrderFormData, RequestGrowthStrategyInput } from '@/schemas';
import { agentService } from '@/services/agentService';

export const growthStrategistAgent: AgentConfig = {
    id: '3f8e2b9a-6d1c-4f5e-9c7d-8b2a4e3d1f0c',
    name: 'Growth Strategist',
    title: 'SaaS Growth Expert',
    description: 'An expert in SaaS growth strategy and optimization',
    category: 'strategy',
    imageUrl: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?w=400&q=80&auto=format',
    credits: 20,
    available: true,
    keyDeliverables: [
        'Distribution channel strategy recommendations',
        'Customer journey optimization plan',
        'Early customer acquisition roadmap (0-10 customers)',
        'Growth scaling strategy (10-100 customers)',
        'Growth strategies'
    ],
    packageDescription: [
        'One Page Revenue Growth Strategy'
    ],
    estimatedDelivery: 'Less than 1 min',
    fields: {
        deliverableName: {
            type: 'text',
            label: 'Deliverable Name',
            required: true,
            placeholder: 'Enter in your deliverable name'
        },
        applicationIdea: {
            type: 'textarea',
            label: 'Application Idea',
            required: true,
            placeholder: 'Enter in your application idea'
        },
        idealCustomer: {
            type: 'text',
            label: 'Ideal Customer',
            required: true,
            placeholder: 'Enter in your ideal customer'
        },
        targetAnnualRevenue: {
            type: 'number',
            label: 'Target Annual Revenue ($)',
            required: true,
            placeholder: 'What is your target annual revenue?'
        }
    },
    faq: [
        {
            question: 'What is the purpose of this agent?',
            answer: 'This agent is designed to help you optimize your SaaS pricing and revenue strategy. It provides actionable advice based on your specific situation, considering factors such as business model, current customer base, and target price point.'
        }
    ],
    deliverable: {
        sections: [
            {
                id: 'applicationIdea',
                label: 'Application Idea',
                type: 'text',
                description: 'Description of the application idea',
                order: 1
            },
            {
                id: 'idealCustomer',
                label: 'Ideal Customer', 
                type: 'text',
                description: 'Description of the ideal customer',
                order: 2
            },
            {
                id: 'distributionChannels',
                label: 'Distribution Channels',
                type: 'list',
                description: 'Recommended channels for customer acquisition',
                order: 3
            },
            {
                id: 'customerJourney',
                label: 'Customer Journey',
                type: 'text', 
                description: 'Detailed customer journey optimization plan',
                order: 4
            },
            {
                id: 'firstTenCustomers',
                label: 'First Ten Customers',
                type: 'text',
                description: 'Strategy for acquiring early customers',
                order: 5
            },
            {
                id: 'firstHundredCustomers', 
                label: 'First Hundred Customers',
                type: 'text',
                description: 'Scaling strategy for growth phase',
                order: 6
            },
            {
                id: 'growthStrategies',
                label: 'Growth Strategies',
                type: 'text',
                description: 'Key strategies for growth',
                order: 7
            }
        ],
        availableFormats: ['pdf', 'markdown'],
    },
    handler: async (token: string, data: OrderFormData) => {
        const response = await agentService.handleGrowthStrategyRequest(
            token,
            data.payload.formData as RequestGrowthStrategyInput
        );
        return response;
    }
};

2. API Endpoints Implementation

Add the Growth Strategist endpoint to your API infrastructure:

// infra/api.ts
api.route("POST /growth-strategy", {
  link: [...apiResources],
  handler: "./packages/functions/src/orchestrator.api.handleRequestGrowthStrategy",
  timeout: "900 seconds"
});

3. Infrastructure Updates

Set up the necessary infrastructure components:

// infra/queues.ts
export const growthStrategyQueue = new sst.aws.Queue("GrowthStrategyQueue", {
    fifo: true
});   

growthStrategyQueue.subscribe({
    handler: "./packages/functions/src/agent-plane.api.growthStrategyHandler", 
    link: [
        deliverablesTable, 
        ordersTable, 
        openaiApiKey, 
    ], 
    permissions: [
        {
            actions: ["dynamodb:*"], 
            resources: [deliverablesTable.arn, ordersTable.arn]
        }
    ],
    timeout: "10 minutes"
});
// infra/topic.ts
orderTopic.subscribeQueue(
  "growthStrategy", 
  growthStrategyQueue.arn, 
  {
      filter: {
          "queue": ["growthStrategy"]
      }
  }
);

4. Orchestrator Updates

Update the orchestrator to handle Growth Strategist requests:

// packages/core/src/orchestrator/metadata/agent-plane.schema.ts
export const GrowthStrategySchema = z.object({
  sections: z.object({
    applicationIdea: z.object({
      id: z.string(),
      label: z.string(),
      type: z.literal('text'),
      description: z.string().optional(),
      data: z.string(),
    }),
    idealCustomer: z.object({
      id: z.string(),
      label: z.string(),
      type: z.literal('text'),
      description: z.string().optional(),
      data: z.string(),
    }),
    distributionChannels: z.object({
      id: z.string(),
      label: z.string(),
      type: z.literal('list'),
      description: z.string().optional(),
      data: z.array(z.string()),
    }),
    customerJourney: z.object({
      id: z.string(),
      label: z.string(),
      type: z.literal('text'),
      description: z.string().optional(),
      data: z.string(),
    }),
    firstTenCustomers: z.object({
      id: z.string(),
      label: z.string(),
      type: z.literal('text'),
      description: z.string().optional(),
      data: z.string(),
    }),
    firstHundredCustomers: z.object({
      id: z.string(),
      label: z.string(),
      type: z.literal('text'),
      description: z.string().optional(),
      data: z.string(),
    }),
    growthStrategies: z.object({
      id: z.string(),
      label: z.string(),
      type: z.literal('text'),
      description: z.string().optional(),
      data: z.string(),
    })
  })
});

export const BasePayloadSchema = z.object({ 
  userId: z.string(),
  orderId: z.string(),
  deliverableId: z.string(),
  deliverableName: z.string(),
  agentId: z.string(),
});

export const RequestGrowthStrategyInputSchema = BasePayloadSchema.extend({
    applicationIdea: z.string(),
    idealCustomer: z.string(),
    targetAnnualRevenue: z.number()
});

export const RequestGrowthStrategyOutputSchema = z.object({
  strategy: z.string(),
});

export const DeliverableSchema = z.object({
  deliverableContent: GrowthStrategySchema, 
});

export const DeliverableDTOSchema = BasePayloadSchema.extend({
  deliverableContent: GrowthStrategySchema, 
});

export type RequestGrowthStrategyInput = z.infer<typeof RequestGrowthStrategyInputSchema>;
export type RequestGrowthStrategyOutput = z.infer<typeof RequestGrowthStrategyOutputSchema>;
export type Deliverable = z.infer<typeof DeliverableSchema>;
export type DeliverableDTO = z.infer<typeof DeliverableDTOSchema>;

5. Agent Plane Implementation

Create the Growth Strategist agent plane implementation:

// packages/core/src/agent-plane/growth-strategist/metadata/growth-strategist.prompt.ts
const growthStrategySystemPrompt = () => `You are an expert growth strategist. Your order is to create a detailed one-page growth strategy based on the provided application idea, ideal customer profile, and target annual revenue. Focus on actionable steps and realistic growth tactics.`;
// packages/core/src/agent-plane/growth-strategist/adapters/primary/create-strategy.adapter.ts
import { SQSEvent, SQSRecord } from 'aws-lambda';
import { RequestGrowthStrategyInputSchema } from '@agent-plane/growth-strategist/metadata/growth-strategist.schema';
import { createStrategyUsecase } from '@agent-plane/growth-strategist/usecases/create-strategy.usecase';

export const createStrategyAdapter = async (event: SQSEvent) => {
    console.info("--- Growth Strategy Queue Adapter ---");
    if (!event.Records || event.Records.length === 0) {
        throw new Error("Missing SQS Records");
    }

    const results = await Promise.all(event.Records.map(async (record: SQSRecord) => {
        const message = JSON.parse(record.body);
        const order = RequestGrowthStrategyInputSchema.parse(JSON.parse(message.Message));
        return await createStrategyUsecase(order);
    }));

    return results;
};
// packages/core/src/agent-plane/growth-strategist/usecases/create-strategy.usecase.ts
export const createStrategyUsecase = async (input: RequestGrowthStrategyInput): Promise<Message> => {
  console.info("Creating growth strategy for User");

  try {
    const content = await runGrowthStrategy(input);
    const deliverable: DeliverableDTO = {
      userId: input.userId,
      orderId: input.orderId,
      deliverableId: input.deliverableId,
      deliverableName: input.deliverableName,
      agentId: input.agentId,
      ...content
    };
    await deliverableRepository.saveDeliverable(deliverable);
    return {
      message: 'Growth strategy created successfully',
    };

  } catch (error) {
    console.error('Error generating growth strategy:', error);
    throw new Error('Failed to generate growth strategy');
  }
};
// packages/core/src/agent-plane/growth-strategist/adapters/secondary/openai.adapter.ts
import OpenAI from "openai";
import { Deliverable, DeliverableSchema, RequestGrowthStrategyInput } from "@agent-plane/growth-strategist/metadata/growth-strategist.schema";
import { zodResponseFormat } from "openai/helpers/zod";
import { Resource } from "sst";
import { withRetry } from "@utils/tools/retry";
import { zodToJsonSchema } from "zod-to-json-schema";

const client = new OpenAI({
  apiKey: Resource.OpenAIApiKey.value
});

const growthStrategySystemPrompt = () => `You are an expert growth strategist. Your order is to create a detailed one-page growth strategy based on the provided application idea, ideal customer profile, and target annual revenue. Focus on actionable steps and realistic growth tactics.`;

export const createGrowthStrategy = async (input: RequestGrowthStrategyInput): Promise<Deliverable> => {
  try {
    const assistant = await client.beta.assistants.create({
      name: "Growth Strategist",
      instructions: growthStrategySystemPrompt(),
      model: "gpt-4",
      response_format: zodResponseFormat(DeliverableSchema, "deliverable"),
      tools: [{ type: "function", function: {
        name: "generateDeliverable",
        parameters: zodToJsonSchema(DeliverableSchema)
      }}]
    });

    const thread = await client.beta.threads.create();
    
    await client.beta.threads.messages.create(thread.id, {
      role: "user",
      content: `Please create a growth strategy for:
        Application Idea: ${input.applicationIdea}
        Ideal Customer: ${input.idealCustomer}
        Target Annual Revenue: $${input.targetAnnualRevenue}`
    });

    const run = await client.beta.threads.runs.create(thread.id, {
      assistant_id: assistant.id
    });

    const completedRun = await waitForRunCompletion(client, thread.id, run.id);
    
    const messages = await client.beta.threads.messages.list(thread.id);
    const lastMessage = messages.data[0];

    if (!lastMessage.content || lastMessage.content.length === 0) {
      throw new Error("No content generated from OpenAI API");
    }

    const textContent = lastMessage.content.find(c => c.type === 'text');
    if (!textContent) {
      throw new Error("No text content found in the response");
    }

    const content = JSON.parse(textContent.text.value);
    const validatedContent = await DeliverableSchema.parseAsync(content);
    
    await client.beta.assistants.del(assistant.id);
    await client.beta.threads.del(thread.id);
    return validatedContent;

  } catch (error) {
    console.error('Error generating growth strategy:', error);
    throw error;
  }
};

async function waitForRunCompletion(client: OpenAI, threadId: string, runId: string) {
  while (true) {
    const run = await client.beta.threads.runs.retrieve(threadId, runId);
    
    switch (run.status) {
      case 'completed':
        return run;
      case 'failed':
      case 'cancelled':
      case 'expired':
        throw new Error(`Run ended with status: ${run.status}`);
      case 'requires_action':
        if (run.required_action?.type === 'submit_tool_outputs') {
          const toolCall = run.required_action.submit_tool_outputs.tool_calls[0];
          const functionArgs = JSON.parse(toolCall.function.arguments);
          
          await client.beta.threads.runs.submitToolOutputs(threadId, runId, {
            tool_outputs: [{
              tool_call_id: toolCall.id,
              output: JSON.stringify(functionArgs)
            }]
          });
        }
        break;
      default:
        await new Promise(resolve => setTimeout(resolve, 1000));
    }
  }
}

export const runGrowthStrategy = withRetry(createGrowthStrategy, { 
  retries: 3, 
  delay: 1000, 
  onRetry: (error: Error) => console.warn('Retrying growth strategy generation due to error:', error) 
});

This completes the implementation of the Growth Strategist agent. The agent will:

  1. Accept user input (application idea, ideal customer, target revenue)
  2. Process the request through the API
  3. Generate a comprehensive growth strategy using OpenAI
  4. Store the deliverable in the database
  5. Return the result to the user