Skip to content

Commit

Permalink
Handle ollama json parse error
Browse files Browse the repository at this point in the history
  • Loading branch information
Caleb-T-Owens committed Jun 25, 2024
1 parent b8b8c18 commit c86201c
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 12 deletions.
8 changes: 2 additions & 6 deletions app/src/lib/ai/butlerClient.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { SHORT_DEFAULT_BRANCH_TEMPLATE, SHORT_DEFAULT_COMMIT_TEMPLATE } from '$lib/ai/prompts';
import { err, ok, type Result } from '$lib/result';
import { ok, stringErrorFromAny, type Result } from '$lib/result';
import type { AIClient, ModelKind, Prompt } from '$lib/ai/types';
import type { HttpClient } from '$lib/backend/httpClient';

Expand All @@ -26,11 +26,7 @@ export class ButlerAIClient implements AIClient {

return ok(response.message);
} catch (e) {
if (e instanceof Error) {
return err(e.message);
} else {
return err('Failed to contant GitButler API');
}
return stringErrorFromAny(e);
}
}
}
17 changes: 11 additions & 6 deletions app/src/lib/ai/ollamaClient.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { LONG_DEFAULT_BRANCH_TEMPLATE, LONG_DEFAULT_COMMIT_TEMPLATE } from '$lib/ai/prompts';
import { MessageRole, type PromptMessage, type AIClient, type Prompt } from '$lib/ai/types';
import { err, isError, ok, type Result } from '$lib/result';
import { err, isError, ok, stringErrorFromAny, type Result } from '$lib/result';
import { isNonEmptyObject } from '$lib/utils/typeguards';
import { fetch, Body, Response } from '@tauri-apps/api/http';

Expand Down Expand Up @@ -89,12 +89,17 @@ export class OllamaClient implements AIClient {
if (isError(responseResult)) return responseResult;
const response = responseResult.value;

const rawResponse = JSON.parse(response.message.content);
if (!isOllamaChatMessageFormat(rawResponse)) {
err('Invalid response: ' + response.message.content);
}
try {
const rawResponse = JSON.parse(response.message.content);
if (!isOllamaChatMessageFormat(rawResponse)) {
return err('Invalid response: ' + response.message.content);
}

return ok(rawResponse.result);
return ok(rawResponse.result);
} catch (e) {
// Catch JSON.parse error
return stringErrorFromAny(e);
}
}

/**
Expand Down
8 changes: 8 additions & 0 deletions app/src/lib/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,3 +41,11 @@ export function ok<Ok, Error>(value: Ok): Result<Ok, Error> {
export function err<Ok, Error>(value: Error): Result<Ok, Error> {
return { ok: false, error: value };
}

export function stringErrorFromAny<Ok>(value: any): Result<Ok, string> {
if (value instanceof Error) {
return err(value.message);
} else {
return err(String(value));
}
}

0 comments on commit c86201c

Please sign in to comment.