# Quickstart

This guide walks through your first three Platform SDK calls: listing agents, fetching a service, and running a voice simulation session step by step.

## Prerequisites

{% hint style="info" %}
**Before You Begin**

1. [**Installed the SDK**](/developer-guide/platform-api/platform-sdk/installation.md) in your project.
2. [**Configured your credentials**](/developer-guide/platform-api/platform-sdk/configuration.md) with a valid API key and workspace ID.
   {% endhint %}

## Initialize the Client

```typescript
import 'dotenv/config'
import { AmigoClient } from '@amigo-ai/platform-sdk'

const client = new AmigoClient({
  apiKey: process.env.AMIGO_API_KEY!,
  workspaceId: process.env.AMIGO_WORKSPACE_ID!,
})
```

## Example 1: List Agents

Fetch all agents in your workspace:

```typescript
const { agents } = await client.agents.list()

for (const agent of agents) {
  console.log(`Agent: ${agent.name} (ID: ${agent.id})`)
  console.log(`  Latest version: ${agent.latest_version ?? 'none'}`)
  console.log(`  Updated: ${agent.updated_at}`)
}
```

Retrieve a specific agent's version to see its full configuration:

```typescript
const agentId = agents[0].id

const version = await client.agents.getVersion(agentId, 'latest')
console.log(`Persona: ${version.identity.persona}`)
console.log(`Background: ${version.background}`)
```

## Example 2: Inspect a Service

List services and inspect the voice configuration of the first one:

```typescript
const { services } = await client.services.list()
const service = services[0]

console.log(`Service: ${service.name}`)
console.log(`Channel: ${service.channel_type}`)
console.log(`Environment: ${service.environment}`)

// Check version sets
for (const [name, versionSet] of Object.entries(service.version_sets)) {
  console.log(`  Version set "${name}": agent v${versionSet.agent_version}`)
}
```

## Example 3: Run a Voice Simulation

Simulate a caller conversation to test your service behavior without making a real call:

```typescript
// Step 1: Start a simulation session
const { session_id, greeting } = await client.simulations.createSession({
  service_id: service.id,
  branch_name: 'release',
})

console.log(`Session started: ${session_id}`)
console.log(`Agent greeting: ${greeting}`)

// Step 2: Send a caller message and observe the agent response
const { observation, snapshot } = await client.simulations.step({
  session_id,
  caller_text: "Hi, I'd like to schedule an appointment",
})

console.log(`Agent response: ${observation.agent_response}`)
console.log(`Conversation state: ${snapshot.current_state}`)
console.log(`Is terminal: ${snapshot.is_terminal}`)

// Step 3: Continue the conversation
const { observation: obs2 } = await client.simulations.step({
  session_id,
  caller_text: 'Tomorrow at 2pm works for me',
})

console.log(`Agent: ${obs2.agent_response}`)

// Step 4: Delete the session when done
await client.simulations.deleteSession(session_id)
console.log('Session complete')
```

## Example 4: Pull Analytics

Check dashboard metrics for the last 7 days:

```typescript
const dashboard = await client.analytics.getDashboard({ days: 7 })

console.log(`Call volume: ${dashboard.call_volume.value}`)
console.log(`Avg quality: ${dashboard.avg_quality.value?.toFixed(1)}`)
console.log(`Escalation rate: ${(dashboard.escalation_rate.value! * 100).toFixed(1)}%`)

// Delta shows week-over-week change
if (dashboard.call_volume.delta_pct !== null) {
  const trend = dashboard.call_volume.delta_pct > 0 ? '▲' : '▼'
  console.log(`Volume trend: ${trend} ${Math.abs(dashboard.call_volume.delta_pct).toFixed(1)}%`)
}
```

## Example 5: Stream a Text Conversation Turn

Send a turn to a text conversation and render the agent's response token by token. The SDK negotiates `Accept: text/event-stream` on the REST turns endpoint and returns a `ReadableStream<Uint8Array>` that you parse with `eventsource-parser`. Every event is typed under the `TurnStreamEvent` discriminated union.

```typescript
import { EventSourceParserStream } from 'eventsource-parser/stream'
import type { TurnStreamEvent } from '@amigo-ai/platform-sdk'

const conversation = await client.conversations.create({ service_id: service.id })

const stream = await client.conversations.createTurnStream(conversation.id, {
  message: "I'd like to schedule a follow-up appointment",
})

const events = stream.pipeThrough(new TextDecoderStream()).pipeThrough(new EventSourceParserStream())

for await (const event of events) {
  const parsed = JSON.parse(event.data) as TurnStreamEvent
  switch (parsed.event) {
    case 'token':
      process.stdout.write(parsed.text)
      break
    case 'tool_call_started':
      console.log(`\n[tool: ${parsed.tool_name} started]`)
      break
    case 'tool_call_completed':
      console.log(`[tool: ${parsed.tool_name} ${parsed.succeeded ? 'ok' : 'failed'}]`)
      break
    case 'message':
      console.log(`\n[final: ${parsed.text}]`)
      break
    case 'done':
      console.log(`\n[done — ${parsed.turn_count} turns total]`)
      break
    case 'error':
      console.error(`\n[stream error: ${parsed.message}]`)
      break
  }
}
```

If the client disconnects mid-stream, the server still finishes the turn and persists the partial agent response. Resuming with `client.conversations.get(conversation.id)` returns the completed turn.

## Example 6: Open a Public Text-Session WebSocket

For interactive UIs, connect a bidirectional WebSocket to the workspace-scoped session-connect endpoint. The SDK builds the URL and provides the auth subprotocol; the API key is delivered via the `Sec-WebSocket-Protocol` header so it never appears in URLs or proxy logs.

```typescript
import { sessionConnectAuthProtocols } from '@amigo-ai/platform-sdk'

const url = client.conversations.sessionConnectUrl({
  serviceId: service.id,
  entityId: ENTITY_ID,
  // conversationId is optional — omit for a fresh session
})

const ws = new WebSocket(url, sessionConnectAuthProtocols(process.env.AMIGO_API_KEY!))

ws.addEventListener('message', (event) => {
  const frame = JSON.parse(event.data as string)
  switch (frame.type) {
    case 'session_started':
      console.log(`session ${frame.session_id} (conv ${frame.conversation_id})`)
      break
    case 'message':
      console.log(`agent: ${frame.text}`)
      break
    case 'tool_call_started':
      console.log(`[tool ${frame.tool_name} started]`)
      break
    case 'session_ended':
      console.log(`session ended: ${frame.reason}`)
      break
  }
})

ws.addEventListener('open', () => {
  ws.send(JSON.stringify({ type: 'message', text: 'Hello' }))
})
```

Available since `@amigo-ai/platform-sdk@0.20.0`. Earlier versions expose only the legacy `textStreamUrl()` helper that targets `/agent/text-stream` with the same wire protocol.

## Example 7: Look Up an Entity

Retrieve a patient or caller entity from the world model:

```typescript
const { entities } = await client.world.listEntities({ limit: 10 })

if (entities.length > 0) {
  const entity = entities[0]
  console.log(`Entity: ${entity.display_name ?? entity.entity_type}`)
  console.log(`Type: ${entity.entity_type}`)
  console.log(`Last seen: ${entity.last_event_at}`)
  console.log(`Event count: ${entity.event_count}`)
}
```

## Full Quickstart Script

Here is a complete runnable script combining all examples above:

```typescript
import 'dotenv/config'
import { AmigoClient } from '@amigo-ai/platform-sdk'

async function main() {
  const client = new AmigoClient({
    apiKey: process.env.AMIGO_API_KEY!,
    workspaceId: process.env.AMIGO_WORKSPACE_ID!,
  })

  // 1. List agents
  const { agents } = await client.agents.list()
  console.log(`\n=== Agents (${agents.length}) ===`)
  for (const agent of agents) {
    console.log(`  ${agent.name} (v${agent.latest_version ?? '?'})`)
  }

  // 2. Inspect first service
  const { services } = await client.services.list()
  if (services.length > 0) {
    const svc = services[0]
    console.log(`\n=== Service: ${svc.name} ===`)
    console.log(`  Channel: ${svc.channel_type}`)
    console.log(`  Agent: ${svc.agent_name}`)
  }

  // 3. Analytics dashboard
  const dashboard = await client.analytics.getDashboard({ days: 7 })
  console.log('\n=== Analytics (7d) ===')
  console.log(`  Calls: ${dashboard.call_volume.value ?? 0}`)
  console.log(`  Avg quality: ${dashboard.avg_quality.value?.toFixed(1) ?? 'N/A'}`)

  console.log('\nDone!')
}

main().catch(console.error)
```

## Next Steps

* [**Error Handling**](/developer-guide/platform-api/platform-sdk/error-handling.md)**.** Handle errors and edge cases.
* [**Agents**](/developer-guide/platform-api/platform-api/agents.md)**.** Deep dive into agent management.
* [**Voice Simulation**](broken://pages/R80ekvNoylly3ry9d82Q)**.** Full simulation coverage reference.
* [**Analytics & Observability**](/developer-guide/platform-api/platform-api/analytics.md)**.** Call analytics and quality metrics.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.amigo.ai/developer-guide/platform-api/platform-sdk/quickstart.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
