Browse Source

Tighten validation of web_fetch tool response

pull/8362/head
Thomas Kaul 4 weeks ago
parent
commit
9b3ebb68cd
  1. 31
      apps/api/src/helper/web-fetch.helper.spec.ts
  2. 47
      apps/api/src/helper/web-fetch.helper.ts
  3. 50
      apps/api/src/services/fetch/fetch.service.spec.ts
  4. 17
      apps/api/src/services/fetch/fetch.service.ts

31
apps/api/src/helper/web-fetch.helper.spec.ts

@ -22,12 +22,6 @@ describe('getWebFetchBody', () => {
).toBe('[{"a":1}]');
});
it('should get an object after a text in brackets', () => {
expect(
getWebFetchBody({ candidate: `[Note] ${BODY}`, isJson: true })
).toBe(BODY);
});
it.each([
['the raw message', FAILURE_MESSAGE],
[
@ -63,7 +57,20 @@ describe('getWebFetchBody', () => {
'a body with broken JSON',
'{"items":{"a":{"id":1,"value":0.1},"b\\":{\\"id\\":2,\\"value\\":0.2},"c":{"id":3,"value":0.3}}}'
],
['two JSON objects', `${BODY}\n\n${BODY}`]
['two JSON objects', `${BODY}\n\n${BODY}`],
['a citation marker', 'The fetch failed with HTTP 403 [1].'],
['an empty array after a text', 'No data was returned []'],
['an object after a citation marker', 'Sources [1]: {"a":1}'],
['an object after a text in brackets', `[Note] ${BODY}`],
[
'an array in a broken object',
'{"name":"bad\\q","items":[{"id":1},{"id":2}],"total":2}'
],
['an object in a broken array', '[{"a":1},]'],
[
'a false tool call',
'\n\n{"url":"https://www.example.com/data.json"}</parameter>'
]
])('should reject %s', (_, candidate) => {
expect(getWebFetchBody({ candidate, isJson: true })).toBeUndefined();
});
@ -73,16 +80,6 @@ describe('getWebFetchBody', () => {
expect(getWebFetchBody({ candidate, isJson: true })).toBe(candidate);
});
it('should leave a false tool call to the check of the caller', () => {
expect(
getWebFetchBody({
candidate:
'\n\n{"url":"https://www.example.com/data.json"}</parameter>',
isJson: true
})
).toBe('{"url":"https://www.example.com/data.json"}');
});
});
describe('with a route for other content', () => {

47
apps/api/src/helper/web-fetch.helper.ts

@ -22,37 +22,38 @@ export function getWebFetchBody({
return undefined;
}
return isJson ? json?.text : body;
if (!isJson) {
return body;
}
return json?.isWhole ? json.text : undefined;
}
/**
* Extracts the JSON object or array from a text. The extraction goes from the
* first opening bracket to the last closing bracket, so that a text with other
* brackets around the JSON gives no result.
* Extracts the JSON object or array from a text. The JSON must start at the
* beginning of a line and goes to the last matching closing bracket, so that a
* bracket in a sentence gives no result. `isWhole` tells if only a closing code
* fence follows the JSON.
*/
function extractJson(text: string) {
const brackets = [
{ close: '}', start: text.indexOf('{') },
{ close: ']', start: text.indexOf('[') }
]
.filter(({ start }) => {
return start >= 0;
})
.sort((a, b) => {
return a.start - b.start;
});
const start = text.search(/^[[{]/m);
for (const { close, start } of brackets) {
const jsonText = text.slice(start, text.lastIndexOf(close) + 1);
try {
return { text: jsonText, value: JSON.parse(jsonText) as unknown };
} catch {
continue;
}
if (start < 0) {
return undefined;
}
return undefined;
const end = text.lastIndexOf(text[start] === '{' ? '}' : ']') + 1;
const jsonText = text.slice(start, end);
try {
return {
isWhole: /^(```)?$/.test(text.slice(end).trim()),
text: jsonText,
value: JSON.parse(jsonText) as unknown
};
} catch {
return undefined;
}
}
/**

50
apps/api/src/services/fetch/fetch.service.spec.ts

@ -6,6 +6,7 @@ import {
PROPERTY_WEB_FETCH_ROUTES
} from '@ghostfolio/common/config';
import { Logger } from '@nestjs/common';
import { createOpenRouter } from '@openrouter/ai-sdk-provider';
import { generateText } from 'ai';
@ -124,6 +125,55 @@ describe('FetchService', () => {
await expect(response.text()).resolves.toBe(BODY);
});
it('should get the body from the content of a source on a truncated text', async () => {
mockGenerateText({
finishReason: 'length',
sources: [{ providerMetadata: { openrouter: { content: BODY } } }],
text: '{"items":['
});
const response = await fetchService.fetch(URL_WITH_ROUTE);
await expect(response.text()).resolves.toBe(BODY);
expect(directFetch).not.toHaveBeenCalled();
});
it('should log the failure message of a source after an empty text', async () => {
const debug = jest.spyOn(Logger.prototype, 'debug');
mockGenerateText({
sources: [
{ providerMetadata: { openrouter: { content: FAILURE_MESSAGE } } }
],
text: ''
});
await fetchService.fetch(URL_WITH_ROUTE);
expect(debug.mock.calls.join()).toContain('HTTP 405');
debug.mockRestore();
});
it('should redact the API keys in the log of a rejected body', async () => {
const debug = jest.spyOn(Logger.prototype, 'debug');
mockGenerateText({
text: '{"url":"https://www.example.com/data.json?apikey=secret&api_token=secret","status":"failed","error":"HTTP 405"}'
});
await fetchService.fetch(URL_WITH_ROUTE);
const logs = debug.mock.calls.join();
expect(logs).toContain('apikey=*******');
expect(logs).toContain('api_token=*******');
expect(logs).not.toContain('secret');
debug.mockRestore();
});
it('should call the model with temperature 0 and the configured engine', async () => {
mockGenerateText({ text: BODY });

17
apps/api/src/services/fetch/fetch.service.ts

@ -155,15 +155,13 @@ export class FetchService implements OnModuleInit {
this.logger.warn(
`Web fetch tool stopped with the reason "${finishReason}" for ${this.redactUrl(url)}`
);
return undefined;
}
const candidates = [
...(sources ?? []).map((source) => {
return source.providerMetadata?.openrouter?.content;
}),
text
...(finishReason === 'stop' ? [text] : [])
];
const isJson =
@ -180,7 +178,7 @@ export class FetchService implements OnModuleInit {
const body = getWebFetchBody({ candidate, isJson });
if (!body) {
rejectedBody = candidate;
rejectedBody = candidate.trim() || rejectedBody;
continue;
}
@ -270,7 +268,16 @@ export class FetchService implements OnModuleInit {
return '(empty)';
}
const singleLineBody = body.replace(/\s+/g, ' ').trim();
const singleLineBody = body
.replace(
new RegExp(
`(${FetchService.REDACTED_QUERY_PARAM_NAMES.join('|')})=[^&\\s"']+`,
'gi'
),
'$1=*******'
)
.replace(/\s+/g, ' ')
.trim();
return singleLineBody.length > FetchService.BODY_PREVIEW_LENGTH
? `${singleLineBody.slice(0, FetchService.BODY_PREVIEW_LENGTH)}…`

Loading…
Cancel
Save