|
| 1 | +import { toJSString } from 'mongodb-query-parser'; |
| 2 | + |
| 3 | +// When including sample documents, we want to ensure that we do not |
| 4 | +// attach large documents and exceed the limit. OpenAI roughly estimates |
| 5 | +// 4 characters = 1 token and we should not exceed context window limits. |
| 6 | +// This roughly translates to 128k tokens. |
| 7 | +// TODO(COMPASS-10129): Adjust this limit based on the model's context window. |
| 8 | +const MAX_TOTAL_PROMPT_LENGTH = 512000; |
| 9 | +const MIN_SAMPLE_DOCUMENTS = 1; |
| 10 | + |
| 11 | +function getCurrentTimeString() { |
| 12 | + const dateTime = new Date(); |
| 13 | + const options: Intl.DateTimeFormatOptions = { |
| 14 | + weekday: 'short', |
| 15 | + year: 'numeric', |
| 16 | + month: 'short', |
| 17 | + day: '2-digit', |
| 18 | + hour: '2-digit', |
| 19 | + minute: '2-digit', |
| 20 | + second: '2-digit', |
| 21 | + timeZoneName: 'short', |
| 22 | + hour12: false, |
| 23 | + }; |
| 24 | + // e.g. Tue, Nov 25, 2025, 12:00:00 GMT+1 |
| 25 | + return dateTime.toLocaleString('en-US', options); |
| 26 | +} |
| 27 | + |
| 28 | +function buildInstructionsForFindQuery() { |
| 29 | + return [ |
| 30 | + 'Reduce prose to the minimum, your output will be parsed by a machine. ' + |
| 31 | + 'You generate MongoDB find query arguments. Provide filter, project, sort, skip, ' + |
| 32 | + 'limit and aggregation in shell syntax, wrap each argument with XML delimiters as follows:', |
| 33 | + '<filter>{}</filter>', |
| 34 | + '<project>{}</project>', |
| 35 | + '<sort>{}</sort>', |
| 36 | + '<skip>0</skip>', |
| 37 | + '<limit>0</limit>', |
| 38 | + '<aggregation>[]</aggregation>', |
| 39 | + 'Additional instructions:', |
| 40 | + '- Only use the aggregation field when the request cannot be represented with the other fields.', |
| 41 | + '- Do not use the aggregation field if a find query fulfills the objective.', |
| 42 | + '- If specifying latitude and longitude coordinates, list the longitude first, and then latitude.', |
| 43 | + `- The current date is ${getCurrentTimeString()}`, |
| 44 | + ].join('\n'); |
| 45 | +} |
| 46 | + |
| 47 | +function buildInstructionsForAggregateQuery() { |
| 48 | + return [ |
| 49 | + 'Reduce prose to the minimum, your output will be parsed by a machine. ' + |
| 50 | + 'You generate MongoDB aggregation pipelines. Provide only the aggregation ' + |
| 51 | + 'pipeline contents in an array in shell syntax, wrapped with XML delimiters as follows:', |
| 52 | + '<aggregation>[]</aggregation>', |
| 53 | + 'Additional instructions:', |
| 54 | + '- If specifying latitude and longitude coordinates, list the longitude first, and then latitude.', |
| 55 | + '- Only pass the contents of the aggregation, no surrounding syntax.', |
| 56 | + `- The current date is ${getCurrentTimeString()}`, |
| 57 | + ].join('\n'); |
| 58 | +} |
| 59 | + |
| 60 | +export type UserPromptForQueryOptions = { |
| 61 | + userPrompt: string; |
| 62 | + databaseName?: string; |
| 63 | + collectionName?: string; |
| 64 | + schema?: unknown; |
| 65 | + sampleDocuments?: unknown[]; |
| 66 | +}; |
| 67 | + |
| 68 | +function withCodeFence(code: string): string { |
| 69 | + return [ |
| 70 | + '', // Line break |
| 71 | + '```', |
| 72 | + code, |
| 73 | + '```', |
| 74 | + ].join('\n'); |
| 75 | +} |
| 76 | + |
| 77 | +function buildUserPromptForQuery({ |
| 78 | + type, |
| 79 | + userPrompt, |
| 80 | + databaseName, |
| 81 | + collectionName, |
| 82 | + schema, |
| 83 | + sampleDocuments, |
| 84 | +}: UserPromptForQueryOptions & { type: 'find' | 'aggregate' }): string { |
| 85 | + const messages = []; |
| 86 | + |
| 87 | + const queryPrompt = [ |
| 88 | + type === 'find' ? 'Write a query' : 'Generate an aggregation', |
| 89 | + 'that does the following:', |
| 90 | + `"${userPrompt}"`, |
| 91 | + ].join(' '); |
| 92 | + |
| 93 | + if (databaseName) { |
| 94 | + messages.push(`Database name: "${databaseName}"`); |
| 95 | + } |
| 96 | + if (collectionName) { |
| 97 | + messages.push(`Collection name: "${collectionName}"`); |
| 98 | + } |
| 99 | + if (schema) { |
| 100 | + messages.push( |
| 101 | + `Schema from a sample of documents from the collection:${withCodeFence( |
| 102 | + toJSString(schema)! |
| 103 | + )}` |
| 104 | + ); |
| 105 | + } |
| 106 | + if (sampleDocuments) { |
| 107 | + // When attaching the sample documents, we want to ensure that we do not |
| 108 | + // exceed the token limit. So we try following: |
| 109 | + // 1. If attaching all the sample documents exceeds then limit, we attach only 1 document. |
| 110 | + // 2. If attaching 1 document still exceeds the limit, we do not attach any sample documents. |
| 111 | + const sampleDocumentsStr = toJSString(sampleDocuments); |
| 112 | + const singleDocumentStr = toJSString( |
| 113 | + sampleDocuments.slice(0, MIN_SAMPLE_DOCUMENTS) |
| 114 | + ); |
| 115 | + const promptLengthWithoutSampleDocs = |
| 116 | + messages.join('\n').length + queryPrompt.length; |
| 117 | + if ( |
| 118 | + sampleDocumentsStr && |
| 119 | + sampleDocumentsStr.length + promptLengthWithoutSampleDocs <= |
| 120 | + MAX_TOTAL_PROMPT_LENGTH |
| 121 | + ) { |
| 122 | + messages.push( |
| 123 | + `Sample documents from the collection:${withCodeFence( |
| 124 | + sampleDocumentsStr |
| 125 | + )}` |
| 126 | + ); |
| 127 | + } else if ( |
| 128 | + singleDocumentStr && |
| 129 | + singleDocumentStr.length + promptLengthWithoutSampleDocs <= |
| 130 | + MAX_TOTAL_PROMPT_LENGTH |
| 131 | + ) { |
| 132 | + messages.push( |
| 133 | + `Sample document from the collection:${withCodeFence( |
| 134 | + singleDocumentStr |
| 135 | + )}` |
| 136 | + ); |
| 137 | + } |
| 138 | + } |
| 139 | + messages.push(queryPrompt); |
| 140 | + return messages.join('\n'); |
| 141 | +} |
| 142 | + |
| 143 | +export type AiQueryPrompt = { |
| 144 | + prompt: string; |
| 145 | + metadata: { |
| 146 | + instructions: string; |
| 147 | + }; |
| 148 | +}; |
| 149 | + |
| 150 | +export function buildFindQueryPrompt({ |
| 151 | + userPrompt, |
| 152 | + databaseName, |
| 153 | + collectionName, |
| 154 | + schema, |
| 155 | + sampleDocuments, |
| 156 | +}: UserPromptForQueryOptions): AiQueryPrompt { |
| 157 | + const prompt = buildUserPromptForQuery({ |
| 158 | + type: 'find', |
| 159 | + userPrompt, |
| 160 | + databaseName, |
| 161 | + collectionName, |
| 162 | + schema, |
| 163 | + sampleDocuments, |
| 164 | + }); |
| 165 | + const instructions = buildInstructionsForFindQuery(); |
| 166 | + return { |
| 167 | + prompt, |
| 168 | + metadata: { |
| 169 | + instructions, |
| 170 | + }, |
| 171 | + }; |
| 172 | +} |
| 173 | + |
| 174 | +export function buildAggregateQueryPrompt({ |
| 175 | + userPrompt, |
| 176 | + databaseName, |
| 177 | + collectionName, |
| 178 | + schema, |
| 179 | + sampleDocuments, |
| 180 | +}: UserPromptForQueryOptions): AiQueryPrompt { |
| 181 | + const prompt = buildUserPromptForQuery({ |
| 182 | + type: 'aggregate', |
| 183 | + userPrompt, |
| 184 | + databaseName, |
| 185 | + collectionName, |
| 186 | + schema, |
| 187 | + sampleDocuments, |
| 188 | + }); |
| 189 | + const instructions = buildInstructionsForAggregateQuery(); |
| 190 | + return { |
| 191 | + prompt, |
| 192 | + metadata: { |
| 193 | + instructions, |
| 194 | + }, |
| 195 | + }; |
| 196 | +} |
0 commit comments