|
| 1 | +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; |
| 2 | +import { AIMessage, HumanMessage, SystemMessage } from '@langchain/core/messages'; |
| 3 | +import { initChatModel } from 'langchain/chat_models/universal'; |
| 4 | + |
| 5 | +import { |
| 6 | + LDAIConfig, |
| 7 | + LDAIConfigTracker, |
| 8 | + LDMessage, |
| 9 | + LDTokenUsage, |
| 10 | +} from '@launchdarkly/server-sdk-ai'; |
| 11 | + |
| 12 | +/** |
| 13 | + * LangChain provider utilities and helper functions. |
| 14 | + */ |
| 15 | +export class LangChainProvider { |
| 16 | + /** |
| 17 | + * Map LaunchDarkly provider names to LangChain provider names. |
| 18 | + * This method enables seamless integration between LaunchDarkly's standardized |
| 19 | + * provider naming and LangChain's naming conventions. |
| 20 | + */ |
| 21 | + static mapProvider(ldProviderName: string): string { |
| 22 | + const lowercasedName = ldProviderName.toLowerCase(); |
| 23 | + |
| 24 | + const mapping: Record<string, string> = { |
| 25 | + gemini: 'google-genai', |
| 26 | + }; |
| 27 | + |
| 28 | + return mapping[lowercasedName] || lowercasedName; |
| 29 | + } |
| 30 | + |
| 31 | + /** |
| 32 | + * Create token usage information from a LangChain provider response. |
| 33 | + * This method extracts token usage information from LangChain responses |
| 34 | + * and returns a LaunchDarkly TokenUsage object. |
| 35 | + */ |
| 36 | + static createTokenUsage(langChainResponse: AIMessage): LDTokenUsage | undefined { |
| 37 | + if (!langChainResponse?.response_metadata?.tokenUsage) { |
| 38 | + return undefined; |
| 39 | + } |
| 40 | + |
| 41 | + const { tokenUsage } = langChainResponse.response_metadata; |
| 42 | + |
| 43 | + return { |
| 44 | + total: tokenUsage.totalTokens || 0, |
| 45 | + input: tokenUsage.promptTokens || 0, |
| 46 | + output: tokenUsage.completionTokens || 0, |
| 47 | + }; |
| 48 | + } |
| 49 | + |
| 50 | + /** |
| 51 | + * Convert LaunchDarkly messages to LangChain messages. |
| 52 | + * This helper method enables developers to work directly with LangChain message types |
| 53 | + * while maintaining compatibility with LaunchDarkly's standardized message format. |
| 54 | + */ |
| 55 | + static convertMessagesToLangChain( |
| 56 | + messages: LDMessage[], |
| 57 | + ): (HumanMessage | SystemMessage | AIMessage)[] { |
| 58 | + return messages.map((msg) => { |
| 59 | + switch (msg.role) { |
| 60 | + case 'system': |
| 61 | + return new SystemMessage(msg.content); |
| 62 | + case 'user': |
| 63 | + return new HumanMessage(msg.content); |
| 64 | + case 'assistant': |
| 65 | + return new AIMessage(msg.content); |
| 66 | + default: |
| 67 | + throw new Error(`Unsupported message role: ${msg.role}`); |
| 68 | + } |
| 69 | + }); |
| 70 | + } |
| 71 | + |
| 72 | + /** |
| 73 | + * Track metrics for a LangChain callable execution. |
| 74 | + * This helper method enables developers to work directly with LangChain callables |
| 75 | + * while ensuring consistent tracking behavior. |
| 76 | + */ |
| 77 | + static async trackMetricsOf( |
| 78 | + tracker: LDAIConfigTracker, |
| 79 | + callable: () => Promise<AIMessage>, |
| 80 | + ): Promise<AIMessage> { |
| 81 | + return tracker.trackDurationOf(async () => { |
| 82 | + try { |
| 83 | + const result = await callable(); |
| 84 | + |
| 85 | + // Extract and track token usage if available |
| 86 | + const tokenUsage = this.createTokenUsage(result); |
| 87 | + if (tokenUsage) { |
| 88 | + tracker.trackTokens({ |
| 89 | + total: tokenUsage.total, |
| 90 | + input: tokenUsage.input, |
| 91 | + output: tokenUsage.output, |
| 92 | + }); |
| 93 | + } |
| 94 | + |
| 95 | + tracker.trackSuccess(); |
| 96 | + return result; |
| 97 | + } catch (error) { |
| 98 | + tracker.trackError(); |
| 99 | + throw error; |
| 100 | + } |
| 101 | + }); |
| 102 | + } |
| 103 | + |
| 104 | + /** |
| 105 | + * Create a LangChain model from an AI configuration. |
| 106 | + * This public helper method enables developers to initialize their own LangChain models |
| 107 | + * using LaunchDarkly AI configurations. |
| 108 | + * |
| 109 | + * @param aiConfig The LaunchDarkly AI configuration |
| 110 | + * @returns A Promise that resolves to a configured LangChain BaseChatModel |
| 111 | + */ |
| 112 | + static async createLangChainModel(aiConfig: LDAIConfig): Promise<BaseChatModel> { |
| 113 | + const modelName = aiConfig.model?.name || ''; |
| 114 | + const provider = aiConfig.provider?.name || ''; |
| 115 | + const parameters = aiConfig.model?.parameters || {}; |
| 116 | + |
| 117 | + // Use LangChain's universal initChatModel to support multiple providers |
| 118 | + return initChatModel(modelName, { |
| 119 | + modelProvider: this.mapProvider(provider), |
| 120 | + ...parameters, |
| 121 | + }); |
| 122 | + } |
| 123 | +} |
0 commit comments