|
| 1 | +// Copyright 2020-2025 SubQuery Pte Ltd authors & contributors |
| 2 | +// SPDX-License-Identifier: GPL-3.0 |
| 3 | + |
| 4 | +import {BaseMessage, SystemMessage} from '@langchain/core/messages'; |
| 5 | +import {createReactAgent} from '@langchain/langgraph/prebuilt'; |
| 6 | +import {Module, OnModuleInit} from '@nestjs/common'; |
| 7 | +import {HttpAdapterHost} from '@nestjs/core'; |
| 8 | +import {SqlToolkit} from 'langchain/agents/toolkits/sql'; |
| 9 | +import {SqlDatabase} from 'langchain/sql_db'; |
| 10 | +import {DataSource} from 'typeorm'; |
| 11 | +import {Config} from '../configure'; |
| 12 | +import {getLogger} from '../utils/logger'; |
| 13 | +import {getYargsOption} from '../yargs'; |
| 14 | +import {createLLM} from './createLLM'; |
| 15 | + |
| 16 | +const {argv} = getYargsOption(); |
| 17 | +const logger = getLogger('chat-module'); |
| 18 | + |
| 19 | +@Module({ |
| 20 | + providers: [], |
| 21 | +}) |
| 22 | +export class ChatModule implements OnModuleInit { |
| 23 | + agent?: ReturnType<typeof createReactAgent>; |
| 24 | + |
| 25 | + constructor( |
| 26 | + private readonly httpAdapterHost: HttpAdapterHost, |
| 27 | + private readonly dataSource: DataSource, |
| 28 | + private readonly config: Config |
| 29 | + ) {} |
| 30 | + |
| 31 | + onModuleInit(): void { |
| 32 | + if (!this.httpAdapterHost) { |
| 33 | + return; |
| 34 | + } |
| 35 | + try { |
| 36 | + this.createServer(); |
| 37 | + } catch (e: any) { |
| 38 | + throw new Error(`create apollo server failed, ${e.message}`); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + private async initializeAgent() { |
| 43 | + const db = await SqlDatabase.fromDataSourceParams({ |
| 44 | + appDataSource: this.dataSource, |
| 45 | + }); |
| 46 | + |
| 47 | + const llm = createLLM(); |
| 48 | + |
| 49 | + const toolkit = new SqlToolkit(db, llm); |
| 50 | + |
| 51 | + this.agent = createReactAgent({ |
| 52 | + llm, |
| 53 | + tools: toolkit.getTools(), |
| 54 | + prompt: new SystemMessage( |
| 55 | + `You are an AI assistant that helps users query their PostgreSQL database using natural language. |
| 56 | +
|
| 57 | +When generating SQL queries: |
| 58 | +* Always use the correct schema (${this.config.get<string>('name') || 'public'}) |
| 59 | +* Only query tables that are available to you |
| 60 | +* Never mutate database, including add/update/remove record from any table, run any DLL statements, only read. |
| 61 | +* Always limit the query with maximum 100 rows |
| 62 | +* Format your responses in a clear, readable way |
| 63 | +* If you're unsure about the schema or table structure, ask for clarification |
| 64 | +* If a table has column _block_range, it is a versioned table, You MUST always add \`_block_range @> 9223372036854775807\` to the where clause for all queries |
| 65 | +* If it is a join query, \`_block_range @> 9223372036854775807\` is needed for all tables in the join` |
| 66 | + ), |
| 67 | + }); |
| 68 | + } |
| 69 | + |
| 70 | + private createServer() { |
| 71 | + const app = this.httpAdapterHost.httpAdapter.getInstance(); |
| 72 | + |
| 73 | + if (argv.chat) { |
| 74 | + app.post('/v1/chat/completions', async (req, res) => { |
| 75 | + try { |
| 76 | + if (!this.agent) { |
| 77 | + await this.initializeAgent(); |
| 78 | + } |
| 79 | + |
| 80 | + const {messages, stream = false} = req.body; |
| 81 | + |
| 82 | + if (!messages || !Array.isArray(messages) || messages.length === 0) { |
| 83 | + return res.status(400).json({ |
| 84 | + error: { |
| 85 | + message: 'messages is required and must be a non-empty array', |
| 86 | + type: 'invalid_request_error', |
| 87 | + code: 'invalid_messages', |
| 88 | + }, |
| 89 | + }); |
| 90 | + } |
| 91 | + |
| 92 | + // Convert OpenAI format messages to LangChain format |
| 93 | + const lastMessage = messages[messages.length - 1]; |
| 94 | + const question = lastMessage.content; |
| 95 | + |
| 96 | + res.setHeader('Content-Type', 'text/event-stream'); |
| 97 | + res.setHeader('Cache-Control', 'no-cache'); |
| 98 | + res.setHeader('Connection', 'keep-alive'); |
| 99 | + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion |
| 100 | + const result = await this.agent!.stream({messages: [['user', question]]}, {streamMode: 'values'}); |
| 101 | + |
| 102 | + let fullResponse = ''; |
| 103 | + for await (const event of result) { |
| 104 | + const lastMsg: BaseMessage = event.messages[event.messages.length - 1]; |
| 105 | + if (lastMsg.content) { |
| 106 | + fullResponse = lastMsg.content as string; |
| 107 | + logger.info(`Streaming response: ${JSON.stringify(lastMsg)}`); |
| 108 | + if (argv['llm-debug'] && stream) { |
| 109 | + // todo: send them as thinking details |
| 110 | + res.write( |
| 111 | + `data: ${JSON.stringify({ |
| 112 | + id: `chatcmpl-${Date.now()}`, |
| 113 | + object: 'chat.completion.chunk', |
| 114 | + created: Math.floor(Date.now() / 1000), |
| 115 | + model: process.env.OPENAI_MODEL, |
| 116 | + choices: [ |
| 117 | + { |
| 118 | + index: 0, |
| 119 | + delta: {content: lastMsg.content}, |
| 120 | + finish_reason: null, |
| 121 | + }, |
| 122 | + ], |
| 123 | + })}\n\n` |
| 124 | + ); |
| 125 | + } |
| 126 | + } |
| 127 | + } |
| 128 | + |
| 129 | + // Send final message |
| 130 | + if (stream) { |
| 131 | + res.write( |
| 132 | + `data: ${JSON.stringify({ |
| 133 | + id: `chatcmpl-${Date.now()}`, |
| 134 | + object: 'chat.completion.chunk', |
| 135 | + created: Math.floor(Date.now() / 1000), |
| 136 | + model: process.env.OPENAI_MODEL, |
| 137 | + choices: [ |
| 138 | + { |
| 139 | + index: 0, |
| 140 | + message: {role: 'assistant', content: fullResponse}, |
| 141 | + finish_reason: 'stop', |
| 142 | + }, |
| 143 | + ], |
| 144 | + })}\n\n` |
| 145 | + ); |
| 146 | + } else { |
| 147 | + res.write( |
| 148 | + `data: ${JSON.stringify({ |
| 149 | + id: `chatcmpl-${Date.now()}`, |
| 150 | + object: 'chat.completion', |
| 151 | + created: Math.floor(Date.now() / 1000), |
| 152 | + model: process.env.OPENAI_MODEL, |
| 153 | + choices: [ |
| 154 | + { |
| 155 | + index: 0, |
| 156 | + message: {role: 'assistant', content: fullResponse}, |
| 157 | + finish_reason: 'stop', |
| 158 | + }, |
| 159 | + ], |
| 160 | + })}\n\n` |
| 161 | + ); |
| 162 | + } |
| 163 | + res.end(); |
| 164 | + } catch (error) { |
| 165 | + logger.error('Error processing request:', error); |
| 166 | + res.status(500).json({ |
| 167 | + error: { |
| 168 | + message: (error as any).message, |
| 169 | + type: 'internal_server_error', |
| 170 | + }, |
| 171 | + }); |
| 172 | + } |
| 173 | + }); |
| 174 | + } else { |
| 175 | + app.post('/v1/chat/completions', (req, res) => { |
| 176 | + res.status(404).json({ |
| 177 | + error: { |
| 178 | + message: 'Chat completions API is not enabled', |
| 179 | + type: 'invalid_request_error', |
| 180 | + code: 'chat_api_not_enabled', |
| 181 | + }, |
| 182 | + }); |
| 183 | + }); |
| 184 | + } |
| 185 | + } |
| 186 | +} |
0 commit comments