feat(providers): extract/repair json before parsing

This commit is contained in:
ItzCrazyKns
2025-12-31 12:58:24 +05:30
parent bd7c563137
commit b83f9bac78
2 changed files with 16 additions and 2 deletions

View File

@@ -11,6 +11,7 @@ import { Ollama, Tool as OllamaTool, Message as OllamaMessage } from 'ollama';
import { parse } from 'partial-json'; import { parse } from 'partial-json';
import crypto from 'crypto'; import crypto from 'crypto';
import { Message } from '@/lib/types'; import { Message } from '@/lib/types';
import { repairJson } from '@toolsycc/json-repair';
type OllamaConfig = { type OllamaConfig = {
baseURL: string; baseURL: string;
@@ -205,7 +206,13 @@ class OllamaLLM extends BaseLLM<OllamaConfig> {
}); });
try { try {
return input.schema.parse(JSON.parse(response.message.content)) as T; return input.schema.parse(
JSON.parse(
repairJson(response.message.content, {
extractJson: true,
}) as string,
),
) as T;
} catch (err) { } catch (err) {
throw new Error(`Error parsing response from Ollama: ${err}`); throw new Error(`Error parsing response from Ollama: ${err}`);
} }

View File

@@ -18,6 +18,7 @@ import {
ChatCompletionToolMessageParam, ChatCompletionToolMessageParam,
} from 'openai/resources/index.mjs'; } from 'openai/resources/index.mjs';
import { Message } from '@/lib/types'; import { Message } from '@/lib/types';
import { repairJson } from '@toolsycc/json-repair';
type OpenAIConfig = { type OpenAIConfig = {
apiKey: string; apiKey: string;
@@ -213,7 +214,13 @@ class OpenAILLM extends BaseLLM<OpenAIConfig> {
if (response.choices && response.choices.length > 0) { if (response.choices && response.choices.length > 0) {
try { try {
return input.schema.parse(response.choices[0].message.parsed) as T; return input.schema.parse(
JSON.parse(
repairJson(response.choices[0].message.content!, {
extractJson: true,
}) as string,
),
) as T;
} catch (err) { } catch (err) {
throw new Error(`Error parsing response from OpenAI: ${err}`); throw new Error(`Error parsing response from OpenAI: ${err}`);
} }