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

# Prompt Management

> Learn how to retrieve and use tested prompts from the Maxim platform for your production workflows

## How to manage prompts?

After testing and perfecting your prompts, you can query and use them in your production systems. This guide shows how to retrieve prompts from the Maxim platform and integrate them into your applications.

## Prerequisites

To query prompts, you need to:

1. **Enable prompt management** in your Maxim SDK configuration
2. **Have deployed prompts** on the Maxim platform with deployment rules

## Setup

Initialize the Maxim SDK with prompt management enabled:

<CodeGroup>
  ```python Python theme={null}
  from maxim import Maxim
  from maxim.models import QueryBuilder

  # Initialize Maxim with prompt management enabled

  maxim = Maxim(
      {
          "api_key": "your-maxim-api-key",
          "prompt_management": True,  # Enable prompt management
      }
  )
  ```

  ```typescript JS/TS theme={null}
  import { Maxim, QueryBuilder } from '@maximai/maxim-js';

  // Initialize Maxim with prompt management enabled
  const maxim = new Maxim({
    apiKey: 'your-maxim-api-key',
    promptManagement: true, // Enable prompt management
  });
  ```
</CodeGroup>

## Querying a Single Prompt

Retrieve a specific prompt using deployment variables to match your environment:

<CodeGroup>
  ```python Python theme={null}
  # Query a prompt for production environment
  prompt = maxim.get_prompt(
      id="your-prompt-id",
      rule=QueryBuilder()
      .and_()
      .deployment_var(
          "Environment", "prod"
      )  # make sure to use your deployment variables here
      .deployment_var("TenantId", 123)
      .build(),
  )

  if prompt:  # Use the prompt in your application
      response = prompt.run(
          input="What are the benefits of cloud computing?",
          variables={"user_level": "beginner", "industry": "healthcare"},
      )
      print(f"Response: {response.choices[0].message.content}")
  else:
      print("No matching prompt found")
  ```

  ```typescript JS/TS theme={null}
  // Query a prompt for production environment
  const prompt = await maxim.getPrompt(
    'your-prompt-id',
    new QueryBuilder()
      .and()
      .deploymentVar('Environment', 'prod') // make sure to use your deployment variables here
      .deploymentVar('TenantId', 123)
      .build()
  );

  if (prompt) {
    // Use the prompt in your application
    const response = await prompt.run(
      'What are the benefits of cloud computing?',
      {
        variables: {
          user_level: 'beginner',
          industry: 'healthcare',
        },
      }
    );
    console.log(`Response: ${response.choices[0]?.message.content}`);
  } else {
    console.log('No matching prompt found');
  }
  ```
</CodeGroup>

## Querying a Specific Prompt Version

Retrieve a specific version of a prompt using the version number:

<CodeGroup>
  ```python Python theme={null}
  # Query a specific prompt version
  prompt = maxim.get_prompt(
      id="prompt-id",
      rule=QueryBuilder()
      .prompt_version_number(1)  # fetches version 1
      .build(),
  )

  if prompt:
      print(f"Retrieved version: {prompt.version_id}")
  ```

  ```typescript JS/TS theme={null}
  // Query a specific prompt version
  const prompt = await maxim.getPrompt(
    'prompt-id',
    new QueryBuilder()
      .promptVersionNumber(1) // fetches version 1
      .build()
  );

  if (prompt) {
    console.log(`Retrieved version: ${prompt.version}`);
  }
  ```
</CodeGroup>

## Querying Multiple Prompts

Retrieve all prompts that match specific deployment criteria:

<CodeGroup>
  ```python Python theme={null}
  from maxim import Maxim
  from maxim.models import QueryBuilder

  # Initialize Maxim with prompt management enabled

  maxim = Maxim(
      {
          "api_key": "your-maxim-api-key",
          "prompt_management": True,  # Enable prompt management
      }
  )

  # Get all prompts for a specific environment and feature
  prompts = maxim.get_prompts(
      rule=QueryBuilder().and_().deployment_var("Environment", "prod").build()
  )

  print(f"Found {len(prompts)} matching prompts:")
  for prompt in prompts:
      print(f"- Prompt ID: {prompt.prompt_id}, Version: {prompt.version_id}")

  # Use prompts in your application

  if prompts:
      support_prompt = prompts[0]  # Use first matching prompt
      response = support_prompt.run("How can I reset my password?")
      print(
          f"\nResponse from first prompt and version: {response.choices[0].message.content}"
      )
  else:
      print("No matching prompts found")
  ```

  ```typescript JS/TS theme={null}
  // Get all prompts for a specific environment and feature
  const prompts = await maxim.getPrompts(
    new QueryBuilder().and().deploymentVar('Environment', 'prod').build()
  );

  if (prompts) {
    console.log(`Found ${prompts.length} matching prompts:`);
    prompts.forEach(prompt => {
      console.log(`- Prompt ID: ${prompt.promptId}, Version: ${prompt.version}`);
    });
  }

  // Use prompts in your application
  if (prompts && prompts.length > 0) {
    const supportPrompt = prompts[0]; // Use first matching prompt
    if (supportPrompt) {
      const response = await supportPrompt.run('How can I reset my password?');
      console.log(
        `\nResponse from first prompt and version: ${response.choices[0]?.message.content}`
      );
    } else {
      console.log('No matching prompt found');
    }
  }
  ```
</CodeGroup>

## Automatic logging

You can configure the SDK to automatically log the prompt runs.

<CodeGroup>
  ```python Python theme={null}
  trace = logger.trace(config={"id": str(uuid.uuid4()), "name": "trace-name"})

  prompt_id = "your-prompt-id"
  prompt_version_number = 1
  prompt = maxim.get_prompt(prompt_id, QueryBuilder().prompt_version_number(prompt_version_number))

  prompt.with_logger(parent=trace)

  result = prompt.run(
    input="Hello",
    variables={"tone": "cheerful and calm"}
  )
  ```

  ```typescript JS/TS theme={null}
  const trace = logger.trace({id: "trace-id", name: "trace-name"})

  const promptId = "your-prompt-id"
  const promptVersionNumber = 1
  const prompt = await maxim.getPrompt(
    promptId,
    new QueryBuilder().promptVersionNumber(promptVersionNumber).build(),
  );

  const promptWithLogger = prompt?.withLogger({parent: trace})
  const result = await promptWithLogger?.run("Hello", {
    variables: { tone: "cheerful and calm" },
  });
  ```
</CodeGroup>

## Supported Variable Types

When building queries using `deploymentVar`, ensure the value matches the type defined in your deployment configuration:

| Variable Type    | SDK Data Type | Example Value            |
| :--------------- | :------------ | :----------------------- |
| **Text**         | String        | `"lorem"`                |
| **Number**       | Number        | `42`                     |
| **Boolean**      | Boolean       | `true` or `false`        |
| **Select**       | String        | `"Production"`           |
| **Multi-select** | String\[]     | `["US-East", "EU-West"]` |

## Using Tags for Fine-Grained Filtering

Query prompts using tags for more specific filtering:

<CodeGroup>
  ```python Python theme={null}
  # Query prompts with specific tags
  prompt = maxim.get_prompt(
      id="your-prompt-id",
      rule=QueryBuilder()
      .and_()
      .deployment_var("Environment", "production")
      .tag("Tier", "premium")
      .tag("Language", "en")
      .build(),
  )

  if prompt:
      response = prompt.run("Explain our premium features")
  ```

  ```typescript JS/TS theme={null}
  // Query prompts with specific tags
  const prompt = await maxim.getPrompt(
      "your-prompt-id",
      new QueryBuilder()
          .and()
          .deploymentVar("Environment", "production")
          .tag("Tier", "premium")
          .tag("Language", "en")
          .build()
  );

  if (prompt) {
      const response = await prompt.run("Explain our premium features");
  }
  ```
</CodeGroup>

## Folder-Based Organization

Query prompts from specific folders to organize by team or feature:

<CodeGroup>
  ```python Python theme={null}
  # Query prompts from a specific folder
  prompts = maxim.get_prompts(
      rule=QueryBuilder()
      .and_()
      .folder("folder-id-for-marketing-team")
      .deployment_var("Environment", "production")
      .build()
  )

  print(f"Found {len(prompts)} marketing production prompts")
  ```

  ```typescript JS/TS theme={null}
  // Query prompts from a specific folder
  const prompts = await maxim.getPrompts(
      new QueryBuilder()
          .and()
          .folder("folder-id-for-marketing-team")
          .deploymentVar("Environment", "production")
          .build()
  );

  console.log(`Found ${prompts.length} marketing prompts`);
  ```
</CodeGroup>

## Matching algorithm

Before going into the details of how to use the SDK, let's understand how the matching algorithm works. Maxim SDK uses best matching entity algorithm.

1. Let's assume that, you have asked for a prompt with deployment var `env` as `prod`, `customerId` as `"123"` and a tag, `tenantId` as `456` for `promptId` - `"abc"`.
2. SDK will first try to find a prompt matching all conditions.
3. **If we don't find any matching entity, we enforce only `deploymentVar` conditions (you can override this behaviour, as explained in the next section) and match as many tags as possible.**
4. If we still don't find any prompt, we check for a prompt version marked as fallback.
5. If we still don't find any prompt, we return `null`.

## Overriding fallback algorithm

1. You can override fallback algorithm by calling `.exactMatch()` on `QueryBuilder` object. That will enforce all conditions to be matched.

<CodeGroup>
  ```typescript JS/TS theme={null}
  const prompt = await maxim.getPrompt(
  	"prompt-id",
  	new QueryBuilder()
          .and()
          .deploymentVar("Environment", "prod")
          .tag("CustomerId", "123")
          .exactMatch()
          .build(),
  );
  ```

  ```python Python theme={null}
  from maxim.models.queryBuilder import QueryBuilder

  prompt = maxim.getPrompt("prompt-id", QueryBuilder().and_()
  		.deploymentVar("Environment", "prod")
  		.tag("CustomerId","123")
  		.exactMatch()
  		.build())
  ```
</CodeGroup>

2. You can override fallback algorithm at each variable level. The third optional parameter in `deploymentVar` & `tag` function is `enforce`. If you pass `true` to this parameter, it will enforce exact match for that variable.

<CodeGroup>
  ```typescript JS/TS theme={null}
  const prompt = await maxim.getPrompt(
  	"prompt-id",
  	new QueryBuilder()
  	    .and()
  		.deploymentVar("Environment", "prod")
  		.tag("CustomerId", "123", true)
  		.build(),
  );
  ```

  ```python Python theme={null}
  from maxim.models.queryBuilder import QueryBuilder

  prompt = maxim.getPrompt("prompt-id", QueryBuilder().and_()
  		.deploymentVar("Environment", "prod")
  		.tag("CustomerId", "123", true)
  		.exactMatch()
  		.build())
  ```
</CodeGroup>

## Caching and Performance

The Maxim SDK automatically caches prompt configurations to improve performance using the cache provided to the constructor. When you request a prompt or prompt chain, the SDK first checks the cache for a matching deployment variable rule before making an API call.

## Best Practices

1. **Environment Separation**: Use deployment variables to separate dev/staging/production prompts
2. **Graceful Degradation**: Implement fallback prompts for critical functionality
3. **Version Management**: Use tags to manage prompt versions and gradual rollouts

## Next Steps

* [CI/CD Integration](/offline-evals/via-sdk/prompts/ci-cd-integration) - Automate prompt testing and deployment
* [Local Prompt Testing](/offline-evals/via-sdk/prompts/local-prompt) - Test changes before deployment
* [Maxim Prompt Testing](/offline-evals/via-sdk/prompts/maxim-prompt) - Validate prompt versions
