Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle triple quotes in invalid json responses returned by the model #49

Merged
merged 5 commits into from
Aug 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 0 additions & 24 deletions src/services/ExtractOperationsFromOutput.js

This file was deleted.

36 changes: 36 additions & 0 deletions src/services/ExtractOperationsService.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
export class ExtractOperationsService {
static call(input) {
try {
const parsedJSON = JSON.parse(input);
return parsedJSON;
} catch (error) {
return this.tryAgain(input)
}
}

static tryAgain(input) {
try {
// Replace triple double quotes with single double quotes
const correctedString = input.replace(/"{3}|'{3}/g, "\"")
return JSON.parse(correctedString)
} catch (error) {
const jsonRegex = /({.*}|\[.*\])/s; // Regular expression to match a JSON object or array
const match = input.match(jsonRegex);
if (match && match[1]) {
console.log('Attemping to extract json:')
console.log(match[1])
try {
const parsed = JSON.parse(match[1]);
return parsed;
} catch (error) {
console.log(error)
return null
}
} else {
console.log("There was an error parsing the model's output:")
console.log(input)
return null
}
}
}
}
6 changes: 3 additions & 3 deletions src/services/PromptrService.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import RefactorResultProcessor from './RefactorResultProcessor.js'
import TemplateLoader from './TemplateLoader.js'
import PromptContext from './PromptContext.js'
import AutoContext from './AutoContext.js'
import { extractOperationsFromOutput } from './ExtractOperationsFromOutput.js'
import { ExtractOperationsService } from './ExtractOperationsService.js'

export default class PromptrService {

Expand Down Expand Up @@ -54,7 +54,7 @@ export default class PromptrService {

if (this.shouldRefactor(CliState.getTemplatePath())) {
if (verbose) console.log(`Executing:\n${output}`)
const operations = extractOperationsFromOutput(output)
const operations = ExtractOperationsService.call(output)
if (CliState.isDryRun()) {
console.log(operations)
return 0
Expand Down Expand Up @@ -90,4 +90,4 @@ export default class PromptrService {
if (CliState.getExecuteFlag()) return true
return templatePath === "refactor" || !templatePath
}
}
}
70 changes: 70 additions & 0 deletions test/ExtractOperationsService.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import assert from 'assert'
import { ExtractOperationsService } from '../src/services/ExtractOperationsService.js'

describe('ExtractOperationsService', () => {
describe('call method', () => {
const testCases = [
{
input: '{"key": "value"}',
expectedOutput: { key: 'value' },
description: 'Simple JSON object'
},
{
input: 'random text {"key": "value"} more text',
expectedOutput: { key: 'value' },
description: 'JSON object with surrounding text'
},
{
input: '[{"key": "value1"}, {"key": "value2"}]',
expectedOutput: [{ key: 'value1' }, { key: 'value2' }],
description: 'Simple JSON array'
},
{
input: 'random text [{"key": "value1"}, {"key": "value2"}] more text',
expectedOutput: [{ key: 'value1' }, { key: 'value2' }],
description: 'JSON array with surrounding text'
},
{
input: 'this is not a JSON object or array',
expectedOutput: null,
description: 'No JSON object or array in the input string'
},
{
input: '{"key": "value" broken JSON',
expectedOutput: null,
description: 'Invalid JSON object'
}
]

testCases.forEach((testCase) => {
it(testCase.description, () => {
const result = ExtractOperationsService.call(testCase.input)
assert.deepStrictEqual(result, testCase.expectedOutput)
})
})

it('corrects the tripple quote fileContents delimeter issue', () => {
const invalidJson = `{
"operations": [
{
"crudOperation": "update",
"filePath": "my-script.py",
"fileContents": """file content"""
}
]
}
`
const expectedOutput = {
"operations": [
{
"crudOperation": "update",
"filePath": "my-script.py",
"fileContents": "file content"
}
]
}
const result = ExtractOperationsService.call(invalidJson)
assert.deepStrictEqual(result, expectedOutput)
})
})
})
32 changes: 17 additions & 15 deletions test/OpenAiGptService.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,21 +35,23 @@ describe('OpenAiGptService', () => {
sinon.assert.calledOnce(openaiStub);
});

it('should return null when the response does not contain choices', async () => {
const prompt = 'What is the capital of France?';
const model = 'gpt-4';

const configStub = sinon.stub(ConfigService, 'retrieveConfig').resolves({ api: { temperature: 0.5 } });
const openaiStub = sinon.stub(OpenAIApi.prototype, 'createChatCompletion').resolves({
data: {}
});

const result = await OpenAiGptService.call(prompt, model);

assert.strictEqual(result, null);
sinon.assert.calledOnce(configStub);
sinon.assert.calledOnce(openaiStub);
});
describe('edge cases around OpenAI API responses', () => {
it('should return null when the response does not contain choices', async () => {
const prompt = 'What is the capital of France?';
const model = 'gpt-4';

const configStub = sinon.stub(ConfigService, 'retrieveConfig').resolves({ api: { temperature: 0.5 } });
const openaiStub = sinon.stub(OpenAIApi.prototype, 'createChatCompletion').resolves({
data: {}
});

const result = await OpenAiGptService.call(prompt, model);

assert.strictEqual(result, null);
sinon.assert.calledOnce(configStub);
sinon.assert.calledOnce(openaiStub);
})
})

it('should append system messages in the call to openai.createChatCompletion when requestJsonOutput is true', async () => {
const prompt = 'What is the capital of France?';
Expand Down
44 changes: 0 additions & 44 deletions test/extractOperationsFromOutput.test.js

This file was deleted.