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

Implementation Guide

Follow these steps to implement the Value Strategist agent.

1. Implement the Agent UI

Start with the agent configuration in the dashboard repository. This is where you’ll define how the Value Strategist appears and behaves in the UI.

Create Agent Configuration

First, create your Value Strategist configuration in your dashboard project:

// src/lib/agents/valueStrategist.agent.ts
import { AgentConfig } from '@/schemas/agent';
import { v4 as uuidv4 } from 'uuid';

export const valueStrategistAgent: AgentConfig = {
  id: uuidv4(),
  name: 'Value Strategist',
  title: 'Value Proposition Specialist',
  description: 'Transform your idea into a comprehensive value specification',
  category: 'strategy',
  imageUrl: '/agents/value-strategist.png',
  credits: 50,
  available: true,
  keyDeliverables: [
    'Detailed value proposition canvas',
    'Target market analysis',
    'Customer pain points and gains',
    'Competitive positioning strategy'
  ],
  rating: 4.8,
  longDescription: 'The Value Strategist analyzes your business idea and creates a comprehensive value specification document that outlines your unique value propositions, target market segments, and competitive advantages.',
  fields: {
    businessIdea: {
      type: 'textarea',
      label: 'Describe your business idea',
      required: true,
      placeholder: 'What problem does your solution solve?'
    },
    targetMarket: {
      type: 'text',
      label: 'Target Market',
      required: true,
      placeholder: 'Who are your ideal customers?'
    },
    competitors: {
      type: 'textarea',
      label: 'Known Competitors',
      required: false,
      placeholder: 'List any known competitors'
    }
  },
  packageDescription: [
    'Comprehensive value proposition analysis',
    'Target market segmentation',
    'Competitor analysis matrix',
    'Strategic positioning recommendations'
  ],
  estimatedDelivery: '24 hours',
  faq: [
    {
      question: 'What format will I receive the value specification in?',
      answer: 'You will receive a detailed PDF document containing your value proposition canvas, market analysis, and strategic recommendations.'
    }
  ],
  deliverable: {
    sections: [
      {
        id: 'valueProposition',
        label: 'Value Proposition',
        type: 'text',
        description: 'Core value proposition',
        order: 1
      },
      {
        id: 'targetMarket',
        label: 'Target Market',
        type: 'text',
        description: 'Market segmentation analysis',
        order: 2
      },
      {
        id: 'painPoints',
        label: 'Pain Points',
        type: 'list',
        description: 'Customer pain points',
        order: 3
      },
      {
        id: 'gains',
        label: 'Gains',
        type: 'list',
        description: 'Customer gains',
        order: 4
      },
      {
        id: 'competitors',
        label: 'Competitors',
        type: 'text',
        description: 'Competitive analysis',
        order: 5
      },
      {
        id: 'positioning',
        label: 'Positioning',
        type: 'text',
        description: 'Strategic positioning',
        order: 6
      }
    ],
    availableFormats: ['pdf', 'markdown'],
  },
  handler: async (token: string, data: OrderFormData) => {
    const response = await agentService.handleValueStrategistRequest(
      token,
      data.payload.formData
    );
    return response;
  }
};

Update the index file in lib/agents/index.ts

// src/lib/agents/index.ts
import { valueStrategistAgent } from './valueStrategist.agent';

export const agents = {
    valueStrategist: valueStrategistAgent,
    // ... other agents
} as const;

Update schemas/agent.ts with the input types for the agent

// src/schemas/agent.ts
import { z } from 'zod';

export const ValueStrategistInputSchema = z.object({
    businessIdea: z.string().min(10),
    targetMarket: z.string().min(5),
    competitors: z.string().optional()
});

export type ValueStrategistInput = z.infer<typeof ValueStrategistInputSchema>;

Update schemas/api.ts with the response body expected from the API

// src/schemas/api.ts
import { z } from 'zod';

export const ValueStrategistResponseSchema = z.object({
    orderId: z.string(),
    orderStatus: z.string(),
    orderCreatedAt: z.string(),
    deliverableName: z.string()
});

export type ValueStrategistResponse = z.infer<typeof ValueStrategistResponseSchema>;

Add the handler to services/agentService.ts

// src/services/agentService.ts
import { ValueStrategistInput, ValueStrategistResponse } from '@/schemas';
import { api } from './api';

export const agentService = {
    handleValueStrategistRequest: async (
        token: string,
        input: ValueStrategistInput
    ): Promise<ValueStrategistResponse> => {
        return await api.post('/value-strategy', input, token);
    }
};

2. Implement the API Endpoints

2.1 Update the infrastructure to support the Value Strategist

Update the infra/api.ts file

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

Update the infra/queues.ts file

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

valueStrategyQueue.subscribe({
    handler: "./packages/functions/src/agent-plane.api.valueStrategyHandler", 
    link: [
        deliverablesTable, 
        ordersTable, 
        openaiApiKey, 
    ], 
    permissions: [
        {
            actions: ["dynamodb:*"], 
            resources: [deliverablesTable.arn, ordersTable.arn]
        }
    ],
    timeout: "10 minutes"
});

Update the infra/topic.ts file

// infra/topic.ts
orderTopic.subscribeQueue(
    "valueStrategy", 
    valueStrategyQueue.arn, 
    {
        filter: {
            "queue": ["valueStrategy"]
        }
    }
);

2.2 Update the orchestrator to route the request to the order topic

Update the metadata/agent-plane.schema.ts file with input types

// packages/core/src/orchestrator/metadata/agent-plane.schema.ts
import { z } from 'zod';

export const ValueStrategySchema = z.object({
  sections: z.object({
    valueProposition: z.object({
      id: z.string(),
      label: z.string(),
      type: z.literal('text'),
      description: z.string().optional(),
      data: z.string(),
    }),
    targetMarket: z.object({
      id: z.string(), 
      label: z.string(),
      type: z.literal('text'),
      description: z.string().optional(),
      data: z.string(),
    }),
    painPoints: z.object({
      id: z.string(),
      label: z.string(),
      type: z.literal('list'),
      description: z.string().optional(),
      data: z.array(z.string()),
    }),
    gains: z.object({
      id: z.string(),
      label: z.string(),
      type: z.literal('list'),
      description: z.string().optional(),
      data: z.array(z.string()),
    }),
    competitors: z.object({
      id: z.string(),
      label: z.string(),
      type: z.literal('text'),
      description: z.string().optional(),
      data: z.string(),
    }),
    positioning: 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 RequestValueStrategyInputSchema = BasePayloadSchema.extend({
  businessIdea: z.string(),
  targetMarket: z.string(),
  competitors: z.string().optional()
});

export type RequestValueStrategyInput = z.infer<typeof RequestValueStrategyInputSchema>;

Update the metadata/order.enum.ts file with the cost of the agent

// packages/core/src/orchestrator/metadata/order.enum.ts
export enum AgentCost {
    ValueStrategy = 50,
}

2.3 Add the Value Strategist module to the agent-plane

Create the following directory structure:

agent-plane/value-strategist/
├── adapters/
│   ├── primary/
│   │   └── create-value-strategy.adapter.ts
│   └── secondary/
│       ├── openai.adapter.ts
│       └── datastore.adapter.ts
├── metadata/
│   ├── value-strategist.schema.ts
│   └── value-strategist.prompt.ts
└── usecases/
    └── create-value-strategy.usecase.ts

Implement the metadata for the agent in metadata/value-strategist.prompt.ts

// packages/core/src/agent-plane/value-strategist/metadata/value-strategist.prompt.ts
export const valueStrategySystemPrompt = (input: RequestValueStrategyInput) => `
You are an expert value strategist.
Your task is to create a detailed one-page value specification based on the provided business idea, target market, and competitor information.
${JSON.stringify(input)}
Focus on providing actionable insights and strategic recommendations.
   For the valueProposition section, provide a clear and compelling statement of value.
   For the targetMarket section, analyze and segment the market.
   For the painPoints section, list key customer pain points.
   For the gains section, list key customer gains.
   For the competitors section, analyze the competitive landscape.
   For the positioning section, provide strategic positioning recommendations.
`;

Implement the primary adapter in adapters/primary/create-value-strategy.adapter.ts

// packages/core/src/agent-plane/value-strategist/adapters/primary/create-value-strategy.adapter.ts
import { SQSEvent, SQSRecord } from 'aws-lambda';
import { RequestValueStrategyInputSchema } from '@agent-plane/value-strategist/metadata/value-strategist.schema';
import { createValueStrategyUsecase } from '@agent-plane/value-strategist/usecases/create-value-strategy.usecase';

export const createValueStrategyAdapter = async (event: SQSEvent) => {
    console.info("--- Value 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 = RequestValueStrategyInputSchema.parse(JSON.parse(message.Message));
        return await createValueStrategyUsecase(order);
    }));

    return results;
};

Implement the usecase in usecases/create-value-strategy.usecase.ts

// packages/core/src/agent-plane/value-strategist/usecases/create-value-strategy.usecase.ts
import { Deliverable, DeliverableDTO, RequestValueStrategyInput } from '@agent-plane/value-strategist/metadata/value-strategist.schema'
import { runValueStrategy } from '@agent-plane/value-strategist/adapters/secondary/openai.adapter';
import { deliverableRepository } from '@agent-plane/value-strategist/adapters/secondary/datastore.adapter';
import { Message } from '@utils/metadata/message.schema';

export const createValueStrategyUsecase = async (input: RequestValueStrategyInput): Promise<Message> => {
  console.info("--- Creating Value Strategy via Usecase ---");

  try {
    const result = await runValueStrategy(input);
    const deliverable: DeliverableDTO = {
      userId: input.userId,
      orderId: input.orderId,
      deliverableId: input.deliverableId,
      deliverableName: input.deliverableName,
      agentId: input.agentId,
      ...result
    };
    await deliverableRepository.saveDeliverable(deliverable);

    return {
      message: "Value strategy created successfully"
    };

  } catch (error) {
    console.error('Error generating value strategy:', error);
    throw new Error('Failed to generate value strategy');
  }
};

Implement the secondary adapter in adapters/secondary/openai.adapter.ts

// packages/core/src/agent-plane/value-strategist/adapters/secondary/openai.adapter.ts
import OpenAI from "openai";
import { Deliverable, DeliverableSchema, RequestValueStrategyInput } from "@agent-plane/value-strategist/metadata/value-strategist.schema";
import { Resource } from "sst";
import { withRetry } from "@utils/tools/retry";
import { valueStrategySystemPrompt } from "../../metadata/value-strategist.prompt";
import { zodToJsonSchema } from "zod-to-json-schema";
import { zodResponseFormat } from "openai/helpers/zod";

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

export const createValueStrategy = async (input: RequestValueStrategyInput): Promise<Deliverable> => {
  console.info("--- Creating Value Strategy via Agent ---");
  try {
    // Create an Assistant
    const assistant = await client.beta.assistants.create({
      name: "Value Strategist",
      instructions: valueStrategySystemPrompt(input),
      model: "gpt-4",
      response_format: zodResponseFormat(DeliverableSchema, "deliverable"),
      tools: [{ type: "function", function: {
        name: "generateDeliverable",
        parameters: zodToJsonSchema(DeliverableSchema)
      }}]
    });

    // Create a Thread
    const thread = await client.beta.threads.create();

    // Run the Assistant and wait for completion
    const run = await client.beta.threads.runs.create(thread.id, {
      assistant_id: assistant.id
    });

    // Wait for completion with proper status handling
    const completedRun = await waitForRunCompletion(client, thread.id, run.id);
    
    // Get the messages
    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");
    }

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

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

    return validatedContent;
  } catch (error) {
    console.error('Error generating value 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 runValueStrategy = withRetry(createValueStrategy, {
  retries: 3,
  delay: 1000,
  onRetry: (error: Error) => console.warn('Retrying value strategy generation due to error:', error)
});

This completes the implementation of the Value Strategist agent. The agent will now:

  1. Accept user input through the UI (business idea, target market, and competitors)
  2. Validate and process the request through the API
  3. Generate a comprehensive value specification using OpenAI
  4. Store the deliverable in the database
  5. Return the result to the user

Remember to:

  • Test each component thoroughly
  • Handle errors appropriately
  • Follow the AMU pattern for clean architecture
  • Use proper typing and validation
  • Document your code
  • Add appropriate logging
  • Follow security best practices