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

# Executing Prompts

> Learn how to execute LLM prompts using the Switchport Go SDK

## Basic Usage

Execute a prompt using its key:

```go theme={null}
package main

import (
	"fmt"
	"log"

	"github.com/switchport-ai/switchport-go/switchport"
)

func main() {
	client, err := switchport.NewClient("")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	response, err := client.Prompts.Execute(
		"welcome-message",
		nil, // no subject
		nil, // no variables
	)
	if err != nil {
		log.Fatalf("Failed to execute prompt: %v", err)
	}

	fmt.Println(response.Text)
}
```

## Using Variables

Pass dynamic variables to your prompts:

```go theme={null}
response, err := client.Prompts.Execute(
	"welcome-message",
	nil, // no subject
	map[string]interface{}{
		"name":    "Alice",
		"product": "Pro Plan",
	},
)
if err != nil {
	log.Fatalf("Failed to execute prompt: %v", err)
}

fmt.Println(response.Text)
```

Your prompt template in the dashboard:

```
Write a friendly welcome message for {{name}} who just purchased {{product}}.
```

## Using Subject for A/B Testing

Provide subject to enable deterministic A/B testing:

```go theme={null}
response, err := client.Prompts.Execute(
	"product-pitch",
	map[string]interface{}{"user_id": "user_123"},
	map[string]interface{}{"product": "Enterprise Plan"},
)
if err != nil {
	log.Fatalf("Failed to execute prompt: %v", err)
}

fmt.Printf("Version: %s\n", response.VersionName)
```

<Info>
  The same subject always gets the same version. This ensures users have a consistent experience.
</Info>

## Subject Types

Subject can be either a string or a map:

<CodeGroup>
  ```go String Subject theme={null}
  response, err := client.Prompts.Execute(
  	"greeting",
  	"user_123", // string subject
  	nil,
  )
  ```

  ```go Map Subject theme={null}
  response, err := client.Prompts.Execute(
  	"greeting",
  	map[string]interface{}{
  		"user_id": "user_123",
  		"tier":    "premium",
  		"region":  "us-west",
  	},
  	nil,
  )
  ```
</CodeGroup>

## Response Object

The `Execute` method returns a `PromptResponse` struct with the following fields:

```go theme={null}
response, err := client.Prompts.Execute(
	"welcome-message",
	nil,
	map[string]interface{}{"name": "Alice"},
)
if err != nil {
	log.Fatalf("Failed to execute prompt: %v", err)
}

// Generated text from the LLM
fmt.Println(response.Text)

// Model that was used
fmt.Println(response.Model) // e.g., "gpt-5"

// Version that was selected
fmt.Println(response.VersionName) // e.g., "v1"
fmt.Println(response.VersionID)   // e.g., "ver_abc123"

// Unique request identifier
fmt.Println(response.RequestID) // e.g., "req_xyz789"
```

### Response Fields

| Field            | Type                     | Description                                                  |
| ---------------- | ------------------------ | ------------------------------------------------------------ |
| `Text`           | `string`                 | The generated text from the LLM                              |
| `Model`          | `string`                 | The model used (e.g., `gpt-5`, `claude-3-5-sonnet-20241022`) |
| `VersionName`    | `string`                 | Human-readable version name                                  |
| `VersionID`      | `string`                 | Unique version identifier                                    |
| `PromptConfigID` | `string`                 | Unique prompt config identifier                              |
| `RequestID`      | `string`                 | Unique request identifier                                    |
| `Metadata`       | `map[string]interface{}` | Additional metadata                                          |

## Error Handling

Handle common errors when executing prompts:

```go theme={null}
package main

import (
	"errors"
	"log"

	"github.com/switchport-ai/switchport-go/switchport"
)

func main() {
	client, err := switchport.NewClient("")
	if err != nil {
		log.Fatalf("Failed to create client: %v", err)
	}

	response, err := client.Prompts.Execute(
		"my-prompt",
		nil,
		map[string]interface{}{"name": "Alice"},
	)
	if err != nil {
		var promptNotFound *switchport.PromptNotFoundError
		var authErr *switchport.AuthenticationError
		var apiErr *switchport.APIError

		switch {
		case errors.As(err, &promptNotFound):
			log.Println("Prompt not found - check your prompt key")
		case errors.As(err, &authErr):
			log.Println("Authentication failed - check your API key")
		case errors.As(err, &apiErr):
			log.Printf("API error (status %d): %v", apiErr.StatusCode, apiErr)
		default:
			log.Printf("Unknown error: %v", err)
		}
		return
	}

	log.Println(response.Text)
}
```

## Common Patterns

### Pattern 1: Dynamic Email Generation

```go theme={null}
func sendWelcomeEmail(user User) error {
	client, err := switchport.NewClient("")
	if err != nil {
		return err
	}

	response, err := client.Prompts.Execute(
		"welcome-email",
		map[string]interface{}{"user_id": user.ID},
		map[string]interface{}{
			"name":  user.Name,
			"email": user.Email,
		},
	)
	if err != nil {
		return err
	}

	return sendEmail(user.Email, response.Text)
}
```

### Pattern 2: Chatbot Responses

```go theme={null}
func getBotResponse(userID, userMessage string) (string, error) {
	client, err := switchport.NewClient("")
	if err != nil {
		return "", err
	}

	history, err := getHistory(userID)
	if err != nil {
		return "", err
	}

	response, err := client.Prompts.Execute(
		"support-bot",
		map[string]interface{}{"user_id": userID},
		map[string]interface{}{
			"user_message":         userMessage,
			"conversation_history": history,
		},
	)
	if err != nil {
		return "", err
	}

	return response.Text, nil
}
```

### Pattern 3: Content Generation

```go theme={null}
func generateProductDescription(productID string, userSegment string) (string, error) {
	client, err := switchport.NewClient("")
	if err != nil {
		return "", err
	}

	product, err := getProduct(productID)
	if err != nil {
		return "", err
	}

	response, err := client.Prompts.Execute(
		"product-description",
		map[string]interface{}{"segment": userSegment},
		map[string]interface{}{
			"product_name": product.Name,
			"features":     product.Features,
			"price":        product.Price,
		},
	)
	if err != nil {
		return "", err
	}

	return response.Text, nil
}
```

### Pattern 4: Fallback Handling

```go theme={null}
func getAIResponse(promptKey string, variables map[string]interface{}) (string, error) {
	client, err := switchport.NewClient("")
	if err != nil {
		// Fallback to default if client creation fails
		return getDefaultResponse(promptKey, variables)
	}

	response, err := client.Prompts.Execute(promptKey, nil, variables)
	if err != nil {
		var apiErr *switchport.APIError
		if errors.As(err, &apiErr) {
			// Fallback to default template if API fails
			return getDefaultResponse(promptKey, variables)
		}
		return "", err
	}

	return response.Text, nil
}

func getDefaultResponse(promptKey string, variables map[string]interface{}) (string, error) {
	// Return a static template or cached response
	return "Default response", nil
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Always use subject for A/B testing">
    If you want to track metrics or run A/B tests, always provide subject when executing prompts.
  </Accordion>

  <Accordion title="Use consistent subject">
    Use the same subject (e.g., user ID) across prompt executions and metric recording for the same subject or session.
  </Accordion>

  <Accordion title="Handle errors gracefully">
    Always implement error handling with fallback behavior to ensure your application continues working even if the API fails.
  </Accordion>

  <Accordion title="Use type-safe variables">
    While variables accept `map[string]interface{}`, consider wrapping in helper functions for type safety.
  </Accordion>

  <Accordion title="Cache responses when appropriate">
    For expensive or frequently-used prompts, consider caching responses to reduce API calls and latency.
  </Accordion>

  <Accordion title="Log request IDs">
    Store `RequestID` values for debugging and support purposes.
  </Accordion>

  <Accordion title="Use defer for cleanup">
    Use Go's `defer` keyword for any cleanup operations needed after API calls.
  </Accordion>
</AccordionGroup>

## Next Steps

<Columns cols={2}>
  <Card title="Recording Metrics" icon="chart-line" href="/sdk/go/metrics">
    Learn how to track metrics for your prompts
  </Card>

  <Card title="A/B Testing" icon="flask" href="/sdk/go/ab-testing">
    Set up A/B tests with multiple versions
  </Card>
</Columns>
