Skip to content

Commit 4bba8f1

Browse files
committed
Enable chatbot to query data structures in file
1 parent f1d7d1b commit 4bba8f1

7 files changed

Lines changed: 521 additions & 52 deletions

File tree

‎src/components/chatbot/copilot-resources.tsx‎

Lines changed: 3 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,14 @@ import { defaultVizSettings } from 'explorviz-frontend/src/utils/settings/defaul
1515
import { VisualizationSettings } from 'explorviz-frontend/src/utils/settings/settings-schemas';
1616
import { use } from 'react';
1717
import { toIsoTime } from './chart-query';
18+
import { summarizeCities } from './landscape-query';
1819

1920
const ASSISTANT_INSTRUCTIONS = `You are the assistant embedded in ExplorViz, a tool that visualizes software systems from static and dynamic program analysis as a 3D landscape using the city metaphor.
2021
2122
Model:
2223
- City: the top-level unit, e.g. an application, service, or repository.
2324
- District: a grouping inside a city, e.g. a package or directory. Districts can be nested. A closed district hides its content.
24-
- Building: a leaf, e.g. a source file or class, with metrics such as lines of code.
25+
- Building: a leaf, e.g. a source file or class, with metrics such as lines of code. What is inside a file (imports, functions, data structures) is available from query-file-data.
2526
- Commit chart: the analyzed commits of the repositories. Selected commits determine which code is visualized; two of a repository are compared, the older one with the newer one.
2627
- Runtime chart: Timestamps with the number of spans that start until the next one. The selected Timestamp determines which runtime data is visualized.
2728
By default all districts are open and nothing is highlighted.
@@ -74,45 +75,6 @@ export function CopilotResources({ cities }: CopilotResourcesProps) {
7475
return result;
7576
};
7677

77-
const summarizeCities = (cities: City[]) =>
78-
cities.map((city) => {
79-
const districtCount = city.allContainedDistrictIds.length;
80-
const buildingCount = city.allContainedBuildingIds.length;
81-
let languages: string[] = [];
82-
let functionCount = 0;
83-
let linesOfCode = 0;
84-
let sourceCodeLines = 0;
85-
let commentedLines = 0;
86-
let combinedFileSizeInBytes = 0;
87-
88-
city.allContainedBuildingIds.forEach((buildingId) => {
89-
const building = useModelStore.getState().getBuilding(buildingId);
90-
const language = building?.language;
91-
functionCount += building?.metrics?.functionCount?.current ?? 0;
92-
linesOfCode += building?.metrics?.lineCount?.current ?? 0;
93-
sourceCodeLines += building?.metrics?.sloc?.current ?? 0;
94-
commentedLines += building?.metrics?.cloc?.current ?? 0;
95-
combinedFileSizeInBytes += building?.metrics?.size?.current ?? 0;
96-
if (language && !languages.includes(language)) {
97-
languages.push(language);
98-
}
99-
});
100-
101-
return {
102-
id: city.id,
103-
name: city.name,
104-
languages,
105-
originOfData: city.originOfData,
106-
districtCount,
107-
buildingCount,
108-
functionCount,
109-
linesOfCode,
110-
sourceCodeLines,
111-
commentedLines,
112-
combinedFileSizeInBytes,
113-
};
114-
});
115-
11678
const { showToolsSidebar, showSettingsSidebar, selectedToolbarTool, selectedSettingsSidebarTab } =
11779
use(ChatbotContext);
11880

@@ -131,7 +93,7 @@ export function CopilotResources({ cities }: CopilotResourcesProps) {
13193

13294
useAgentContext({
13395
description: 'Cities of the landscape with their totals. For anything more detailed use query-landscape-data.',
134-
value: JSON.stringify(summarizeCities(cities ?? [])),
96+
value: JSON.stringify(summarizeCities(cities ?? [], useModelStore.getState().getBuilding)),
13597
});
13698

13799
useAgentContext({

‎src/components/chatbot/copilot-tools.tsx‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
isSelectSetting,
1717
VisualizationSettings,
1818
} from 'explorviz-frontend/src/utils/settings/settings-schemas';
19+
import { requestFileDetailedData } from 'explorviz-frontend/src/utils/landscape-http-request-util';
1920
import { pingByModelId } from 'explorviz-frontend/src/view-objects/3d/city/ping-animation';
2021
import * as htmlToImage from 'html-to-image';
2122
import { use } from 'react';
@@ -40,6 +41,7 @@ import {
4041
resolveCopilotSettingsTab,
4142
resolveCopilotToolbarTool,
4243
} from './copilot-sidebar-map';
44+
import { DEFAULT_MAX_ENTRIES, FILE_SECTIONS, MAX_FILES, queryFiles } from './file-query';
4345
import {
4446
DEFAULT_MAX_BUILDINGS,
4547
DEFAULT_MAX_DISTRICTS,
@@ -230,6 +232,54 @@ export function CopilotTools() {
230232
},
231233
});
232234

235+
useChatbotTool({
236+
name: 'query-file-data',
237+
description: `Inspects files (buildings from static analysis): their imports, functions, and data structures (classes, interfaces, enums, etc.) with superclasses, fields, and functions. Only reads, opens nothing. Functions are given as "name: return type", fields as "name: type". Data structures inside others are named "Outer.Inner". "counts" are the totals of the file, "omitted" states how many matches were cut off. Not available: source code, function parameters, enum values, and other versions of a file than the one in the landscape (while two commits are compared, the newer one; for removed files the older one). Inspect only files that the question is about, do not scan the landscape file by file.`,
238+
parameters: z.object({
239+
ids: z.array(z.string()).describe(`Building ids from query-landscape-data, at most ${MAX_FILES}.`),
240+
sections: z
241+
.array(z.enum(FILE_SECTIONS))
242+
.optional()
243+
.describe(
244+
'Default: all. functions: top-level functions and functions of data structures. dataStructures: their type, superclasses, and fields.'
245+
),
246+
search: z
247+
.string()
248+
.optional()
249+
.describe(
250+
'Only imports, functions, fields, and data structures whose name or type contains this. A data structure whose name contains it is returned completely.'
251+
),
252+
includeMetrics: z
253+
.boolean()
254+
.optional()
255+
.describe('Also metrics of the file, its functions, and its data structures. Default false.'),
256+
maxEntries: z.number().optional().describe(`Per file. Default ${DEFAULT_MAX_ENTRIES}.`),
257+
}),
258+
// @ts-ignore
259+
_isRenderAndWait: true,
260+
handler: async (query, { agent, toolCall }) => {
261+
const { getBuilding } = useModelStore.getState();
262+
const result = JSON.stringify(await queryFiles(query, getBuilding, (id) => requestFileDetailedData(id)));
263+
return referenceEarlierResult(result, agent?.messages ?? [], toolCall.id);
264+
},
265+
render: ({ status, args, result }) => {
266+
const ids = args.ids ?? [];
267+
const building = ids.length === 1 && ids[0] ? useModelStore.getState().getBuilding(ids[0]) : undefined;
268+
return (
269+
<ToolCallCard
270+
status={status}
271+
action="queryFileData"
272+
errorMessage={getErrorMessage(result)}
273+
component={
274+
building
275+
? { id: building.id, name: building.name }
276+
: { name: ids.length > 0 ? `${ids.length} ${ids.length === 1 ? 'file' : 'files'}` : undefined }
277+
}
278+
/>
279+
);
280+
},
281+
});
282+
233283
useChatbotTool({
234284
name: 'query-commit-chart',
235285
description:
Lines changed: 185 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,185 @@
1+
import {
2+
ClazzDto,
3+
FieldDto,
4+
FileDetailedDto,
5+
FunctionDto,
6+
} from 'explorviz-frontend/src/utils/landscape-schemes/file-detailed-data';
7+
import { Building } from 'explorviz-frontend/src/utils/landscape-schemes/flat-landscape';
8+
import { TypeOfAnalysis } from 'explorviz-frontend/src/utils/landscape-schemes/structure-data';
9+
10+
export const FILE_SECTIONS = ['imports', 'functions', 'dataStructures'] as const;
11+
export type FileSection = (typeof FILE_SECTIONS)[number];
12+
13+
/** Every file is a request to the landscape service. */
14+
export const MAX_FILES = 10;
15+
export const DEFAULT_MAX_ENTRIES = 100;
16+
17+
export interface FileQuery {
18+
ids: string[];
19+
sections?: FileSection[];
20+
search?: string;
21+
includeMetrics?: boolean;
22+
maxEntries?: number;
23+
}
24+
25+
type Entry = Record<string, unknown>;
26+
27+
/** Drops absent values and empty lists so they cost no tokens. */
28+
function compact(entry: Entry): Entry {
29+
return Object.fromEntries(
30+
Object.entries(entry).filter(
31+
([, value]) => value !== undefined && value !== null && !(Array.isArray(value) && value.length === 0)
32+
)
33+
);
34+
}
35+
36+
/** The service returns these lists in no particular order, which would make equal results look different. */
37+
function sortedByName<T extends { name: string }>(items: T[] | null | undefined): T[] {
38+
return [...(items ?? [])].sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
39+
}
40+
41+
interface DataStructure {
42+
/** Includes the names of the data structures it is nested in. */
43+
name: string;
44+
clazz: ClazzDto;
45+
}
46+
47+
function flatten(classes: ClazzDto[] | null | undefined, prefix = ''): DataStructure[] {
48+
return sortedByName(classes).flatMap((clazz) => {
49+
const name = prefix + clazz.name;
50+
return [{ name, clazz }, ...flatten(clazz.innerClasses, `${name}.`)];
51+
});
52+
}
53+
54+
/** Counts down how many entries may still be listed for a file. */
55+
class Budget {
56+
omitted: Partial<Record<FileSection, number>> = {};
57+
58+
constructor(private remaining: number) {}
59+
60+
take<T>(section: FileSection, items: T[]): T[] {
61+
const taken = items.slice(0, this.remaining);
62+
this.remaining -= taken.length;
63+
if (taken.length < items.length) {
64+
this.omitted[section] = (this.omitted[section] ?? 0) + items.length - taken.length;
65+
}
66+
return taken;
67+
}
68+
}
69+
70+
/** Selects the requested data of one file. The same function serves functions of files and of data structures. */
71+
export function describeFile(file: FileDetailedDto, query: Omit<FileQuery, 'ids'>): Entry {
72+
const sections = new Set<FileSection>(query.sections?.length ? query.sections : FILE_SECTIONS);
73+
const search = query.search?.trim().toLowerCase() ?? '';
74+
const matches = (...texts: (string | null | undefined)[]) =>
75+
!search || texts.some((text) => text?.toLowerCase().includes(search));
76+
const maxEntries = query.maxEntries;
77+
const budget = new Budget(
78+
typeof maxEntries === 'number' && maxEntries >= 0 ? Math.floor(maxEntries) : DEFAULT_MAX_ENTRIES
79+
);
80+
81+
const toFunction = ({ name, returnType, metrics }: FunctionDto) => {
82+
const signature = returnType ? `${name}: ${returnType}` : name;
83+
return query.includeMetrics ? { function: signature, metrics } : signature;
84+
};
85+
const toField = ({ name, type }: FieldDto) => (type ? `${name}: ${type}` : name);
86+
const listFunctions = (functions: FunctionDto[] | null | undefined, takeAll = false) =>
87+
sections.has('functions')
88+
? budget
89+
.take(
90+
'functions',
91+
sortedByName(functions).filter(({ name, returnType }) => takeAll || matches(name, returnType))
92+
)
93+
.map(toFunction)
94+
: [];
95+
96+
const imports = sections.has('imports')
97+
? budget.take(
98+
'imports',
99+
[...(file.importNames ?? [])].sort().filter((name) => matches(name))
100+
)
101+
: [];
102+
const functions = listFunctions(file.functions);
103+
104+
const dataStructures = flatten(file.classes).flatMap(({ name, clazz }) => {
105+
// A data structure that is searched for is returned with everything in it.
106+
const isMatch = matches(name);
107+
const superclasses = clazz.superclassFqns ?? [];
108+
const hasMatchingSuperclass = sections.has('dataStructures') && matches(...superclasses);
109+
const matchingFields = sections.has('dataStructures')
110+
? sortedByName(clazz.fields).filter((field) => isMatch || matches(field.name, field.type))
111+
: [];
112+
const hasMatchingFunction =
113+
sections.has('functions') && (clazz.functions ?? []).some((fn) => isMatch || matches(fn.name, fn.returnType));
114+
const isListed =
115+
(isMatch && sections.has('dataStructures')) ||
116+
(search !== '' && hasMatchingSuperclass) ||
117+
matchingFields.length > 0 ||
118+
hasMatchingFunction;
119+
if (!isListed || budget.take('dataStructures', [clazz]).length === 0) {
120+
return [];
121+
}
122+
return [
123+
compact({
124+
name,
125+
type: clazz.type,
126+
...(sections.has('dataStructures') && {
127+
superclasses: [...superclasses].sort(),
128+
fields: budget.take('dataStructures', matchingFields).map(toField),
129+
metrics: query.includeMetrics ? clazz.metrics : undefined,
130+
}),
131+
functions: listFunctions(clazz.functions, isMatch),
132+
}),
133+
];
134+
});
135+
136+
return compact({
137+
language: file.language,
138+
package: file.packageName || undefined,
139+
metrics: query.includeMetrics ? file.metrics : undefined,
140+
// Totals, so that the chatbot can tell "none" from "none that match".
141+
counts: {
142+
imports: file.importNames?.length ?? 0,
143+
topLevelFunctions: file.functions?.length ?? 0,
144+
dataStructures: flatten(file.classes).length,
145+
},
146+
imports,
147+
functions,
148+
dataStructures,
149+
omitted: Object.keys(budget.omitted).length > 0 ? budget.omitted : undefined,
150+
});
151+
}
152+
153+
function hasFileData({ originOfData }: Building) {
154+
return originOfData === TypeOfAnalysis.Static || originOfData === TypeOfAnalysis.StaticAndRuntime;
155+
}
156+
157+
/**
158+
* Loads and describes files. A file that cannot be inspected is reported in its
159+
* place, so it does not keep the chatbot from getting the others.
160+
*/
161+
export async function queryFiles(
162+
query: FileQuery,
163+
getBuilding: (id: string) => Building | undefined,
164+
requestFile: (id: string) => Promise<FileDetailedDto>
165+
): Promise<{ files: Entry[]; omittedIds?: string[] }> {
166+
const ids = [...new Set(query.ids)];
167+
const files = await Promise.all(
168+
ids.slice(0, MAX_FILES).map(async (id) => {
169+
const building = getBuilding(id);
170+
if (!building) {
171+
return { id, error: 'Not the id of a building. Look up the id with query-landscape-data.' };
172+
}
173+
const name = building.fqn ?? building.name;
174+
if (!hasFileData(building)) {
175+
return { id, name, error: 'Has no file data: it does not come from static analysis.' };
176+
}
177+
try {
178+
return { id, name, ...describeFile(await requestFile(id), query) };
179+
} catch (error) {
180+
return { id, name, error: error instanceof Error ? error.message : String(error) };
181+
}
182+
})
183+
);
184+
return { files, ...(ids.length > MAX_FILES && { omittedIds: ids.slice(MAX_FILES) }) };
185+
}

0 commit comments

Comments
 (0)