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

# Quick Start Guide

> Get up and running with Struct APIs in minutes

## Welcome to Struct

This guide will help you create your first 3D simulation using Struct APIs. In just a few minutes, you'll be generating immersive simulations from simple text prompts.

## Step 1: Get Your API Key

1. **Sign up** at [https://api.vects.ai/auth/register](https://api.vects.ai/auth/register)
2. **Verify your email** and complete the onboarding process
3. **Generate an API key** from your dashboard
4. **Copy and save** your API key securely

<Warning>
  Keep your API key secure and never expose it in client-side code. Use environment variables or secure key management systems.
</Warning>

## Step 2: Create Your First Simulation

Let's create a simple urban intersection simulation:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X POST "https://api.vects.ai/api/v1/simulations/" \
    -H "Authorization: Api-Key YOUR_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "prompt": "Create a busy downtown intersection with pedestrians crossing, cars waiting at traffic lights, and a food truck on the corner"
    }'
  ```

  ```javascript JavaScript theme={null}
  const response = await fetch('https://api.vects.ai/api/v1/simulations/', {
    method: 'POST',
    headers: {
      'Authorization': 'Api-Key YOUR_API_KEY',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      prompt: "Create a busy downtown intersection with pedestrians crossing, cars waiting at traffic lights, and a food truck on the corner"
    })
  });

  const simulation = await response.json();
  console.log('Simulation ID:', simulation.simulation_id);
  ```

  ```python Python theme={null}
  import requests

  url = "https://api.vects.ai/api/v1/simulations/"
  headers = {
      "Authorization": "Api-Key YOUR_API_KEY",
      "Content-Type": "application/json"
  }
  data = {
      "prompt": "Create a busy downtown intersection with pedestrians crossing, cars waiting at traffic lights, and a food truck on the corner"
  }

  response = requests.post(url, headers=headers, json=data)
  simulation = response.json()
  print(f"Simulation ID: {simulation['simulation_id']}")
  ```
</CodeGroup>

**Response:**

```json theme={null}
{
  "simulation_id": "sim_abc123def456",
  "status": "queued",
  "created_at": "2024-01-15T10:30:00Z",
  "estimated_completion_time": "2024-01-15T10:35:00Z",
  "prompt": "Create a busy downtown intersection with pedestrians crossing, cars waiting at traffic lights, and a food truck on the corner"
}
```

## Step 3: Check Simulation Status

Monitor your simulation's progress:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://api.vects.ai/api/v1/simulations/sim_abc123def456/status/" \
    -H "Authorization: Api-Key YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  async function checkStatus(simulationId) {
    const response = await fetch(`https://api.vects.ai/api/v1/simulations/${simulationId}/status/`, {
      headers: {
        'Authorization': 'Api-Key YOUR_API_KEY'
      }
    });
    
    const status = await response.json();
    console.log(`Status: ${status.status} (${status.progress.percentage}%)`);
    return status;
  }

  // Poll every 10 seconds
  const pollStatus = setInterval(async () => {
    const status = await checkStatus('sim_abc123def456');
    if (status.status === 'completed') {
      clearInterval(pollStatus);
      console.log('Simulation complete!');
    }
  }, 10000);
  ```

  ```python Python theme={null}
  import time

  def check_status(simulation_id):
      url = f"https://api.vects.ai/api/v1/simulations/{simulation_id}/status/"
      headers = {"Authorization": "Api-Key YOUR_API_KEY"}
      
      response = requests.get(url, headers=headers)
      return response.json()

  # Poll until complete
  simulation_id = "sim_abc123def456"
  while True:
      status = check_status(simulation_id)
      print(f"Status: {status['status']} ({status['progress']['percentage']}%)")
      
      if status['status'] == 'completed':
          print("Simulation complete!")
          break
      
      time.sleep(10)
  ```
</CodeGroup>

## Step 4: Retrieve Your Results

Once complete, get your simulation data:

<CodeGroup>
  ```bash cURL theme={null}
  curl -X GET "https://api.vects.ai/api/v1/simulations/sim_abc123def456/" \
    -H "Authorization: Api-Key YOUR_API_KEY"
  ```

  ```javascript JavaScript theme={null}
  async function getResults(simulationId) {
    const response = await fetch(`https://api.vects.ai/api/v1/simulations/${simulationId}/`, {
      headers: {
        'Authorization': 'Api-Key YOUR_API_KEY'
      }
    });
    
    const results = await response.json();
    
    console.log(`Simulation: ${results.metadata.prompt}`);
    console.log(`Agents: ${results.actors.length}`);
    console.log(`Features: ${results.features.length}`);
    
    return results;
  }

  const results = await getResults('sim_abc123def456');
  ```

  ```python Python theme={null}
  def get_results(simulation_id):
      url = f"https://api.vects.ai/api/v1/simulations/{simulation_id}/"
      headers = {"Authorization": "Api-Key YOUR_API_KEY"}
      
      response = requests.get(url, headers=headers)
      return response.json()

  results = get_results("sim_abc123def456")
  print(f"Simulation: {results['metadata']['prompt']}")
  print(f"Agents: {len(results['actors'])}")
  print(f"Features: {len(results['features'])}")
  ```
</CodeGroup>

## Step 5: Try Risk Analysis

Add risk assessment to your simulation:

```bash theme={null}
curl -X POST "https://api.vects.ai/risk-assessment/" \
  -H "Authorization: Api-Key YOUR_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "routePoints": [
      {"lat": 37.7749, "lng": -122.4194},
      {"lat": 37.7849, "lng": -122.4094}
    ]
  }'
```

**Response:**

```json theme={null}
{
  "riskPoints": [
    {
      "lat": 37.7749,
      "lng": -122.4194,
      "weight": 0.2,
      "riskLevel": "low"
    },
    {
      "lat": 37.7849,
      "lng": -122.4094,
      "weight": 0.7,
      "riskLevel": "high"
    }
  ],
  "summary": {
    "overallRisk": "medium",
    "averageRisk": 0.45
  }
}
```

## Step 6: Explore Real-time MARL

Connect to the WebSocket for real-time urban mobility simulation:

```javascript theme={null}
const ws = new WebSocket('ws://api.vects.ai:8001/ws/marl_state');

ws.onopen = function() {
  console.log('Connected to MARL WebSocket');
  
  // Request initial agents
  ws.send(JSON.stringify({
    type: 'request_initial_agents',
    payload: {
      focus_latitude: 37.7749,
      focus_longitude: -122.4194
    }
  }));
};

ws.onmessage = function(event) {
  const message = JSON.parse(event.data);
  
  switch(message.type) {
    case 'add_agent':
      console.log('New agent:', message.payload.id);
      // Add agent to your 3D scene
      break;
    case 'initial_population_complete':
      console.log(`Loaded ${message.payload.count} agents`);
      break;
  }
};
```

## Common Use Cases

### Emergency Response Planning

```javascript theme={null}
const emergencySimulation = {
  prompt: "Simulate a building evacuation during a fire emergency with multiple exit routes and emergency responders",
  scenario_type: "emergency_response",
  settings: {
    max_agents: 300,
    simulation_duration: 600,
    environment_type: "indoor"
  }
};
```

### Urban Planning

```javascript theme={null}
const urbanPlanningSimulation = {
  prompt: "Model pedestrian and vehicle traffic around a new subway station entrance during rush hour",
  scenario_type: "urban_planning",
  settings: {
    max_agents: 800,
    simulation_duration: 3600,
    environment_type: "mixed"
  }
};
```

### Security Assessment

```javascript theme={null}
const securitySimulation = {
  prompt: "Analyze crowd flow and security coverage at a large outdoor event with multiple entry points",
  scenario_type: "security_assessment",
  settings: {
    max_agents: 1000,
    simulation_duration: 7200,
    environment_type: "outdoor"
  }
};
```

## Next Steps

<CardGroup cols={2}>
  <Card title="Authentication" icon="key" href="/authentication">
    Learn about API keys, tokens, and rate limits
  </Card>

  <Card title="Text to 3D Simulation" icon="cube" href="/api-reference/simulation/text-to-3d">
    Explore advanced simulation generation options
  </Card>

  <Card title="Risk Analysis" icon="shield-exclamation" href="/api-reference/risk/route-analysis">
    Add comprehensive risk assessment to your applications
  </Card>

  <Card title="MARL WebSocket" icon="bolt" href="/api-reference/marl/websocket-overview">
    Build real-time urban mobility applications
  </Card>
</CardGroup>

## Integration Examples

### React Application

```jsx theme={null}
import React, { useState, useEffect } from 'react';

function StructSimulation() {
  const [simulation, setSimulation] = useState(null);
  const [status, setStatus] = useState('idle');

  const createSimulation = async () => {
    setStatus('creating');
    
    const response = await fetch('https://api.vects.ai/api/v1/simulations/', {
      method: 'POST',
      headers: {
        'Authorization': `Api-Key ${process.env.REACT_APP_Struct_API_KEY}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        prompt: "Create a busy city intersection with traffic and pedestrians"
      })
    });
    
    const sim = await response.json();
    setSimulation(sim);
    setStatus('processing');
    
    // Poll for completion
    pollStatus(sim.simulation_id);
  };

  const pollStatus = async (simulationId) => {
    const response = await fetch(`https://api.vects.ai/api/v1/simulations/${simulationId}/status/`);
    const statusData = await response.json();
    
    if (statusData.status === 'completed') {
      setStatus('completed');
    } else {
      setTimeout(() => pollStatus(simulationId), 5000);
    }
  };

  return (
    <div>
      <h1>Struct Simulation</h1>
      <button onClick={createSimulation} disabled={status !== 'idle'}>
        Create Simulation
      </button>
      <p>Status: {status}</p>
      {simulation && <p>ID: {simulation.simulation_id}</p>}
    </div>
  );
}
```

### Unity C# Integration

```csharp theme={null}
using UnityEngine;
using System.Collections;
using UnityEngine.Networking;

public class StructIntegration : MonoBehaviour 
{
    private string apiKey = "YOUR_API_KEY";
    private string baseUrl = "https://api.vects.ai/api/v1";
    
    public void CreateSimulation() 
    {
        StartCoroutine(CreateSimulationCoroutine());
    }
    
    IEnumerator CreateSimulationCoroutine() 
    {
        string json = JsonUtility.ToJson(new {
            prompt = "Create a busy intersection with cars and pedestrians"
        });
        
        using (UnityWebRequest request = UnityWebRequest.Post($"{baseUrl}/simulations/", json, "application/json")) 
        {
            request.SetRequestHeader("Authorization", $"Api-Key {apiKey}");
            
            yield return request.SendWebRequest();
            
            if (request.result == UnityWebRequest.Result.Success) 
            {
                var response = JsonUtility.FromJson<SimulationResponse>(request.downloadHandler.text);
                Debug.Log($"Simulation created: {response.simulation_id}");
                
                StartCoroutine(PollStatus(response.simulation_id));
            }
        }
    }
}
```

## Troubleshooting

### Common Issues

**401 Unauthorized**

* Check that your API key is correct
* Ensure you're including the "Api-Key" prefix
* Verify your account is active

**429 Rate Limited**

* You've exceeded your plan's rate limits
* Wait before making more requests
* Consider upgrading your plan

**Simulation Taking Too Long**

* Complex prompts take longer to process
* Check the estimated completion time
* Use webhooks instead of polling for efficiency

### Getting Help

* **Documentation**: Browse our comprehensive API docs
* **Support**: Email [support@vects.ai](mailto:support@vects.ai)
* **Community**: Join our Discord community
* **Status**: Check api.vects.ai/status for service status

## What's Next?

You've successfully created your first Struct simulation! Here are some ideas for what to explore next:

1. **Experiment with different prompts** - Try emergency scenarios, urban planning, or security assessments
2. **Add risk analysis** - Enhance your simulations with comprehensive threat assessment
3. **Build real-time applications** - Use the MARL WebSocket for dynamic simulations
4. **Integrate with your stack** - Add Struct to your existing applications
5. **Explore advanced features** - Custom settings, webhooks, and export formats

Ready to build the future of spatial intelligence? Let's get started! 🚀
