Overview

PromptL seamlessly integrates with OpenAI’s API. By default, PromptL formats prompts in the structure required by OpenAI, so you can use the output directly without additional processing.


Basic Example

Here’s how to generate a response from OpenAI using PromptL:

import { render } from 'promptl-ai'
import OpenAI from 'openai'

const prompt = `
---
model: gpt-4o
temperature: 0.6
---

Generate a joke about {{ topic }}.
`

const { messages, config } = await render({
  prompt,
  parameters: { topic: 'chickens' },
})

const client = new OpenAI({ apiKey: YOUR_OPENAI_API_KEY })
const response = await client.chat.completions.create({
  ...config,
  messages,
})

console.log(response.choices[0].message.content)

Key Features

  1. Default Adapter: PromptL automatically uses the OpenAI adapter for correct formatting.
  2. Role-Based Messages: OpenAI expects a role field (system, user, assistant) in messages, which PromptL handles for you.
  3. Configuration Pass-Through: Configuration options (e.g., temperature, model) are passed directly to OpenAI’s API.

Error Handling

When working with OpenAI, ensure you handle potential API errors gracefully:

try {
  const response = await client.chat.completions.create({
    ...config,
    messages,
  })
  console.log(response.choices[0].message.content)
} catch (error) {
  console.error('Error with OpenAI API:', error)
}

Next Steps