|
| 1 | +import 'crypto'; |
| 2 | +import { ChatPromptTemplate, SystemMessagePromptTemplate, HumanMessagePromptTemplate } from 'langchain/prompts'; |
| 3 | +import { createOpenAPIChain, BaseChain } from 'langchain/chains'; |
| 4 | +import { ChainValues } from 'langchain/schema'; |
| 5 | +import { CallbackManagerForChainRun } from 'langchain/callbacks'; |
| 6 | +import { createStructuredOutputChain } from 'langchain/chains/openai_functions'; |
| 7 | +import { ChatOpenAI } from 'langchain/chat_models/openai'; |
| 8 | +import type { Logger } from '../types'; |
| 9 | + |
| 10 | +const basePrompt = ( |
| 11 | + `You are a helpful AI copilot. Your job is to support and help the user answer questions about their data. ` + |
| 12 | + `Sometimes you may need to call Directus API endpoints to get the data you need to answer the user's question. ` + |
| 13 | + `You will be given a context and a question. Answer the question based on the context.` |
| 14 | +); |
| 15 | + |
| 16 | +type AskOutput = { |
| 17 | + response: string; |
| 18 | +}; |
| 19 | + |
| 20 | +export type AiServiceOptions = { |
| 21 | + apiKey?: string; |
| 22 | + verbose?: boolean; |
| 23 | + headers?: Record<string, string>; |
| 24 | + llm?: string; |
| 25 | + logger?: Logger; |
| 26 | +} |
| 27 | + |
| 28 | +export class AiService { |
| 29 | + spec: any; |
| 30 | + apiKey?: string; |
| 31 | + verbose?: boolean; |
| 32 | + headers?: Record<string, string>; |
| 33 | + llm?: string; |
| 34 | + logger?: Logger; |
| 35 | + |
| 36 | + constructor(spec: any, options: AiServiceOptions = {}) { |
| 37 | + this.spec = spec; |
| 38 | + this.apiKey = options.apiKey; |
| 39 | + this.verbose = options.verbose; |
| 40 | + this.headers = options.headers; |
| 41 | + this.llm = options.llm; |
| 42 | + this.logger = options.logger; |
| 43 | + |
| 44 | + return this; |
| 45 | + } |
| 46 | + |
| 47 | + async ask(question: string): Promise<AskOutput> { |
| 48 | + const openApiChain = await createOpenAPIChain(this.spec, { |
| 49 | + verbose: this.verbose, |
| 50 | + headers: this.headers, |
| 51 | + llm: new ChatOpenAI({ |
| 52 | + modelName: this.llm, |
| 53 | + configuration: { |
| 54 | + apiKey: this.apiKey, |
| 55 | + }, |
| 56 | + }), |
| 57 | + requestChain: new SimpleRequestChain({ |
| 58 | + requestMethod: async (name, args) => { |
| 59 | + console.log(name, args); |
| 60 | + throw Error('Request failed.'); |
| 61 | + } |
| 62 | + }), |
| 63 | + }); |
| 64 | + |
| 65 | + this.logger?.info(openApiChain.chains[0]); |
| 66 | + |
| 67 | + let apiOutput: string | undefined; |
| 68 | + try { |
| 69 | + this.logger?.info('Calling the API endpoint...'); |
| 70 | + const result = await openApiChain.run(question); |
| 71 | + if (result) { |
| 72 | + this.logger?.info(`Got an API result: ${result}`); |
| 73 | + apiOutput = JSON.stringify(JSON.parse(result)); |
| 74 | + this.logger?.info('Parsed response.'); |
| 75 | + } |
| 76 | + } catch (err) { |
| 77 | + this.logger?.warn(err); |
| 78 | + } |
| 79 | + |
| 80 | + const promptTemplate = await getChatPromptTemplate({ |
| 81 | + apiOutput, |
| 82 | + basePrompt, |
| 83 | + question, |
| 84 | + }); |
| 85 | + |
| 86 | + const structuredOutputChain = createStructuredOutputChain({ |
| 87 | + verbose: this.verbose, |
| 88 | + llm: new ChatOpenAI({ |
| 89 | + modelName: this.llm, |
| 90 | + temperature: 0, |
| 91 | + configuration: { |
| 92 | + apiKey: this.apiKey, |
| 93 | + }, |
| 94 | + }), |
| 95 | + prompt: promptTemplate, |
| 96 | + outputSchema: { |
| 97 | + type: 'object', |
| 98 | + properties: { |
| 99 | + 'response': { |
| 100 | + type: 'string', |
| 101 | + description: `The answer to the user's question in Markdown.`, |
| 102 | + }, |
| 103 | + }, |
| 104 | + }, |
| 105 | + }); |
| 106 | + |
| 107 | + const output = await structuredOutputChain.run({ |
| 108 | + question |
| 109 | + }) as any; |
| 110 | + |
| 111 | + return output; |
| 112 | + } |
| 113 | +} |
| 114 | + |
| 115 | +type GetChatPromptTemplateParams = { |
| 116 | + basePrompt: string; |
| 117 | + question: string; |
| 118 | + apiOutput?: string; |
| 119 | +}; |
| 120 | + |
| 121 | +async function getChatPromptTemplate({ basePrompt, question, apiOutput }: GetChatPromptTemplateParams): Promise<ChatPromptTemplate> { |
| 122 | + if (apiOutput) { |
| 123 | + return await ChatPromptTemplate.fromPromptMessages([ |
| 124 | + SystemMessagePromptTemplate.fromTemplate( |
| 125 | + '{base_prompt}' |
| 126 | + ), |
| 127 | + SystemMessagePromptTemplate.fromTemplate( |
| 128 | + 'Do not let the user know that you are calling an API endpoint. ' + |
| 129 | + 'Do not ask follow up questions. ' + |
| 130 | + 'Try to get the job done in one go.' |
| 131 | + ), |
| 132 | + SystemMessagePromptTemplate.fromTemplate( |
| 133 | + 'Calling the API endpoint...' |
| 134 | + ), |
| 135 | + SystemMessagePromptTemplate.fromTemplate( |
| 136 | + 'The API was called successfully.' |
| 137 | + ), |
| 138 | + SystemMessagePromptTemplate.fromTemplate( |
| 139 | + 'The API response is:\n```\n{api_output}\n```' |
| 140 | + ), |
| 141 | + HumanMessagePromptTemplate.fromTemplate( |
| 142 | + '{user_question}' |
| 143 | + ), |
| 144 | + SystemMessagePromptTemplate.fromTemplate( |
| 145 | + 'Based on the previous user question and the chat context, provide a helpful answer in Markdown format:', |
| 146 | + ), |
| 147 | + ]).partial({ |
| 148 | + base_prompt: basePrompt, |
| 149 | + api_output: apiOutput, |
| 150 | + user_question: question, |
| 151 | + }); |
| 152 | + } else { |
| 153 | + return await ChatPromptTemplate.fromPromptMessages([ |
| 154 | + SystemMessagePromptTemplate.fromTemplate( |
| 155 | + '{base_prompt}' |
| 156 | + ), |
| 157 | + SystemMessagePromptTemplate.fromTemplate( |
| 158 | + 'The API output is unavailable.' |
| 159 | + ), |
| 160 | + HumanMessagePromptTemplate.fromTemplate( |
| 161 | + '{user_question}' |
| 162 | + ), |
| 163 | + SystemMessagePromptTemplate.fromTemplate( |
| 164 | + 'Although the API output is unavailable, do your best to provide a helpful response:', |
| 165 | + ), |
| 166 | + ]).partial({ |
| 167 | + base_prompt: basePrompt, |
| 168 | + user_question: question, |
| 169 | + }); |
| 170 | + } |
| 171 | +} |
| 172 | + |
| 173 | +/** |
| 174 | + * Type representing a function for executing simple requests. |
| 175 | + */ |
| 176 | +type SimpleRequestChainExecutionMethod = ( |
| 177 | + name: string, |
| 178 | + // eslint-disable-next-line @typescript-eslint/no-explicit-any |
| 179 | + requestArgs: Record<string, any> |
| 180 | +) => Promise<string>; |
| 181 | + |
| 182 | +/** |
| 183 | + * A chain for making simple API requests. |
| 184 | + */ |
| 185 | +class SimpleRequestChain extends BaseChain { |
| 186 | + static lc_name() { |
| 187 | + return "SimpleRequestChain"; |
| 188 | + } |
| 189 | + |
| 190 | + private requestMethod: SimpleRequestChainExecutionMethod; |
| 191 | + |
| 192 | + inputKey = "function"; |
| 193 | + |
| 194 | + outputKey = "response"; |
| 195 | + |
| 196 | + constructor(config: { requestMethod: SimpleRequestChainExecutionMethod }) { |
| 197 | + super(); |
| 198 | + this.requestMethod = config.requestMethod; |
| 199 | + } |
| 200 | + |
| 201 | + get inputKeys() { |
| 202 | + return [this.inputKey]; |
| 203 | + } |
| 204 | + |
| 205 | + get outputKeys() { |
| 206 | + return [this.outputKey]; |
| 207 | + } |
| 208 | + |
| 209 | + _chainType() { |
| 210 | + return "simple_request_chain" as const; |
| 211 | + } |
| 212 | + |
| 213 | + /** @ignore */ |
| 214 | + async _call( |
| 215 | + values: ChainValues, |
| 216 | + _runManager?: CallbackManagerForChainRun |
| 217 | + ): Promise<ChainValues> { |
| 218 | + const inputKeyValue = values[this.inputKey]; |
| 219 | + const methodName = inputKeyValue.name; |
| 220 | + const args = inputKeyValue.arguments; |
| 221 | + const response = await this.requestMethod(methodName, args); |
| 222 | + return { [this.outputKey]: response }; |
| 223 | + } |
| 224 | +} |
0 commit comments