|
| 1 | +/* eslint-disable no-console */ |
| 2 | +import { OpenAI } from 'openai'; |
| 3 | + |
| 4 | +import { initAi } from '@launchdarkly/ai'; |
| 5 | +import { init, LDContext } from '@launchdarkly/node-server-sdk'; |
| 6 | + |
| 7 | +// Environment variables |
| 8 | +const sdkKey = process.env.LAUNCHDARKLY_SDK_KEY; |
| 9 | +const aiConfigKey = process.env.LAUNCHDARKLY_AI_CONFIG_KEY || 'sample-ai-config'; |
| 10 | + |
| 11 | +// Initialize OpenAI client |
| 12 | +const client = new OpenAI({ |
| 13 | + apiKey: process.env.OPENAI_API_KEY, // This is the default and can be omitted |
| 14 | +}); |
| 15 | + |
| 16 | +// Validate required environment variables |
| 17 | +if (!sdkKey) { |
| 18 | + console.error('*** Please set the LAUNCHDARKLY_SDK_KEY env first'); |
| 19 | + process.exit(1); |
| 20 | +} |
| 21 | + |
| 22 | +if (!aiConfigKey) { |
| 23 | + console.error('*** Please set the LAUNCHDARKLY_AI_CONFIG_KEY env first'); |
| 24 | + process.exit(1); |
| 25 | +} |
| 26 | + |
| 27 | +// Initialize LaunchDarkly client |
| 28 | +const ldClient = init(sdkKey); |
| 29 | + |
| 30 | +// Set up the context properties. This context should appear on your LaunchDarkly contexts dashboard |
| 31 | +// soon after you run the demo. |
| 32 | +const context: LDContext = { |
| 33 | + kind: 'user', |
| 34 | + key: 'example-user-key', |
| 35 | + name: 'Sandy', |
| 36 | +}; |
| 37 | + |
| 38 | +async function main(): Promise<void> { |
| 39 | + try { |
| 40 | + await ldClient.waitForInitialization({ timeout: 10 }); |
| 41 | + console.log('*** SDK successfully initialized'); |
| 42 | + const aiClient = initAi(ldClient); |
| 43 | + |
| 44 | + const configValue = await aiClient.modelConfig( |
| 45 | + aiConfigKey, |
| 46 | + context, |
| 47 | + { |
| 48 | + model: { |
| 49 | + modelId: 'gpt-4', |
| 50 | + }, |
| 51 | + }, |
| 52 | + { myVariable: 'My User Defined Variable' }, |
| 53 | + ); |
| 54 | + |
| 55 | + const { tracker } = configValue; |
| 56 | + const completion = await tracker.trackOpenAI(async () => |
| 57 | + client.chat.completions.create({ |
| 58 | + messages: configValue.config.prompt || [], |
| 59 | + model: configValue.config.model?.modelId || 'gpt-4', |
| 60 | + }), |
| 61 | + ); |
| 62 | + |
| 63 | + console.log('AI Response:', completion.choices[0]?.message.content); |
| 64 | + console.log('Success.'); |
| 65 | + } catch (error) { |
| 66 | + console.log(`*** SDK failed to initialize: ${error}`); |
| 67 | + process.exit(1); |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +main(); |
0 commit comments