# Quick Start

Build your first MindedJS agent in minutes! We'll create a customer support agent that can process refunds.

## What You'll Build

A customer support agent for an ecommerce store:

* Greets customers and asks for order details
* Intelligently routes to refund processing when appropriate
* Processes refunds with business logic
* Maintains conversation state throughout

## Project Setup

First, create the necessary files in your project:

### 1. Agent Configuration

Create `minded.json` in your project root (see [Project Configuration](https://docs.minded.com/getting-started/project-configuration) for detailed documentation):

```json
{
  "flows": ["./flows"],
  "llm": {
    "name": "ChatOpenAI",
    "properties": {
      "model": "gpt-5.2"
    }
  }
}
```

### 2. Flow Definition

Create `flows/refundFlow.yaml`:

```yaml
name: 'Order Refund Flow'
nodes:
  - type: 'trigger'
    triggerType: 'manual'
    name: 'CLI Trigger'
  - type: 'promptNode'
    name: 'Support Agent'
    prompt: "Hello! I'm your customer support agent. I can help you with refunds. Please provide your name, order ID, and describe your issue."
  - type: 'tool'
    name: 'Process Refund'
    toolName: 'processRefund'
edges:
  - source: 'CLI Trigger'
    target: 'Support Agent'
    type: 'stepForward'
  - source: 'Support Agent'
    target: 'Process Refund'
    type: 'promptCondition'
    prompt: 'The user is asking for a refund and provided their order details'
```

### 3. Memory Schema

Create `agentMemorySchema.ts`:

```ts
import { z } from 'zod';

export default z.object({
  customerName: z.string().optional(),
  orderId: z.string().optional(),
  issue: z.string().optional(),
});
```

### 4. Tools

Create `tools/processRefund.ts`:

```ts
import { z } from 'zod';
import { Tool } from 'mindedjs/src/types/Tools.types';
import memorySchema from '../schema';

type Memory = z.infer<typeof memorySchema>;

const schema = z.object({
  orderId: z.string(),
  customerName: z.string(),
  reason: z.string(),
});

const processRefundTool: Tool<typeof schema, Memory> = {
  name: 'processRefund',
  description: 'Process a refund for the customer order',
  input: schema,
  execute: async ({ input, memory }) => {
    console.log('*Action: Processing refund*');
    console.log(`Refunding order ${input.orderId} for ${input.customerName}`);
    console.log(`Reason: ${input.reason}`);

    // Simulate refund processing
    const refundAmount = Math.floor(Math.random() * 100) + 20; // Random amount between $20-$120
    console.log(`Refund of $${memory.orderAmount} has been processed successfully!`);

    return {
      memory: {
        customerName: input.customerName,
        orderId: input.orderId,
        issue: `Refund processed - $${refundAmount}`,
      },
    };
  },
};

export default processRefundTool;
```

Create `tools/index.ts`:

```ts
import processRefundTool from './processRefund';

export default [processRefundTool];
```

### 5. Main Agent

Create `agent.ts`:

```ts
import { Agent } from 'mindedjs/src/agent';
import { HumanMessage } from '@langchain/core/messages';
import { events } from 'mindedjs/src/index';
import * as readline from 'readline';
import memorySchema from './schema';
import tools from './tools';
import config from './minded.json';

// 1. Create readline interface for interactive chat
const rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
});

// 2. Create the agent with config from minded.json
const agent = new Agent({
  memorySchema,
  config,
  tools,
});

// 3. Listen for AI messages
agent.on(events.AI_MESSAGE, async ({ message }) => {
  console.log('AI:', message);
  promptUser(); // Continue the conversation
});

// 4. Handle trigger events
agent.on(events.TRIGGER_EVENT, async ({ triggerName, triggerBody }) => {
  if (triggerName === 'CLI Trigger') {
    return {
      memory: {},
      messages: [new HumanMessage(triggerBody)],
    };
  }
});

// 5. Function to prompt user for input
const promptUser = () => {
  rl.question('You: ', async (input) => {
    if (input.toLowerCase() === 'exit' || input.toLowerCase() === 'quit') {
      console.log('Goodbye!');
      rl.close();
      return;
    }

    console.log(); // Add spacing for readability

    // Send user message to agent
    await agent.invoke({
      triggerBody: input,
      triggerName: 'CLI Trigger',
    });
  });
};

// 6. Start the interactive session
console.log('🤖 Customer Support Agent is ready!');
console.log('Type your message below (or "exit" to quit):\n');
promptUser();
```

## Project Structure

Your project should look like this:

```
your-project/
├── minded.json          # Agent configuration
├── schema.ts           # Memory schema definition
├── agent.ts            # Main agent file
├── flows/              # Flow definitions
│   └── refundFlow.yaml  # Individual flow files
└── tools/              # Tools directory
    ├── processRefund.ts # Refund processing tool
    └── index.ts        # Export your tools
```

## Run Your Agent

Start the interactive chat session:

```bash
npx ts-node agent.ts
```

This will start an interactive conversation where you can chat with your agent:

```
🤖 Customer Support Agent is ready!
Type your message below (or "exit" to quit):

You: Hi, I want to refund my order #1234. I received the wrong item.

AI: Hello! I'm your customer support agent. I can help you with refunds. Please provide your name, order ID, and describe your issue.

You: My name is John Smith, order ID is 1234, and I received the wrong size shoes.

*Action: Processing refund*
Refunding order 1234 for John Smith
Reason: received the wrong size shoes
Refund of $87 has been processed successfully!

You: Thank you!

AI: You're welcome! Your refund has been processed successfully. Is there anything else I can help you with?

You: exit
Goodbye!
```

**Tips:**

* Type `exit` or `quit` to end the conversation
* Each message maintains conversation context and memory
* The agent will intelligently route to refund processing when appropriate

## What Happens

1. **Trigger Activation**: The manual trigger receives your input message
2. **Support Agent**: The prompt node greets the customer and asks for details
3. **Intelligent Routing**: If the customer mentions refunds and provides order details, the flow routes to the refund tool
4. **Refund Processing**: The tool processes the refund and updates memory
5. **State Management**: Memory persists customer information throughout the conversation

## Next Steps

Now that you have a working agent, explore:

* [**Core Concepts**](https://docs.minded.com/low-code-editor/flows) - Understand how flows, nodes, and edges work
* [**Node Types**](https://docs.minded.com/low-code-editor/nodes) - Learn about all available node types
* [**Edge Types**](https://docs.minded.com/low-code-editor/edges) - Learn about all available edge types
* [**Tools**](https://docs.minded.com/low-code-editor/tools) - Learn about all available tools
