> ## Documentation Index
> Fetch the complete documentation index at: https://docs.greenflash.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Business Events (TypeScript)

> System prompt for coding agents to add business event tracking to an existing TypeScript SDK integration. Copy and paste the content of this page into your coding assistant.

export const CopyAllButton = ({content, label = 'Copy Page'}) => {
  const [copied, setCopied] = React.useState(false);
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(content);
      setCopied(true);
      setTimeout(() => setCopied(false), 3000);
    } catch (err) {
      console.error('Failed to copy content:', err);
      alert('Failed to copy content. Please try selecting and copying manually.');
    }
  };
  return <div className="copy-all-container">
      <div className="copy-all-content">
        <div className="copy-all-title">Copy Integration Instructions</div>
        <div className="copy-all-description">
          Click to copy the entire page content to paste into your AI coding
          assistant
        </div>
      </div>
      <button className={`copy-all-button${copied ? ' copied' : ''}`} onClick={handleCopy} type="button">
        {copied ? 'Page Copied' : label}
      </button>
    </div>;
};

<Tip>
  **Using a Skills-compatible agent like Claude Code?** The [Greenflash agent skill](/features/agent-skill) handles this automatically. Run `/greenflash-onboard-events` instead of copying this prompt.
</Tip>

export const pageContent = `# Add Business Event Tracking to Our Greenflash Integration

You are a **coding agent** tasked with extending our existing Greenflash TypeScript SDK integration to track **business events**. We already have message logging working. Your goal is to **add event tracking** so that Greenflash can connect AI interactions to real business outcomes like conversions, upgrades, and churn.

---

## High-Level Objective

Extend the current implementation to:

1. **Track business events** that represent meaningful user milestones
2. **Link events to conversations** when the outcome relates to an AI interaction
3. **Assign influence and value** to quantify the business impact
4. **Use the correct TypeScript SDK syntax**

> **Reference:** The full documentation for the Events API is available at: https://docs.greenflash.ai/features/events

---

## Why Track Events?

Events close the loop between AI interactions and business outcomes. While Greenflash already analyzes conversation quality and sentiment, events provide the ground truth:

- **Attribute Success:** Link specific AI responses directly to business outcomes like upgrades or purchases
- **Validate Quality:** Confirm heuristic signals (like sentiment) with tangible outcome data
- **Deepen Insights:** Train Greenflash to identify conversation patterns that drive real-world results

---

## When to Send Events

Capture moments that matter. Send an event whenever a user reaches a milestone that represents value creation or loss.

### Positive Indicators (Success Signals)

- \\\`signup_completed\\\`
- \\\`trial_started\\\`
- \\\`task_success\\\`
- \\\`upgrade_purchased\\\`
- \\\`meeting_booked\\\`
- \\\`lead_converted\\\`

### Negative Indicators (Friction/Churn Signals)

- \\\`cancellation_requested\\\`
- \\\`error_encountered\\\`
- \\\`workflow_abandoned\\\`
- \\\`refund_requested\\\`

### Contextual Indicators (Usage Context)

- \\\`feature_viewed\\\`
- \\\`step_completed\\\`
- \\\`usage_logged\\\`

---

## Core Event Fields

| Field | Type | Required | Description |
|-------|------|----------|-------------|
| \\\`eventType\\\` | string | Yes | The name of the event (e.g., \\\`upgrade\\\`, \\\`cancellation_requested\\\`) |
| \\\`productId\\\` | uuid | Yes | Your Greenflash Product ID |
| \\\`conversationId\\\` | uuid | No | Link to the conversation that influenced this outcome |
| \\\`influence\\\` | enum | No | \\\`positive\\\`, \\\`negative\\\`, or \\\`neutral\\\` (defaults to \\\`neutral\\\`) |
| \\\`value\\\` | string | Yes | The measurable value (e.g., \\\`"149.00"\\\`) |
| \\\`valueType\\\` | string | No | The type of value (e.g., \\\`currency\\\`, \\\`count\\\`) |
| \\\`properties\\\` | object | No | Additional context as key-value pairs |
| \\\`insertId\\\` | string | No | Unique ID for deduplication |

---

## Basic Event Tracking

### Fire-and-Forget (Recommended)

\\\`\\\`\\\`typescript
// Track a successful upgrade after a support conversation
client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: conversationId,  // Link to the AI interaction
  influence: "positive",
  value: "149.00",
  valueType: "currency",
  properties: {
    plan: "pro",
    billingCycle: "annual",
  },
}).catch(err => console.error('Greenflash event error:', err));
\\\`\\\`\\\`

### With Await (If Needed)

\\\`\\\`\\\`typescript
// If you need to wait for confirmation
await client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: conversationId,
  influence: "positive",
  value: "149.00",
  valueType: "currency",
  properties: {
    plan: "pro",
    billingCycle: "annual",
  },
});
\\\`\\\`\\\`

---

## Event Examples by Use Case

### Customer Support: Post-Chat Upgrade

\\\`\\\`\\\`typescript
// User upgraded to Pro after a helpful support chat
client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: supportConversationId,
  influence: "positive",
  value: "149.00",
  valueType: "currency",
  properties: {
    plan: "pro",
    billingCycle: "annual",
    previousPlan: "free",
  },
}).catch(err => console.error('Greenflash event error:', err));
\\\`\\\`\\\`

### Customer Support: Cancellation Request

\\\`\\\`\\\`typescript
// User requested cancellation during a support chat
client.events.create({
  eventType: "cancellation_requested",
  productId: productId,
  conversationId: supportConversationId,
  influence: "negative",
  value: "49.00",
  valueType: "currency",
  properties: {
    reason: "too_expensive",
    plan: "starter",
    monthsSubscribed: 3,
  },
}).catch(err => console.error('Greenflash event error:', err));
\\\`\\\`\\\`

### Sales: Meeting Booked

\\\`\\\`\\\`typescript
// AI-assisted outreach led to a booked meeting
client.events.create({
  eventType: "meeting_booked",
  productId: productId,
  conversationId: outreachConversationId,
  influence: "positive",
  value: "50000",
  valueType: "currency",
  properties: {
    pipelineStage: "qualification",
    engagementTouches: 5,
    daysSinceFirstTouch: 7,
  },
}).catch(err => console.error('Greenflash event error:', err));
\\\`\\\`\\\`

### Workflow: Task Completed Successfully

\\\`\\\`\\\`typescript
// AI-powered workflow completed a task
client.events.create({
  eventType: "task_success",
  productId: productId,
  conversationId: workflowSessionId,
  influence: "positive",
  value: "1500",
  valueType: "numeric",
  properties: {
    taskType: "data_extraction",
    recordsProcessed: 1500,
    timeSavedMinutes: 45,
  },
}).catch(err => console.error('Greenflash event error:', err));
\\\`\\\`\\\`

### Workflow: Error Encountered

\\\`\\\`\\\`typescript
// AI workflow encountered an error
client.events.create({
  eventType: "error_encountered",
  productId: productId,
  conversationId: workflowSessionId,
  influence: "negative",
  value: "1",
  valueType: "numeric",
  properties: {
    errorType: "validation_failure",
    errorMessage: "Invalid date format in row 42",
    recordsAffected: 1,
  },
}).catch(err => console.error('Greenflash event error:', err));
\\\`\\\`\\\`

---

## Linking Events to Conversations

The \\\`conversationId\\\` field is crucial for connecting business outcomes to AI interactions. Always include it when:

- The event happened during an AI session
- The event happened shortly after an AI interaction
- There's a clear causal relationship between the conversation and the outcome

\\\`\\\`\\\`typescript
// Store the conversation ID from your message logging
const conversationId = response.conversationId;

// Later, when a business event occurs...
client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: conversationId,  // Links this outcome to the AI interaction
  influence: "positive",
  value: "149.00",
  valueType: "currency",
}).catch(err => console.error('Greenflash event error:', err));
\\\`\\\`\\\`

---

## Sampling for High-Volume Events

For high-volume applications, use sampling to control ingestion:

\\\`\\\`\\\`typescript
// Sample 10% of page view events
client.events.create({
  eventType: "feature_viewed",
  productId: productId,
  sampleRate: 0.1,  // 10% sampling
  value: "dashboard",
  valueType: "text",
  properties: {
    feature: "dashboard",
  },
}).catch(err => console.error('Greenflash event error:', err));

// Always capture critical events
client.events.create({
  eventType: "upgrade",
  productId: productId,
  forceSample: true,  // Never drop this event
  influence: "positive",
  value: "149.00",
  valueType: "currency",
}).catch(err => console.error('Greenflash event error:', err));
\\\`\\\`\\\`

---

## Idempotency for Reliable Event Tracking

Use \\\`insertId\\\` to prevent duplicate events when retrying failed requests:

\\\`\\\`\\\`typescript
import { randomUUID } from 'crypto';

// Generate a unique ID for this event (store it if you need to retry)
const eventInsertId = randomUUID();

client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: conversationId,
  influence: "positive",
  value: "149.00",
  valueType: "currency",
  insertId: eventInsertId,  // Same ID = same event (no duplicates)
}).catch(err => console.error('Greenflash event error:', err));
\\\`\\\`\\\`

> **Best Practice:** For critical events like purchases, generate the \\\`insertId\\\` before attempting the request and persist it. If the request fails, retry with the same \\\`insertId\\\` to guarantee exactly-once delivery.

---

## Fire-and-Forget Pattern

For event tracking, you typically don't want to block your application flow. Use fire-and-forget by not awaiting the promise:

\\\`\\\`\\\`typescript
// Fire-and-forget: don't await, just add .catch() to handle errors
client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: conversationId,
  influence: "positive",
  value: "149.00",
  valueType: "currency",
}).catch(err => console.error('Greenflash event error:', err));
\\\`\\\`\\\`

> **Note:** The \\\`.catch()\\\` is recommended to prevent unhandled promise rejections from crashing your app, but the event call runs in the background without blocking.

---

## Integration Checklist

Your code should:

1. **Identify key business milestones** in our application (upgrades, cancellations, task completions, etc.)
2. **Add event tracking** at each milestone using \\\`client.events.create(...)\\\`
3. **Link events to conversations** by passing \\\`conversationId\\\` when relevant
4. **Set appropriate influence** (\\\`positive\\\`, \\\`negative\\\`, \\\`neutral\\\`)
5. **Include value and valueType** for revenue-impacting events
6. **Add useful properties** for deeper analysis
7. **Use fire-and-forget** (no \\\`await\\\`) with \\\`.catch()\\\` to avoid blocking

---

## What You Must Deliver

1. **Event tracking** at key business milestones
2. **Proper conversation linking** where applicable
3. **Correct influence assignment** (positive/negative/neutral)
4. **Value tracking** for revenue-related events
5. **No disruption** to existing message logging behavior

This will enable Greenflash to connect AI interactions to real business outcomes, validating conversation quality with tangible results.`;

<CopyAllButton content={pageContent} />

# Add Business Event Tracking to Our Greenflash Integration

You are a **coding agent** tasked with extending our existing Greenflash TypeScript SDK integration to track **business events**. We already have message logging working. Your goal is to **add event tracking** so that Greenflash can connect AI interactions to real business outcomes like conversions, upgrades, and churn.

***

## High-Level Objective

Extend the current implementation to:

1. **Track business events** that represent meaningful user milestones
2. **Link events to conversations** when the outcome relates to an AI interaction
3. **Assign influence and value** to quantify the business impact
4. **Use the correct TypeScript SDK syntax**

> **Reference:** The full documentation for the Events API is available at: [https://docs.greenflash.ai/features/events](https://docs.greenflash.ai/features/events)

***

## Why Track Events?

Events close the loop between AI interactions and business outcomes. While Greenflash already analyzes conversation quality and sentiment, events provide the ground truth:

* **Attribute Success:** Link specific AI responses directly to business outcomes like upgrades or purchases
* **Validate Quality:** Confirm heuristic signals (like sentiment) with tangible outcome data
* **Deepen Insights:** Train Greenflash to identify conversation patterns that drive real-world results

***

## When to Send Events

Capture moments that matter. Send an event whenever a user reaches a milestone that represents value creation or loss.

### Positive Indicators (Success Signals)

* `signup_completed`
* `trial_started`
* `task_success`
* `upgrade_purchased`
* `meeting_booked`
* `lead_converted`

### Negative Indicators (Friction/Churn Signals)

* `cancellation_requested`
* `error_encountered`
* `workflow_abandoned`
* `refund_requested`

### Contextual Indicators (Usage Context)

* `feature_viewed`
* `step_completed`
* `usage_logged`

***

## Core Event Fields

| Field            | Type   | Required | Description                                                       |
| ---------------- | ------ | -------- | ----------------------------------------------------------------- |
| `eventType`      | string | Yes      | The name of the event (e.g., `upgrade`, `cancellation_requested`) |
| `productId`      | uuid   | Yes      | Your Greenflash Product ID                                        |
| `conversationId` | uuid   | No       | Link to the conversation that influenced this outcome             |
| `influence`      | enum   | No       | `positive`, `negative`, or `neutral` (defaults to `neutral`)      |
| `value`          | string | Yes      | The measurable value (e.g., `"149.00"`)                           |
| `valueType`      | string | No       | The type of value (e.g., `currency`, `count`)                     |
| `properties`     | object | No       | Additional context as key-value pairs                             |
| `insertId`       | string | No       | Unique ID for deduplication                                       |

***

## Basic Event Tracking

### Fire-and-Forget (Recommended)

```typescript theme={"theme":{"light":"github-light","dark":"vesper"}}
// Track a successful upgrade after a support conversation
client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: conversationId,  // Link to the AI interaction
  influence: "positive",
  value: "149.00",
  valueType: "currency",
  properties: {
    plan: "pro",
    billingCycle: "annual",
  },
}).catch(err => console.error('Greenflash event error:', err));
```

### With Await (If Needed)

```typescript theme={"theme":{"light":"github-light","dark":"vesper"}}
// If you need to wait for confirmation
await client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: conversationId,
  influence: "positive",
  value: "149.00",
  valueType: "currency",
  properties: {
    plan: "pro",
    billingCycle: "annual",
  },
});
```

***

## Event Examples by Use Case

### Customer Support: Post-Chat Upgrade

```typescript theme={"theme":{"light":"github-light","dark":"vesper"}}
// User upgraded to Pro after a helpful support chat
client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: supportConversationId,
  influence: "positive",
  value: "149.00",
  valueType: "currency",
  properties: {
    plan: "pro",
    billingCycle: "annual",
    previousPlan: "free",
  },
}).catch(err => console.error('Greenflash event error:', err));
```

### Customer Support: Cancellation Request

```typescript theme={"theme":{"light":"github-light","dark":"vesper"}}
// User requested cancellation during a support chat
client.events.create({
  eventType: "cancellation_requested",
  productId: productId,
  conversationId: supportConversationId,
  influence: "negative",
  value: "49.00",
  valueType: "currency",
  properties: {
    reason: "too_expensive",
    plan: "starter",
    monthsSubscribed: 3,
  },
}).catch(err => console.error('Greenflash event error:', err));
```

### Sales: Meeting Booked

```typescript theme={"theme":{"light":"github-light","dark":"vesper"}}
// AI-assisted outreach led to a booked meeting
client.events.create({
  eventType: "meeting_booked",
  productId: productId,
  conversationId: outreachConversationId,
  influence: "positive",
  value: "50000",
  valueType: "currency",
  properties: {
    pipelineStage: "qualification",
    engagementTouches: 5,
    daysSinceFirstTouch: 7,
  },
}).catch(err => console.error('Greenflash event error:', err));
```

### Workflow: Task Completed Successfully

```typescript theme={"theme":{"light":"github-light","dark":"vesper"}}
// AI-powered workflow completed a task
client.events.create({
  eventType: "task_success",
  productId: productId,
  conversationId: workflowSessionId,
  influence: "positive",
  value: "1500",
  valueType: "numeric",
  properties: {
    taskType: "data_extraction",
    recordsProcessed: 1500,
    timeSavedMinutes: 45,
  },
}).catch(err => console.error('Greenflash event error:', err));
```

### Workflow: Error Encountered

```typescript theme={"theme":{"light":"github-light","dark":"vesper"}}
// AI workflow encountered an error
client.events.create({
  eventType: "error_encountered",
  productId: productId,
  conversationId: workflowSessionId,
  influence: "negative",
  value: "1",
  valueType: "numeric",
  properties: {
    errorType: "validation_failure",
    errorMessage: "Invalid date format in row 42",
    recordsAffected: 1,
  },
}).catch(err => console.error('Greenflash event error:', err));
```

***

## Linking Events to Conversations

The `conversationId` field is crucial for connecting business outcomes to AI interactions. Always include it when:

* The event happened during an AI session
* The event happened shortly after an AI interaction
* There's a clear causal relationship between the conversation and the outcome

```typescript theme={"theme":{"light":"github-light","dark":"vesper"}}
// Store the conversation ID from your message logging
const conversationId = response.conversationId;

// Later, when a business event occurs...
client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: conversationId,  // Links this outcome to the AI interaction
  influence: "positive",
  value: "149.00",
  valueType: "currency",
}).catch(err => console.error('Greenflash event error:', err));
```

***

## Sampling for High-Volume Events

For high-volume applications, use sampling to control ingestion:

```typescript theme={"theme":{"light":"github-light","dark":"vesper"}}
// Sample 10% of page view events
client.events.create({
  eventType: "feature_viewed",
  productId: productId,
  sampleRate: 0.1,  // 10% sampling
  value: "dashboard",
  valueType: "text",
  properties: {
    feature: "dashboard",
  },
}).catch(err => console.error('Greenflash event error:', err));

// Always capture critical events
client.events.create({
  eventType: "upgrade",
  productId: productId,
  forceSample: true,  // Never drop this event
  influence: "positive",
  value: "149.00",
  valueType: "currency",
}).catch(err => console.error('Greenflash event error:', err));
```

***

## Idempotency for Reliable Event Tracking

Use `insertId` to prevent duplicate events when retrying failed requests:

```typescript theme={"theme":{"light":"github-light","dark":"vesper"}}
import { randomUUID } from 'crypto';

// Generate a unique ID for this event (store it if you need to retry)
const eventInsertId = randomUUID();

client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: conversationId,
  influence: "positive",
  value: "149.00",
  valueType: "currency",
  insertId: eventInsertId,  // Same ID = same event (no duplicates)
}).catch(err => console.error('Greenflash event error:', err));
```

> **Best Practice:** For critical events like purchases, generate the `insertId` before attempting the request and persist it. If the request fails, retry with the same `insertId` to guarantee exactly-once delivery.

***

## Fire-and-Forget Pattern

For event tracking, you typically don't want to block your application flow. Use fire-and-forget by not awaiting the promise:

```typescript theme={"theme":{"light":"github-light","dark":"vesper"}}
// Fire-and-forget: don't await, just add .catch() to handle errors
client.events.create({
  eventType: "upgrade",
  productId: productId,
  conversationId: conversationId,
  influence: "positive",
  value: "149.00",
  valueType: "currency",
}).catch(err => console.error('Greenflash event error:', err));
```

> **Note:** The `.catch()` is recommended to prevent unhandled promise rejections from crashing your app, but the event call runs in the background without blocking.

***

## Integration Checklist

Your code should:

1. **Identify key business milestones** in our application (upgrades, cancellations, task completions, etc.)
2. **Add event tracking** at each milestone using `client.events.create(...)`
3. **Link events to conversations** by passing `conversationId` when relevant
4. **Set appropriate influence** (`positive`, `negative`, `neutral`)
5. **Include value and valueType** for revenue-impacting events
6. **Add useful properties** for deeper analysis
7. **Use fire-and-forget** (no `await`) with `.catch()` to avoid blocking

***

## What You Must Deliver

1. **Event tracking** at key business milestones
2. **Proper conversation linking** where applicable
3. **Correct influence assignment** (positive/negative/neutral)
4. **Value tracking** for revenue-related events
5. **No disruption** to existing message logging behavior

This will enable Greenflash to connect AI interactions to real business outcomes, validating conversation quality with tangible results.
