|
| 1 | +/* eslint-disable no-console */ |
| 2 | +import { init, type LDContext } from '@launchdarkly/node-server-sdk'; |
| 3 | +import { initAi } from '@launchdarkly/server-sdk-ai'; |
| 4 | + |
| 5 | +// Environment variables |
| 6 | +const sdkKey = process.env.LAUNCHDARKLY_SDK_KEY; |
| 7 | +const aiConfigKey = process.env.LAUNCHDARKLY_AI_CONFIG_KEY || 'sample-ai-config'; |
| 8 | + |
| 9 | +// Validate required environment variables |
| 10 | +if (!sdkKey) { |
| 11 | + console.error('*** Please set the LAUNCHDARKLY_SDK_KEY env first'); |
| 12 | + process.exit(1); |
| 13 | +} |
| 14 | + |
| 15 | +// Initialize LaunchDarkly client |
| 16 | +const ldClient = init(sdkKey); |
| 17 | + |
| 18 | +// Set up the context properties. This context should appear on your LaunchDarkly contexts dashboard |
| 19 | +// soon after you run the demo. |
| 20 | +const context: LDContext = { |
| 21 | + kind: 'user', |
| 22 | + key: 'example-user-key', |
| 23 | + name: 'Sandy', |
| 24 | +}; |
| 25 | + |
| 26 | +async function main(): Promise<void> { |
| 27 | + try { |
| 28 | + await ldClient.waitForInitialization({ timeout: 10 }); |
| 29 | + console.log('*** SDK successfully initialized'); |
| 30 | + } catch (error) { |
| 31 | + console.log(`*** SDK failed to initialize: ${error}`); |
| 32 | + process.exit(1); |
| 33 | + } |
| 34 | + |
| 35 | + const aiClient = initAi(ldClient); |
| 36 | + const defaultValue = { |
| 37 | + enabled: true, |
| 38 | + model: { name: 'gpt-3.5-turbo' }, |
| 39 | + messages: [{ role: 'system' as const, content: 'You are a helpful assistant.' }], |
| 40 | + provider: { name: 'openai' }, |
| 41 | + }; |
| 42 | + |
| 43 | + // You provide a disabled default value |
| 44 | + // const defaultValue = { |
| 45 | + // enabled: false, |
| 46 | + // }; |
| 47 | + |
| 48 | + // Get AI chat configuration from LaunchDarkly |
| 49 | + const chat = await aiClient.initChat(aiConfigKey, context, defaultValue, { |
| 50 | + companyName: 'LaunchDarkly', |
| 51 | + }); |
| 52 | + |
| 53 | + if (!chat) { |
| 54 | + console.log('*** AI chat configuration is not enabled'); |
| 55 | + process.exit(0); |
| 56 | + } |
| 57 | + |
| 58 | + // Example of using the chat functionality |
| 59 | + console.log('\n*** Starting chat conversation:'); |
| 60 | + try { |
| 61 | + const userInput = 'Hello! Can you help me understand how your company can help me?'; |
| 62 | + console.log('User Input:', userInput); |
| 63 | + |
| 64 | + const response = await chat.invoke(userInput); |
| 65 | + |
| 66 | + console.log('AI Response:', response.message.content); |
| 67 | + |
| 68 | + console.log('Success.'); |
| 69 | + } catch (err) { |
| 70 | + console.error('Error:', err); |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +main(); |
0 commit comments