-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathuseChat.ts
More file actions
2102 lines (1936 loc) · 83.1 KB
/
useChat.ts
File metadata and controls
2102 lines (1936 loc) · 83.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { useCallback, useRef } from "react";
import { useAuth } from "@/auth";
import {
useStreamingStore,
useAllStreams,
useIsStreaming,
type StreamingResponse,
} from "@/stores/streamingStore";
import {
useConversationStore,
useMessages,
useSelectedInstances,
} from "@/stores/conversationStore";
import { useDebugStore } from "@/stores/debugStore";
import type {
CompletedRound,
ConversationMode,
ModeConfig,
MessageModeMetadata,
ModelInstance,
PerModelSettings,
Citation,
ChunkCitation,
Artifact,
ToolExecution,
ToolExecutionRound,
} from "@/components/chat-types";
import type {
ChatMessage,
ChatFile,
HistoryMode,
MessageUsage,
ModelResponse,
ModelSettings,
} from "./types";
import {
createToolCallTracker,
parseToolCallFromEvent,
type ParsedToolCall,
} from "./utils/toolCallParser";
import {
executeToolCalls,
buildToolResultInputItems,
createMCPToolName,
type ToolExecutorContext,
} from "./utils/toolExecutors";
import { getToolStatusLabel } from "@/components/ToolIcons";
import { useMCPStore } from "@/stores/mcpStore";
import {
sendChainedMode,
sendRoutedMode,
sendSynthesizedMode,
sendRefinedMode,
sendCritiquedMode,
sendElectedMode,
sendTournamentMode,
sendConsensusMode,
sendDebatedMode,
sendCouncilMode,
sendHierarchicalMode,
sendScattershotMode,
sendExplainerMode,
sendConfidenceWeightedMode,
filterMessagesForModel,
type ModeContext,
type ModeResult,
type ResponsesStreamEvent,
} from "./modes";
import { getDefaultSystemPrompt } from "@/utils/defaultSystemPrompt";
/** Data file info for SQL query context */
interface DataFileInfo {
name: string;
/** For flat files (CSV, Parquet, JSON) */
columns?: Array<{ name: string; type: string }>;
/** For database files (DuckDB) */
tables?: Array<{
tableName: string;
schemaName: string;
columns: Array<{ name: string; type: string }>;
}>;
/** Database alias for attached databases */
dbName?: string;
}
interface UseChatOptions {
models: string[];
settings?: ModelSettings;
historyMode?: HistoryMode;
/** Conversation mode - controls how multiple models interact */
conversationMode?: ConversationMode;
/** Mode-specific configuration */
modeConfig?: ModeConfig;
/** Per-model settings including reasoning config */
perModelSettings?: PerModelSettings;
/** Attached vector store IDs for file_search tool (RAG) */
vectorStoreIds?: string[];
/**
* Enable client-side tool execution for file_search.
* When true, the frontend detects tool calls in the SSE stream,
* executes the search API directly, and sends results back to continue.
* When false (default), the backend middleware handles tool execution.
*/
clientSideToolExecution?: boolean;
/**
* Enabled tool IDs. Only tools in this list will be sent to the model.
* Each tool may have additional requirements (e.g., file_search needs vectorStoreIds).
*/
enabledTools?: string[];
/**
* Data files registered with DuckDB for SQL queries.
* Used to build dynamic tool description with schema information.
*/
dataFiles?: DataFileInfo[];
/**
* Maximum number of tool execution iterations to prevent infinite loops.
* Defaults to 25.
*/
maxToolIterations?: number;
/**
* Whether to capture raw SSE events for debugging.
* When enabled, SSE events are stored in debugStore for inspection.
*/
captureRawSSEEvents?: boolean;
/**
* Default model for sub-agent tool.
* When null/undefined, uses the current streaming model as fallback.
*/
subAgentModel?: string | null;
/** Project ID for usage attribution (sent as X-Hadrian-Project header) */
projectId?: string;
/** Conversation ID for per-conversation MCP sessions */
conversationId?: string;
}
/**
* Build API content from text and optional files.
* Images are sent as input_image, text files are inlined as text content.
* Returns a simple string if no files, or a content array for multi-modal input.
*/
function buildApiContent(content: string, files?: ChatFile[]): string | unknown[] {
// If no files, return simple format
if (!files || files.length === 0) {
return content;
}
// Separate images from text files
const imageFiles = files.filter((f) => f.type.startsWith("image/"));
const textFiles = files.filter((f) => !f.type.startsWith("image/"));
// Build content array
const contentParts: unknown[] = [];
// Add main text content
if (content) {
contentParts.push({ type: "input_text", text: content });
}
// Add text files as inline text content
for (const file of textFiles) {
// Decode base64 content (file.base64 is a data URL like "data:type;base64,...")
const base64Data = file.base64.split(",")[1] || "";
let textContent: string;
try {
textContent = atob(base64Data);
} catch {
textContent = "[Could not decode file content]";
}
contentParts.push({
type: "input_text",
text: `\n\n--- File: ${file.name} ---\n${textContent}\n--- End of ${file.name} ---`,
});
}
// Add image files
for (const file of imageFiles) {
contentParts.push({
type: "input_image",
detail: "auto",
image_url: file.base64,
});
}
return contentParts;
}
/**
* Convert a ChatMessage to API input format, including any attached files.
*/
function messageToApiInput(msg: ChatMessage): { role: string; content: string | unknown[] } {
return { role: msg.role, content: buildApiContent(msg.content, msg.files) };
}
interface UseChatReturn {
messages: ChatMessage[];
modelResponses: ModelResponse[];
isStreaming: boolean;
sendMessage: (content: string, files: ChatFile[]) => void;
stopStreaming: () => void;
clearMessages: () => void;
/** Set messages directly. For functional updates, use the conversation store's actions. */
setMessages: (messages: ChatMessage[]) => void;
regenerateResponse: (userMessageId: string, model: string) => void;
/**
* Edit a message and re-run the conversation from that point.
* For user messages: updates content, deletes all subsequent messages, and streams new responses.
* For assistant messages: updates content only (preserves sibling model responses).
*/
editAndRerun: (messageId: string, newContent: string) => void;
}
/** Default maximum number of tool execution iterations to prevent infinite loops */
const DEFAULT_maxToolIterations = 25;
/** Result from streaming a response, including any tool calls */
interface StreamResponseResult {
content: string;
/** Whether any output_text deltas were received (vs reasoning-only fallback) */
hasOutputText: boolean;
usage?: MessageUsage;
reasoningContent?: string;
/** Per-round reasoning, content, and tool execution for multi-round tool execution */
completedRounds?: CompletedRound[];
/** Tool calls detected during streaming (only when clientSideToolExecution is enabled) */
toolCalls?: ParsedToolCall[];
/** Tool execution timeline for progressive disclosure UI */
toolExecutionRounds?: ToolExecutionRound[];
/** The request body sent to the API (for debugging) */
requestBody?: Record<string, unknown>;
/** The response.output array from the completed response (for debugging) */
responseOutput?: unknown[];
}
/** Extract the metadata fields from a streaming response for committing to the conversation store. */
function commitFieldsFromStream(stream: StreamingResponse | undefined) {
return {
citations: stream?.citations,
artifacts: stream?.artifacts,
toolExecutionRounds: stream?.toolExecutionRounds,
completedRounds: stream?.completedRounds.length ? stream.completedRounds : undefined,
};
}
export function useChat({
models,
settings,
historyMode = "all",
conversationMode = "multiple",
modeConfig,
perModelSettings,
vectorStoreIds,
clientSideToolExecution = false,
enabledTools = [],
dataFiles = [],
maxToolIterations = DEFAULT_maxToolIterations,
captureRawSSEEvents = false,
subAgentModel,
projectId,
conversationId,
}: UseChatOptions): UseChatReturn {
const { token } = useAuth();
const abortControllersRef = useRef<AbortController[]>([]);
// Use zustand stores instead of local state
const messages = useMessages();
const selectedInstances = useSelectedInstances();
const { setMessages, addUserMessage, addAssistantMessages } = useConversationStore();
// projectId is passed in from ChatPage (via useConversationSync's currentConversation)
// and used as a ref to ensure the latest value is available at fetch time.
const projectIdRef = useRef(projectId);
projectIdRef.current = projectId;
const conversationIdRef = useRef(conversationId);
conversationIdRef.current = conversationId;
const streamingStore = useStreamingStore();
const debugStore = useDebugStore();
const modelResponses = useAllStreams();
const isStreaming = useIsStreaming();
const stopStreaming = useCallback(() => {
abortControllersRef.current.forEach((controller) => controller.abort());
abortControllersRef.current = [];
streamingStore.stopStreaming();
}, [streamingStore]);
/**
* Stream a response from a model using the Responses API
*
* @param model - The model ID to use for the API call
* @param inputItems - The conversation input items
* @param abortController - Controller for cancellation
* @param modelSettings - Optional model settings (temperature, etc.)
* @param streamId - Optional stream ID for the streaming store (defaults to model). Use instance ID for multi-instance support.
* @param trackToolCalls - Whether to track tool calls for client-side execution
* @param onSSEEvent - Optional callback for capturing SSE events (for debugging)
* @param instanceParams - Optional instance-specific parameters (overrides perModelSettings lookup)
* @returns The response content, usage, reasoning, and any tool calls
*/
const streamResponse = useCallback(
async (
model: string,
inputItems: Array<{
role?: string;
type?: string;
content?: string | unknown[];
[key: string]: unknown;
}>,
abortController: AbortController,
modelSettings?: ModelSettings,
streamId?: string,
trackToolCalls?: boolean,
/** Optional callback for capturing SSE events (for debugging) */
onSSEEvent?: (event: { type: string; timestamp: number; data: unknown }) => void,
/** Optional instance-specific parameters (overrides perModelSettings lookup) */
instanceParams?: ModelInstance["parameters"],
/** Optional instance label for system prompt identity */
instanceLabel?: string
): Promise<StreamResponseResult | null> => {
// Use streamId for streaming store updates if provided, otherwise use model
const storeKey = streamId ?? model;
// Create tool call tracker if client-side tool execution is enabled
const toolTracker = trackToolCalls ? createToolCallTracker() : null;
try {
// Build Responses API input from chat messages
// Support both role-based messages and type-based items (function_call_output)
const input = inputItems.map((msg) => {
if (msg.type) {
// Type-based input item (e.g., function_call_output) - pass through as-is
return msg;
}
// Role-based message
return {
role: msg.role,
content: typeof msg.content === "string" ? msg.content : msg.content,
};
});
// Per-model settings for this model (instance params override stored per-model settings)
const perModel = instanceParams ?? perModelSettings?.[model];
// Add system prompt if not already present in input
// Some modes (explainer, synthesized, etc.) inject their own specialized system prompts
// Priority: existing in input > instanceParams > perModelSettings > global modelSettings > default
const hasSystemMessage = input.some((item) => item.role === "system");
if (!hasSystemMessage) {
const systemPrompt =
perModel?.systemPrompt ??
modelSettings?.systemPrompt ??
getDefaultSystemPrompt(model, instanceLabel);
input.unshift({
role: "system",
content: systemPrompt,
});
}
// Build request body with settings
const requestBody: Record<string, unknown> = {
model,
input,
stream: true,
};
// Add optional settings only if explicitly configured
// Priority: instanceParams > perModelSettings > global modelSettings
const temperature = perModel?.temperature ?? modelSettings?.temperature;
if (temperature !== undefined) {
requestBody.temperature = temperature;
}
const maxTokens = perModel?.maxTokens ?? modelSettings?.maxTokens;
if (maxTokens !== undefined) {
requestBody.max_output_tokens = maxTokens;
}
const topP = perModel?.topP ?? modelSettings?.topP;
if (topP !== undefined) {
requestBody.top_p = topP;
}
const topK = perModel?.topK ?? modelSettings?.topK;
if (topK !== undefined) {
requestBody.top_k = topK;
}
const frequencyPenalty = perModel?.frequencyPenalty ?? modelSettings?.frequencyPenalty;
if (frequencyPenalty !== undefined) {
requestBody.frequency_penalty = frequencyPenalty;
}
const presencePenalty = perModel?.presencePenalty ?? modelSettings?.presencePenalty;
if (presencePenalty !== undefined) {
requestBody.presence_penalty = presencePenalty;
}
// Add reasoning configuration from per-model settings if enabled
const reasoning = perModel?.reasoning;
if (reasoning?.enabled && reasoning.effort !== "none") {
requestBody.reasoning = {
effort: reasoning.effort,
};
}
// Build tools array based on enabled tools and their requirements
const tools: Array<{ type: string; [key: string]: unknown }> = [];
// Add file_search tool if enabled and vector stores are attached
if (enabledTools.includes("file_search") && vectorStoreIds && vectorStoreIds.length > 0) {
tools.push({
type: "file_search",
vector_store_ids: vectorStoreIds,
});
}
// Add code_interpreter as a function tool (client-side execution via Pyodide)
if (enabledTools.includes("code_interpreter")) {
tools.push({
type: "function",
name: "code_interpreter",
description:
"Execute Python code in a sandboxed browser environment (Pyodide/WebAssembly). " +
"Pre-installed: numpy, pandas, scipy, matplotlib, scikit-learn, pillow. " +
"Additional packages from PyPI are auto-installed when imported (via micropip). " +
"Use for calculations, data analysis, visualizations, or any Python task. " +
"Matplotlib figures are automatically captured and displayed. " +
"Note: Packages with C extensions not compiled for WebAssembly won't work.",
parameters: {
type: "object",
properties: {
code: {
type: "string",
description: "The Python code to execute",
},
},
required: ["code"],
},
});
}
// Add js_code_interpreter as a function tool (client-side execution via QuickJS)
if (enabledTools.includes("js_code_interpreter")) {
tools.push({
type: "function",
name: "js_code_interpreter",
description:
"Execute JavaScript code in a sandboxed browser environment using QuickJS. " +
"This is a lightweight, isolated JavaScript runtime with no access to DOM or browser APIs. " +
"Use console.log() to output results. Supports ES2020 syntax. " +
"Best for quick calculations, string manipulation, and JSON processing.",
parameters: {
type: "object",
properties: {
code: {
type: "string",
description: "The JavaScript code to execute",
},
},
required: ["code"],
},
});
}
// Add sql_query as a function tool (client-side execution via DuckDB WASM)
if (enabledTools.includes("sql_query")) {
// Build dynamic description with schema information
let sqlDescription =
"Execute SQL queries in-browser using DuckDB. " +
"Supports standard SQL syntax with analytics functions. " +
"Can query CSV, Parquet, JSON files directly (e.g., SELECT * FROM 'data.csv') " +
"and DuckDB database files (e.g., SELECT * FROM db_name.table_name). " +
"Use for data analysis, aggregations, joins, and transformations.";
// Add available files and their schemas
if (dataFiles.length > 0) {
sqlDescription += "\n\nAvailable data:";
for (const file of dataFiles) {
if (file.tables && file.tables.length > 0 && file.dbName) {
// Database file with tables
for (const table of file.tables) {
const columnList = table.columns.map((c) => `${c.name} (${c.type})`).join(", ");
sqlDescription += `\n- ${file.dbName}.${table.schemaName}.${table.tableName}: ${columnList}`;
}
} else if (file.columns && file.columns.length > 0) {
const columnList = file.columns.map((c) => `${c.name} (${c.type})`).join(", ");
sqlDescription += `\n- '${file.name}': ${columnList}`;
} else if (file.dbName) {
sqlDescription += `\n- Database '${file.name}' attached as ${file.dbName}`;
} else {
sqlDescription += `\n- '${file.name}'`;
}
}
}
tools.push({
type: "function",
name: "sql_query",
description: sqlDescription,
parameters: {
type: "object",
properties: {
sql: {
type: "string",
description: "The SQL query to execute",
},
},
required: ["sql"],
},
});
}
// Add chart_render as a function tool (client-side rendering via Vega-Lite)
if (enabledTools.includes("chart_render")) {
tools.push({
type: "function",
name: "chart_render",
description:
"Create data visualizations using Vega-Lite. " +
"Renders charts in the browser including bar charts, line charts, scatter plots, " +
"pie/donut charts, area charts, heatmaps, and more. " +
"IMPORTANT: Data must be embedded inline in the spec - external URLs or file references will NOT work. " +
'Use the format: {"data": {"values": [{"x": 1, "y": 2}, ...]}, "mark": "...", "encoding": {...}}. ' +
"If you have data from sql_query or code_interpreter, extract the values and embed them directly. " +
"Use this when the user asks for charts, graphs, or data visualizations.",
parameters: {
type: "object",
properties: {
spec: {
type: "object",
description:
"A Vega-Lite specification object. Must include 'data' with inline 'values' array, 'mark', and 'encoding'. " +
'Example: {"$schema": "https://vega.github.io/schema/vega-lite/v6.json", ' +
'"data": {"values": [{"category": "A", "value": 10}]}, "mark": "bar", ' +
'"encoding": {"x": {"field": "category"}, "y": {"field": "value", "type": "quantitative"}}}',
},
title: {
type: "string",
description: "Optional title for the chart (overrides spec.title if provided)",
},
},
required: ["spec"],
},
});
}
// Add html_render as a function tool (client-side sandboxed HTML preview)
if (enabledTools.includes("html_render")) {
tools.push({
type: "function",
name: "html_render",
description:
"Render HTML content in a sandboxed preview. " +
"Use this to display formatted HTML content, reports, interactive demos, or styled output. " +
"The HTML is rendered in a secure sandboxed iframe with scripts enabled but no external access. " +
"You can include inline CSS for styling. External resources (images, scripts, stylesheets) will not load. " +
"Use this when the user asks for formatted output, HTML reports, or web content previews.",
parameters: {
type: "object",
properties: {
html: {
type: "string",
description:
"The HTML content to render. Can include inline styles and scripts. " +
"Should be valid HTML (fragment or complete document).",
},
title: {
type: "string",
description: "Optional title for the preview",
},
},
required: ["html"],
},
});
}
// Add display_artifacts tool when any artifact-producing tool is enabled
// This allows the model to select which outputs to show prominently
const artifactProducingTools = [
"code_interpreter",
"js_code_interpreter",
"sql_query",
"chart_render",
"html_render",
];
const hasArtifactProducingTool = artifactProducingTools.some((t) =>
enabledTools.includes(t)
);
if (hasArtifactProducingTool) {
tools.push({
type: "function",
name: "display_artifacts",
description:
"After executing tools that produce outputs (code, charts, tables, images), " +
"call this to select which artifacts to display prominently to the user inline at this point in the conversation. " +
"Artifacts not selected will be available in a collapsed 'more outputs' section. " +
"Call this each time you have outputs to show rather than waiting until the end — " +
"artifacts appear where you call this function, so call it right after the relevant tools complete. " +
"Choose the most relevant and interesting outputs - typically final results rather than intermediate steps.",
parameters: {
type: "object",
properties: {
artifacts: {
type: "array",
items: { type: "string" },
description:
"Array of artifact IDs to display prominently, in order of presentation. " +
"Artifact IDs are provided in the tool execution results.",
},
layout: {
type: "string",
enum: ["inline", "gallery", "stacked"],
description:
"How to arrange the displayed artifacts: " +
"'inline' (default) - flows with your text response, " +
"'gallery' - compact thumbnail grid, " +
"'stacked' - full-size vertical stack",
},
},
required: ["artifacts"],
},
});
}
// Add sub_agent tool for delegating investigative tasks
if (enabledTools.includes("sub_agent")) {
tools.push({
type: "function",
name: "sub_agent",
description:
"Delegate a focused research or analysis task to a separate AI agent. " +
"The sub-agent runs in isolation with fresh context and no tool access, " +
"making it ideal for:\n" +
"- Breaking down complex research into focused subtasks\n" +
"- Reducing context size by investigating specific aspects separately\n" +
"- Getting a focused analysis without conversation history baggage\n\n" +
"Only use for substantial investigative tasks that benefit from isolation. " +
"For simple questions, answer directly instead.",
parameters: {
type: "object",
properties: {
task: {
type: "string",
description:
"A clear, detailed description of what to investigate or analyze. " +
"Include all necessary context since the sub-agent cannot see the conversation history.",
},
},
required: ["task"],
},
});
}
// Add wikipedia tool for searching and fetching Wikipedia articles
if (enabledTools.includes("wikipedia")) {
tools.push({
type: "function",
name: "wikipedia",
description:
"Search Wikipedia articles or fetch article summaries. " +
"Use action='search' to find articles matching a query. " +
"Use action='get' to fetch the summary of a specific article by title. " +
"Supports multiple language editions (en, de, fr, es, etc.).",
parameters: {
type: "object",
properties: {
action: {
type: "string",
enum: ["search", "get"],
description:
"'search' to find articles matching a query, 'get' to fetch a specific article summary",
},
query: {
type: "string",
description:
"For action='search': the search query. For action='get': the exact article title (e.g., 'Albert Einstein')",
},
language: {
type: "string",
description:
"Language code for Wikipedia edition (default: 'en'). Examples: 'en', 'de', 'fr', 'es', 'ja', 'zh'",
},
limit: {
type: "number",
description: "Maximum number of search results (default: 5, max: 20)",
},
},
required: ["action", "query"],
},
});
}
// Add wikidata tool for searching and fetching structured data from Wikidata
if (enabledTools.includes("wikidata")) {
tools.push({
type: "function",
name: "wikidata",
description:
"Search and fetch structured data from Wikidata knowledge base. " +
"Use action='search' to find entities (items or properties) by label. " +
"Use action='get' to fetch full entity data by Q-ID (e.g., 'Q42' for Douglas Adams) or P-ID (e.g., 'P31' for 'instance of'). " +
"Returns structured data including labels, descriptions, claims/statements, and Wikipedia links.",
parameters: {
type: "object",
properties: {
action: {
type: "string",
enum: ["search", "get"],
description:
"'search' to find entities by label, 'get' to fetch entity data by ID",
},
query: {
type: "string",
description:
"For action='search': the search query. For action='get': the entity ID (e.g., 'Q42', 'P31')",
},
language: {
type: "string",
description:
"Language code for labels and descriptions (default: 'en'). Examples: 'en', 'de', 'fr'",
},
limit: {
type: "number",
description: "Maximum number of search results (default: 5, max: 20)",
},
type: {
type: "string",
enum: ["item", "property"],
description:
"Entity type filter for search (default: 'item'). 'item' for Q-IDs, 'property' for P-IDs",
},
},
required: ["action", "query"],
},
});
}
// Add web_search tool for searching the live web
if (enabledTools.includes("web_search")) {
tools.push({
type: "function",
name: "web_search",
description:
"Search the web for current information. Returns a list of relevant results with titles, URLs, and content snippets.",
parameters: {
type: "object",
properties: {
query: {
type: "string",
description: "The search query",
},
},
required: ["query"],
},
});
}
// Add web_fetch tool for fetching content from a URL
if (enabledTools.includes("web_fetch")) {
tools.push({
type: "function",
name: "web_fetch",
description:
"Fetch the content of a web page or API endpoint. Returns the text content of the URL. HTML pages are automatically converted to plain text.",
parameters: {
type: "object",
properties: {
url: {
type: "string",
description: "The URL to fetch",
},
max_length: {
type: "number",
description:
"Maximum content length in bytes to return (default: server configured limit)",
},
},
required: ["url"],
},
});
}
// Add MCP tools from connected servers
if (enabledTools.includes("mcp")) {
// Ensure enabled servers are connected before building tools list
await useMCPStore.getState().ensureConnected();
const mcpState = useMCPStore.getState();
for (const server of mcpState.servers) {
// Skip disabled or disconnected servers
if (!server.enabled || server.status !== "connected") continue;
for (const tool of server.tools) {
// Check if this specific tool is enabled (default to enabled)
if (server.toolsEnabled[tool.name] === false) continue;
// Create namespaced tool name to avoid collisions
const mcpToolName = createMCPToolName(server.id, tool.name);
tools.push({
type: "function",
name: mcpToolName,
description:
`[MCP: ${server.name}] ` + (tool.description || `Execute ${tool.name}`),
parameters: tool.inputSchema || {
type: "object",
properties: {},
},
});
}
}
}
// Add tools to request if any are configured
if (tools.length > 0) {
requestBody.tools = tools;
}
const response = await fetch("/api/v1/responses", {
method: "POST",
headers: {
"Content-Type": "application/json",
...(token && { Authorization: `Bearer ${token}` }),
...(projectIdRef.current && { "X-Hadrian-Project": projectIdRef.current }),
},
body: JSON.stringify(requestBody),
signal: abortController.signal,
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(errorText || response.statusText);
}
const reader = response.body?.getReader();
if (!reader) throw new Error("No response body");
const decoder = new TextDecoder();
let content = "";
let reasoningContent = "";
let buffer = "";
let usage: MessageUsage | undefined;
// Fallback: extract tool calls from response.completed if not captured during streaming
let completedToolCalls: ParsedToolCall[] = [];
let hasOutputText = false;
// Capture response output for debugging
let responseOutput: unknown[] | undefined;
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split("\n");
// Keep the last partial line in the buffer
buffer = lines.pop() || "";
for (const line of lines) {
if (line.startsWith("data: ")) {
const data = line.slice(6).trim();
if (!data || data === "[DONE]") continue;
try {
const event = JSON.parse(data) as ResponsesStreamEvent;
// Capture SSE event for debugging if callback provided
if (onSSEEvent) {
onSSEEvent({
type: event.type,
timestamp: Date.now(),
data: event,
});
}
// Track tool calls if enabled
if (toolTracker) {
// Cast to BaseSSEEvent since parseToolCallFromEvent expects that type
const parseResult = parseToolCallFromEvent(
event as { type: string; [key: string]: unknown },
toolTracker
);
if (parseResult.type === "tool_call_added") {
// Update streaming store with new tool call
streamingStore.addToolCall(storeKey, parseResult.toolCall);
} else if (parseResult.type === "tool_call_arguments_delta") {
streamingStore.updateToolCallArguments(
storeKey,
parseResult.id,
parseResult.delta
);
} else if (parseResult.type === "tool_call_complete") {
streamingStore.completeToolCall(
storeKey,
parseResult.toolCall.id,
parseResult.toolCall.arguments as Record<string, unknown>
);
}
}
// Handle different Responses API event types
if (event.type === "response.output_text.delta" && event.delta) {
hasOutputText = true;
content += event.delta;
streamingStore.appendContent(storeKey, event.delta);
} else if (
(event.type === "response.reasoning_text.delta" ||
event.type === "response.reasoning_summary_text.delta") &&
event.delta
) {
// Stream reasoning content (extended thinking)
reasoningContent += event.delta;
streamingStore.appendReasoningContent(storeKey, event.delta);
} else if (
(event.type === "response.reasoning_text.done" ||
event.type === "response.reasoning_summary_text.done") &&
event.text
) {
// Final reasoning text
reasoningContent = event.text;
streamingStore.setReasoningContent(storeKey, reasoningContent);
} else if (event.type === "response.output_text.done") {
// Completion signal only — streamed deltas are authoritative.
} else if (event.type === "response.output_item.done" && event.item) {
// Handle file_search_call output items (server-side file search)
if (event.item.type === "file_search_call" && event.item.results) {
// Convert file_search results to citations
const citations: Citation[] = event.item.results.map(
(
result: {
file_id: string;
filename: string;
score: number;
content?: Array<{ type: string; text: string }>;
},
index: number
): ChunkCitation => ({
id: `citation-${result.file_id}-${index}`,
type: "chunk",
fileId: result.file_id,
filename: result.filename,
score: result.score,
chunkIndex: index,
content: result.content?.[0]?.text ?? "",
})
);
if (citations.length > 0) {
streamingStore.addCitations(storeKey, citations);
}
} else if (event.item.type === "image_generation_call" && event.item.result) {
// Image generation completed - create image artifact from data URL
const artifact: Artifact = {
id: event.item.id ?? `img_${Date.now()}`,
type: "image",
title: "Generated Image",
data: event.item.result,
mimeType: "image/png",
role: "output",
};
streamingStore.addArtifacts(storeKey, [artifact]);
}
} else if (event.type === "response.file_search_call.in_progress") {
// Server-side file search starting - add tool call to streaming store
const itemId = event.item_id ?? `fs_${Date.now()}`;
streamingStore.addToolCall(storeKey, {
id: itemId,
callId: itemId,
name: "file_search",
outputIndex: event.output_index ?? 0,
argumentsBuffer: "",
status: "pending",
});
} else if (event.type === "response.file_search_call.searching") {
// Server-side file search actively searching - update status
if (event.item_id) {
streamingStore.updateToolCallArguments(storeKey, event.item_id, "");
}
} else if (event.type === "response.file_search_call.completed") {
// Server-side file search completed - remove the tool call indicator
if (event.item_id) {
streamingStore.completeToolCall(storeKey, event.item_id, {});
}
} else if (event.type === "response.image_generation_call.in_progress") {
// Image generation starting - show tool call indicator
const itemId = event.item_id ?? `img_${Date.now()}`;
streamingStore.addToolCall(storeKey, {
id: itemId,
callId: itemId,
name: "image_generation",
outputIndex: event.output_index ?? 0,
argumentsBuffer: "",
status: "pending",
});
} else if (event.type === "response.image_generation_call.generating") {
// Image generation in progress - update status
if (event.item_id) {
streamingStore.updateToolCallArguments(storeKey, event.item_id, "");
}
} else if (event.type === "response.image_generation_call.partial_image") {
// Progressive image preview
if (event.partial_image_b64) {
const dataUrl = `data:image/png;base64,${event.partial_image_b64}`;
const artifact: Artifact = {
id: event.item_id ?? `img_partial_${Date.now()}`,
type: "image",
title: "Generated Image",
data: dataUrl,
mimeType: "image/png",