(request: string, promptPreamble?: string | PromptSection[])
| 122 | } |
| 123 | |
| 124 | async function translate(request: string, promptPreamble?: string | PromptSection[]) { |
| 125 | const preamble: PromptSection[] = typeof promptPreamble === "string" ? [{ role: "user", content: promptPreamble }] : promptPreamble ?? []; |
| 126 | let prompt: PromptSection[] = [...preamble, { role: "user", content: typeChat.createRequestPrompt(request) }]; |
| 127 | let attemptRepair = typeChat.attemptRepair; |
| 128 | while (true) { |
| 129 | const response = await model.complete(prompt); |
| 130 | if (!response.success) { |
| 131 | return response; |
| 132 | } |
| 133 | const responseText = response.data; |
| 134 | const startIndex = responseText.indexOf("{"); |
| 135 | const endIndex = responseText.lastIndexOf("}"); |
| 136 | if (!(startIndex >= 0 && endIndex > startIndex)) { |
| 137 | return error(`Response is not JSON:\n${responseText}`); |
| 138 | } |
| 139 | const jsonText = responseText.slice(startIndex, endIndex + 1); |
| 140 | let jsonObject; |
| 141 | try { |
| 142 | jsonObject = JSON.parse(jsonText) as object; |
| 143 | } |
| 144 | catch (e) { |
| 145 | return error(e instanceof SyntaxError ? e.message : "JSON parse error"); |
| 146 | } |
| 147 | if (typeChat.stripNulls) { |
| 148 | stripNulls(jsonObject); |
| 149 | } |
| 150 | const schemaValidation = validator.validate(jsonObject); |
| 151 | const validation = schemaValidation.success ? typeChat.validateInstance(schemaValidation.data) : schemaValidation; |
| 152 | if (validation.success) { |
| 153 | return validation; |
| 154 | } |
| 155 | if (!attemptRepair) { |
| 156 | return error(`JSON validation failed: ${validation.message}\n${jsonText}`); |
| 157 | } |
| 158 | prompt.push({ role: "assistant", content: responseText }); |
| 159 | prompt.push({ role: "user", content: typeChat.createRepairPrompt(validation.message) }); |
| 160 | attemptRepair = false; |
| 161 | } |
| 162 | } |
| 163 | } |
| 164 | |
| 165 | /** |
nothing calls this directly
no test coverage detected
searching dependent graphs…