|
| 1 | +/* eslint-disable no-console */ |
| 2 | +import { |
| 3 | + BedrockRuntimeClient, |
| 4 | + ConversationRole, |
| 5 | + ConverseCommand, |
| 6 | + Message, |
| 7 | +} from '@aws-sdk/client-bedrock-runtime'; |
| 8 | + |
| 9 | +import { initAi, LDAIConfig } from '@launchdarkly/ai'; |
| 10 | +import { init } from '@launchdarkly/node-server-sdk'; |
| 11 | + |
| 12 | +const sdkKey = process.env.LAUNCHDARKLY_SDK_KEY; |
| 13 | +const aiConfigKey = process.env.LAUNCHDARKLY_AI_CONFIG_KEY || 'sample-ai-config'; |
| 14 | +const awsClient = new BedrockRuntimeClient({ region: 'us-east-1' }); |
| 15 | + |
| 16 | +if (!sdkKey) { |
| 17 | + console.error('*** Please set the LAUNCHDARKLY_SDK_KEY env first'); |
| 18 | + process.exit(1); |
| 19 | +} |
| 20 | + |
| 21 | +const ldClient = init(sdkKey); |
| 22 | + |
| 23 | +// Set up the context properties |
| 24 | +const context = { |
| 25 | + kind: 'user', |
| 26 | + key: 'example-user-key', |
| 27 | + name: 'Sandy', |
| 28 | +}; |
| 29 | + |
| 30 | +console.log('*** SDK successfully initialized'); |
| 31 | + |
| 32 | +function mapPromptToConversation(prompt: { role: ConversationRole; content: string }[]): Message[] { |
| 33 | + return prompt.map((item) => ({ |
| 34 | + role: item.role, |
| 35 | + content: [{ text: item.content }], |
| 36 | + })); |
| 37 | +} |
| 38 | + |
| 39 | +async function main() { |
| 40 | + let tracker; |
| 41 | + let configValue: LDAIConfig | false; |
| 42 | + |
| 43 | + try { |
| 44 | + await ldClient.waitForInitialization({ timeout: 10 }); |
| 45 | + const aiClient = initAi(ldClient); |
| 46 | + |
| 47 | + configValue = await aiClient.modelConfig(aiConfigKey, context, false, { |
| 48 | + myVariable: 'My User Defined Variable', |
| 49 | + }); |
| 50 | + tracker = configValue.tracker; |
| 51 | + } catch (error) { |
| 52 | + console.log(`*** SDK failed to initialize: ${error}`); |
| 53 | + process.exit(1); |
| 54 | + } |
| 55 | + |
| 56 | + const completion = await tracker.trackBedrockConverse( |
| 57 | + await awsClient.send( |
| 58 | + new ConverseCommand({ |
| 59 | + modelId: configValue.config.config.modelId, |
| 60 | + messages: mapPromptToConversation(configValue.config.prompt), |
| 61 | + }), |
| 62 | + ), |
| 63 | + ); |
| 64 | + |
| 65 | + console.log('AI Response:', completion.output.message.content[0].text); |
| 66 | + console.log('Success.'); |
| 67 | +} |
| 68 | + |
| 69 | +main(); |
0 commit comments