Skip to content

Commit 24207bc

Browse files
cihan-gykclaudegkhngyk
authored
feat(tracking): keep the searches the OpenAI API model ran as its query fan-out (#1756)
* feat(tracking): sample ChatGPT's query fan-out one day a week through Cloro's legacy interface ChatGPT's default (mobile-web) interface has carried no query text since 2026-09-30, so its tasks stopped asking for fan-out (#1119). Cloro's legacy desktop interface (`legacy: true`) still returns `searchQueries`, at the add-on's +2 credits a task. - CLORO_CHATGPT_FANOUT = off | sample | all (default sample). On sample a prompt's ChatGPT task asks one UTC weekday a week, picked from a hash of the prompt id (no stored state, spread across the week). That day's answer is the tracked one; no extra request. - The tracking worker decides per task and passes `legacy` to submitScraperTask / buildRequestBody, which stays pure. A legacy task Cloro refuses is submitted again without it. - Health report: on sample, ChatGPT is judged over the last 7 days (flagged when none of its answers carried fan-out) instead of day against days before, which swings by design; on all it is expected daily; on off it is not judged. - Docs: env var in self-host docs and .env.example; Prompts guide explains the weekly sample. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(tracking): retry failed legacy ChatGPT tasks and keep fan-out to nightly runs Review follow-ups for the sampled ChatGPT fan-out. - A legacy ChatGPT task that Cloro takes and then fails goes once more without legacy, in both paths: the webhook reads it from the new cloro_pending_tasks.legacy column (00378) and swaps in the new task's pending row; polling uses the submission's own record. - A refused submission is sent again without legacy only on 400/422. submitScraperTask errors now carry the HTTP status; a network error, timeout, 429, 5xx, 401 or 402 is never resubmitted, since the first task may exist and be billed. - Only the nightly run's first attempt asks (source 'cron', attempt 1): manual runs, analyze-new, retries and recovered runs don't. - CLORO_CHATGPT_FANOUT unset: sample on the cloud, off on self-host. An unknown value is off and logged once. - Health report: sampled ChatGPT needs 7 x FANOUT_MIN_ANSWERS answers before a silent week or a silent day is flagged; if the extra days can't be read, only ChatGPT goes unjudged. - Web: ChatGPT is neither "shares" nor "not shared" on the Query Fan-out page, and its copy says ChatGPT's searches are sampled on some days. - Docs: per-location cost, nightly-only, and the UTC-midnight caveat; the probe notes the legacy sources/footnote check still to run. Co-Authored-By: Claude Opus 5.5 <[email protected]> * feat(tracking): keep the searches the OpenAI API model ran as its query fan-out ChatGPT's fan-out has come only once a week through Cloro since 2026-09-30. The OpenAI API model's answers carry theirs already: the Responses web_search calls hold the queries they ran. They were dropped. - openai-tracker.js: searchQueriesOf reads each web_search_call's search action (`query`, and `queries` when given; open_page and find_in_page aren't searches) into the fan-out shape [{ query, source_platform: 'chatgpt' }], trimmed and once each. From the same response: no other call, no extra cost. - tracking-worker.js: the model path's insertResult keeps search_queries, as the scraper path does (Claude's gives none: an empty list). - The Query Fan-out page counts `chatgpt` (the API model) among the engines that share their searches (fanout-platforms.ts), and the daily health report expects it (FANOUT_EXPECTED), its warning pointing at OpenAI rather than Cloro. On Cloud, API-model tracking is off on every plan (allowedModels []), so this shows where an OpenAI model is tracked: self-host, or an Enterprise plan_overrides. ChatGPT's own interface (chatgpt-web) is unchanged here. Co-Authored-By: Claude Opus 5.5 <[email protected]> * fix(tracking): judge the OpenAI API model's fan-out on a drop only Review follow-ups for the API model's query fan-out. - Health report: `chatgpt` leaves FANOUT_EXPECTED. gpt-5-chat-latest may run web_search rarely or not at all, so a silent day is no news; a fall from the days before still is, and points at OpenAI. - Web: `chatgpt` is neither "shares" nor "not shared" on the Query Fan-out page; fanout-platforms.test.ts checks fanoutSharing's answers rather than the lists. - searchQueriesOf reads the action's `queries` first (`query` is deprecated) and skips web_search calls whose status is `failed`. - Copy: the Prompts guide calls it "ChatGPT API" as the page does and says Claude and Gemini models' searches aren't captured yet; the empty state and coverage tooltip mention the API model. Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Cihan <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Gökhan Geyik <[email protected]>
1 parent 144e8a2 commit 24207bc

9 files changed

Lines changed: 211 additions & 16 deletions

File tree

‎docs/guides/prompts.mdx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,10 @@ Over 7 days or more, every prompt tracked daily has had its day. A 24-hour range
3434

3535
Self-hosted instances turn this on with `CLORO_CHATGPT_FANOUT` (off unless set; see [Environment variables](/self-host/env-variables)). The extra cost is per ChatGPT task, and a prompt has one task per location: a prompt tracked in 3 locations pays it 3 times on its day. The day is the UTC day the nightly run starts, so with a schedule close to midnight UTC a prompt can be asked 0 or 2 times in a week.
3636

37+
### API models' fan-out
38+
39+
A prompt tracked with an OpenAI model (an AI model, not the ChatGPT platform) shares the searches that model ran, from the same answer: they show as **ChatGPT API**, at no extra cost. The model doesn't search for every prompt, so some answers have none. We don't capture Claude and Gemini models' searches yet.
40+
3741
## Adding prompts
3842

3943
Three ways:

‎server/src/lib/health/report.js‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,10 @@ async function checkCloro(now) {
175175
* When those days can't be read, ChatGPT alone goes unjudged that day.
176176
* - `off` (the self-host default): nothing asks, so it isn't judged.
177177
*/
178+
// `chatgpt`, the OpenAI API model's answers (the tracking worker's
179+
// resolveModelPlatform), isn't expected: its web_search calls carry their
180+
// queries, but gpt-5-chat-latest may search rarely or not at all, so a silent
181+
// day is no news. It's judged on a drop only, like any other platform.
178182
export const FANOUT_EXPECTED = ['copilot-web', 'perplexity-web'];
179183
export const FANOUT_DROP_RATIO = 0.25;
180184
/** Fewer answers than this, on either side, are too few to judge. */
@@ -399,12 +403,14 @@ export function findIssues(report) {
399403
);
400404
continue;
401405
}
406+
// The API model's answers come from OpenAI, not from Cloro.
407+
const source = p.platform === 'chatgpt' ? "OpenAI's web_search returns" : 'Cloro returns';
402408
issues.push(
403409
p.withFanout === 0
404410
? `${p.platform} returned no query fan-out on any of its ${p.answers} answers ` +
405-
`in the last 24h (${percent(p.baselineRate)} the days before) — check what Cloro returns`
411+
`in the last 24h (${percent(p.baselineRate)} the days before) — check what ${source}`
406412
: `${p.platform} query fan-out fell to ${percent(p.rate)} of answers ` +
407-
`(${percent(p.baselineRate)} the days before) — check what Cloro returns`,
413+
`(${percent(p.baselineRate)} the days before) — check what ${source}`,
408414
);
409415
}
410416

‎server/src/lib/health/report.test.js‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,22 @@ describe('query fan-out', () => {
264264
expect(fanoutDropped({ ...silent, platform: 'chatgpt-web', chatgptFanout: 'off' })).toBe(false);
265265
// When every ChatGPT task asks, it should fan out like Copilot.
266266
expect(fanoutDropped({ ...silent, platform: 'chatgpt-web', chatgptFanout: 'all' })).toBe(true);
267+
// The OpenAI API model may search rarely or not at all, so a silent day
268+
// is no news for it either...
269+
expect(fanoutDropped({ ...silent, platform: 'chatgpt' })).toBe(false);
270+
// ...but a fall from what it shared the days before is, and it's OpenAI's.
271+
const fell = { ...silent, platform: 'chatgpt', withFanout: 4, rate: 0.01, baselineRate: 0.3 };
272+
expect(fanoutDropped(fell)).toBe(true);
273+
expect(
274+
findIssues({
275+
probes: {},
276+
nightly: {},
277+
cloro: {},
278+
fanout: { platforms: [fell] },
279+
}).filter((i) => i.includes('fan-out')),
280+
).toEqual([
281+
"chatgpt query fan-out fell to 1% of answers (30% the days before) — check what OpenAI's web_search returns",
282+
]);
267283
});
268284

269285
describe("ChatGPT's sample, one day a week per prompt", () => {

‎server/src/lib/openai-tracker.js‎

Lines changed: 38 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
/**
22
* OpenAI Responses API client with web_search tool for prompt tracking.
3-
* Sends prompts to OpenAI and returns the response with citations.
3+
* Sends prompts to OpenAI and returns the response with citations, and the
4+
* searches the model ran (its query fan-out, #332), read from the same
5+
* response: no other call.
46
*/
57

68
import OpenAI from 'openai';
@@ -21,14 +23,47 @@ function getClient() {
2123
return client;
2224
}
2325

26+
/** The platform API-model answers are stored under (the tracking worker's resolveModelPlatform). */
27+
const SOURCE_PLATFORM = 'chatgpt';
28+
29+
/**
30+
* The searches a response's web_search calls ran, as the query fan-out is
31+
* kept (#332, as Cloro's engines give it): `[{ query, source_platform }]`,
32+
* each once, trimmed. A search action lists them in `queries`; the single
33+
* `query` it carried before is deprecated, and still read while responses
34+
* may hold it. Opening or searching within a page is no search, and a call
35+
* whose `status` is `failed` ran none.
36+
*
37+
* @param {Array<{ type?: string, status?: string, action?: { type?: string, queries?: unknown, query?: unknown } }>} output
38+
*/
39+
export function searchQueriesOf(output) {
40+
const seen = new Set();
41+
const queries = [];
42+
for (const item of output || []) {
43+
if (item?.type !== 'web_search_call' || item.action?.type !== 'search') continue;
44+
if (item.status === 'failed') continue;
45+
const asked = [
46+
...(Array.isArray(item.action.queries) ? item.action.queries : []),
47+
item.action.query,
48+
];
49+
for (const value of asked) {
50+
const query = typeof value === 'string' ? value.trim() : '';
51+
if (!query || seen.has(query)) continue;
52+
seen.add(query);
53+
queries.push({ query, source_platform: SOURCE_PLATFORM });
54+
}
55+
}
56+
return queries;
57+
}
58+
2459
/**
2560
* Run a single prompt through OpenAI Responses API with web_search enabled.
2661
* @param {string} promptText - The prompt to send
2762
* @param {string} [model] - OpenAI model name (defaults to gpt-5-chat-latest)
2863
* @param {string} [region] - Location code for web_search user_location: an
2964
* ISO country (`DE`) or a US state (`US-CA`, #691). Country-only codes
3065
* produce exactly the payload they did before states existed.
31-
* @returns {Promise<{ text: string, citations: Array<{ url: string, title: string, startIndex: number, endIndex: number }>, model: string }>}
66+
* @returns {Promise<{ text: string, citations: Array<{ url: string, title: string, startIndex: number, endIndex: number }>, model: string, search_queries: Array<{ query: string, source_platform: string }> }>}
3267
*/
3368
export async function runPrompt(promptText, model, region) {
3469
const openai = getClient();
@@ -68,7 +103,7 @@ export async function runPrompt(promptText, model, region) {
68103
}
69104
}
70105

71-
return { text, citations, model: modelName };
106+
return { text, citations, model: modelName, search_queries: searchQueriesOf(response.output) };
72107
}
73108

74109
const SENTIMENT_MODEL = 'gpt-5-mini';
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
import { beforeEach, describe, expect, it, vi } from 'vitest';
2+
3+
/**
4+
* The OpenAI API model's searches (#332): read from the same Responses
5+
* answer the tracking already asks for, its web_search calls' queries kept
6+
* as the query fan-out. No other call.
7+
*/
8+
9+
const create = vi.hoisted(() => vi.fn());
10+
vi.mock('openai', () => ({
11+
default: class {
12+
responses = { create };
13+
},
14+
}));
15+
vi.mock('./logger.js', () => ({ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() } }));
16+
17+
process.env.OPENAI_API_KEY = 'sk-test';
18+
const { runPrompt, searchQueriesOf } = await import('./openai-tracker.js');
19+
20+
const search = (action, status = 'completed') => ({
21+
type: 'web_search_call',
22+
id: 'ws_1',
23+
status,
24+
action,
25+
});
26+
27+
beforeEach(() => {
28+
create.mockReset();
29+
});
30+
31+
describe('searchQueriesOf', () => {
32+
it("keeps each search's queries (and the deprecated query) once, trimmed, and nothing else", () => {
33+
expect(
34+
searchQueriesOf([
35+
search({ type: 'search', queries: [' best electric kettle 2026 ', 'kettle reviews', ' '] }),
36+
search({ type: 'search', query: 'best electric kettle 2026' }),
37+
search({ type: 'search', query: 'kettle descaling' }),
38+
search({ type: 'open_page', url: 'https://example.com' }),
39+
search({ type: 'find_in_page', pattern: 'price' }),
40+
{ type: 'message', content: [] },
41+
search({ type: 'search', query: 42 }),
42+
]),
43+
).toEqual([
44+
{ query: 'best electric kettle 2026', source_platform: 'chatgpt' },
45+
{ query: 'kettle reviews', source_platform: 'chatgpt' },
46+
{ query: 'kettle descaling', source_platform: 'chatgpt' },
47+
]);
48+
expect(searchQueriesOf(undefined)).toEqual([]);
49+
});
50+
51+
it('counts no search a failed call ran', () => {
52+
expect(
53+
searchQueriesOf([
54+
search({ type: 'search', queries: ['kettle reviews'] }, 'failed'),
55+
search({ type: 'search', queries: ['kettle prices'] }, 'in_progress'),
56+
]),
57+
).toEqual([{ query: 'kettle prices', source_platform: 'chatgpt' }]);
58+
});
59+
});
60+
61+
describe('runPrompt', () => {
62+
it('returns the searches beside the answer and its citations, from one call', async () => {
63+
create.mockResolvedValue({
64+
output_text: 'The Acme Kettle is a good pick.',
65+
output: [
66+
search({ type: 'search', query: 'best electric kettle' }),
67+
{
68+
type: 'message',
69+
content: [
70+
{
71+
type: 'output_text',
72+
annotations: [
73+
{
74+
type: 'url_citation',
75+
url: 'https://acme.com/kettle',
76+
title: 'Acme Kettle',
77+
start_index: 4,
78+
end_index: 15,
79+
},
80+
],
81+
},
82+
],
83+
},
84+
],
85+
});
86+
const result = await runPrompt('best electric kettle?', undefined, 'US');
87+
expect(create).toHaveBeenCalledTimes(1);
88+
expect(create.mock.calls[0][0]).toMatchObject({
89+
model: 'gpt-5-chat-latest',
90+
tools: [{ type: 'web_search' }],
91+
});
92+
expect(result).toEqual({
93+
text: 'The Acme Kettle is a good pick.',
94+
citations: [
95+
{ url: 'https://acme.com/kettle', title: 'Acme Kettle', startIndex: 4, endIndex: 15 },
96+
],
97+
model: 'gpt-5-chat-latest',
98+
search_queries: [{ query: 'best electric kettle', source_platform: 'chatgpt' }],
99+
});
100+
});
101+
102+
it('gives no searches for an answer that ran none', async () => {
103+
create.mockResolvedValue({ output_text: 'Hello.', output: [] });
104+
expect((await runPrompt('hi', 'gpt-4.1')).search_queries).toEqual([]);
105+
});
106+
});

‎server/src/workers/tracking-worker.js‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -945,6 +945,10 @@ export async function processTrackingJob({ brandId, promptId, promptIds, source,
945945
competitor_mentions: metrics.competitorMentions,
946946
mention_position: metrics.mentionPosition,
947947
mentioned_entity_count: metrics.mentionedEntityCount,
948+
// The searches the model ran, where its API gives them (OpenAI's web_search).
949+
search_queries: Array.isArray(aiResponse.search_queries)
950+
? aiResponse.search_queries
951+
: [],
948952
});
949953
} catch (err) {
950954
logger.error({ err, model: modelName, region }, 'ai model task failed');

‎web/messages/en.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8191,8 +8191,8 @@
81918191
"engineEmptyTitle": "No {engine} searches in the {range}",
81928192
"engineEmptyBody": "{engine} usually shares the searches behind its answers. Try a longer date range.",
81938193
"emptyTitle": "No fan-out captured yet",
8194-
"emptyBody": "Copilot and Perplexity share the searches behind their answers, and ChatGPT's are sampled on some days; Google AI Overviews, AI Mode and Gemini don't share them. Once those engines run for your prompts, the searches will appear here.",
8195-
"coverageTooltip": "Of {total} tracked answers in this window, {withFanout} came with the searches the engine ran. Copilot and Perplexity share them, and ChatGPT's are sampled on some days."
8194+
"emptyBody": "Copilot and Perplexity share the searches behind their answers; ChatGPT's are sampled on some days, and the ChatGPT API shares them when it searches. Google AI Overviews, AI Mode and Gemini don't share them. Once those engines run for your prompts, the searches will appear here.",
8195+
"coverageTooltip": "Of {total} tracked answers in this window, {withFanout} came with the searches the engine ran. Copilot and Perplexity share them, ChatGPT's are sampled on some days, and the ChatGPT API shares them when it searches."
81968196
},
81978197
"bulkDelete": {
81988198
"progress": "Deleting {done} of {total} prompts…",
Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import { describe, expect, it } from 'vitest';
2+
import { fanoutSharing } from './fanout-platforms';
3+
4+
/** How the Query Fan-out page reads each engine's searches (#332). */
5+
describe('fanoutSharing', () => {
6+
it('expects searches from the engines that send them with their answers', () => {
7+
expect(fanoutSharing('copilot-web')).toBe('shares');
8+
expect(fanoutSharing('perplexity-web')).toBe('shares');
9+
});
10+
11+
it('reads the engines that never send them, or whose searches we miss, as not shared', () => {
12+
for (const platform of ['google-aio', 'google-aimode', 'gemini-web', 'claude', 'gemini']) {
13+
expect(fanoutSharing(platform)).toBe('not-shared');
14+
}
15+
});
16+
17+
it('expects nothing either way from ChatGPT and the ChatGPT API, which send them some days', () => {
18+
// ChatGPT: sampled one day a week per prompt. The API model: when it searches.
19+
expect(fanoutSharing('chatgpt-web')).toBe('unknown');
20+
expect(fanoutSharing('chatgpt')).toBe('unknown');
21+
expect(fanoutSharing('something-new')).toBe('unknown');
22+
});
23+
});

‎web/src/config/fanout-platforms.ts‎

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -12,23 +12,24 @@ export const FANOUT_SHARING_PLATFORMS: readonly string[] = ['copilot-web', 'perp
1212

1313
/**
1414
* Platforms whose answers never come with their searches: those our provider
15-
* documents no fan-out for, and the API models (`claude`, `gemini`,
16-
* `chatgpt`, see resolveModelPlatform in the tracking worker), whose searches
17-
* we don't capture.
15+
* documents no fan-out for, and the API models whose searches we don't
16+
* capture (`claude`, `gemini`, see resolveModelPlatform in the tracking
17+
* worker).
1818
*
19-
* ChatGPT (`chatgpt-web`) is in neither list. Its default interface carries no
20-
* query text since 2026-09-30 (#1119); the server asks its legacy interface on
21-
* one day a week per prompt (CLORO_CHATGPT_FANOUT, off unless set on
22-
* self-host). So a window may hold some of its searches or none, and neither
23-
* is news: it reads as an ordinary engine, never flagged.
19+
* Two are in neither list, so a window may hold some of their searches or
20+
* none and neither is news: they read as ordinary engines, never flagged.
21+
* - ChatGPT (`chatgpt-web`): its default interface carries no query text
22+
* since 2026-09-30 (#1119); the server asks its legacy interface on one day
23+
* a week per prompt (CLORO_CHATGPT_FANOUT, off unless set on self-host).
24+
* - The OpenAI API model (`chatgpt`): its web_search calls carry their
25+
* queries, but gpt-5-chat-latest may search rarely or not at all.
2426
*/
2527
export const FANOUT_NOT_SHARED_PLATFORMS: readonly string[] = [
2628
'google-aio',
2729
'google-aimode',
2830
'gemini-web',
2931
'claude',
3032
'gemini',
31-
'chatgpt',
3233
];
3334

3435
/**

0 commit comments

Comments
 (0)