pipelinesTable.tsx 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  1. import styled from '@emotion/styled';
  2. import type {Location} from 'history';
  3. import * as qs from 'query-string';
  4. import GridEditable, {
  5. COL_WIDTH_UNDEFINED,
  6. type GridColumnHeader,
  7. } from 'sentry/components/gridEditable';
  8. import Link from 'sentry/components/links/link';
  9. import type {CursorHandler} from 'sentry/components/pagination';
  10. import Pagination from 'sentry/components/pagination';
  11. import SearchBar from 'sentry/components/searchBar';
  12. import {Tooltip} from 'sentry/components/tooltip';
  13. import {IconInfo} from 'sentry/icons';
  14. import {t} from 'sentry/locale';
  15. import {space} from 'sentry/styles/space';
  16. import type {Organization} from 'sentry/types/organization';
  17. import {browserHistory} from 'sentry/utils/browserHistory';
  18. import type {EventsMetaType} from 'sentry/utils/discover/eventView';
  19. import {getFieldRenderer} from 'sentry/utils/discover/fieldRenderers';
  20. import type {Sort} from 'sentry/utils/discover/fields';
  21. import {RATE_UNIT_TITLE, RateUnit} from 'sentry/utils/discover/fields';
  22. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  23. import {decodeScalar, decodeSorts} from 'sentry/utils/queryString';
  24. import {MutableSearch} from 'sentry/utils/tokenizeSearch';
  25. import {useLocation} from 'sentry/utils/useLocation';
  26. import useOrganization from 'sentry/utils/useOrganization';
  27. import {useModuleURL} from 'sentry/views/performance/utils/useModuleURL';
  28. import {renderHeadCell} from 'sentry/views/starfish/components/tableCells/renderHeadCell';
  29. import {useSpanMetrics} from 'sentry/views/starfish/queries/useDiscover';
  30. import type {SpanMetricsResponse} from 'sentry/views/starfish/types';
  31. import {QueryParameterNames} from 'sentry/views/starfish/views/queryParameters';
  32. type Row = Pick<
  33. SpanMetricsResponse,
  34. | 'project.id'
  35. | 'span.description'
  36. | 'span.group'
  37. | 'spm()'
  38. | 'avg(span.duration)'
  39. | 'sum(span.duration)'
  40. | 'sum(ai.total_tokens.used)'
  41. | 'sum(ai.total_cost)'
  42. >;
  43. type Column = GridColumnHeader<
  44. | 'span.description'
  45. | 'spm()'
  46. | 'avg(span.duration)'
  47. | 'sum(ai.total_tokens.used)'
  48. | 'sum(ai.total_cost)'
  49. >;
  50. const COLUMN_ORDER: Column[] = [
  51. {
  52. key: 'span.description',
  53. name: t('AI Pipeline Name'),
  54. width: COL_WIDTH_UNDEFINED,
  55. },
  56. {
  57. key: 'sum(ai.total_tokens.used)',
  58. name: t('Total tokens used'),
  59. width: 180,
  60. },
  61. {
  62. key: 'sum(ai.total_cost)',
  63. name: t('Total cost'),
  64. width: 180,
  65. },
  66. {
  67. key: `avg(span.duration)`,
  68. name: t('Pipeline Duration'),
  69. width: COL_WIDTH_UNDEFINED,
  70. },
  71. {
  72. key: 'spm()',
  73. name: `${t('Pipeline runs')} ${RATE_UNIT_TITLE[RateUnit.PER_MINUTE]}`,
  74. width: COL_WIDTH_UNDEFINED,
  75. },
  76. ];
  77. const SORTABLE_FIELDS = ['sum(ai.total_tokens.used)', 'avg(span.duration)', 'spm()'];
  78. type ValidSort = Sort & {
  79. field: 'spm()' | 'avg(span.duration)';
  80. };
  81. export function isAValidSort(sort: Sort): sort is ValidSort {
  82. return (SORTABLE_FIELDS as unknown as string[]).includes(sort.field);
  83. }
  84. export function PipelinesTable() {
  85. const location = useLocation();
  86. const moduleURL = useModuleURL('ai');
  87. const organization = useOrganization();
  88. const cursor = decodeScalar(location.query?.[QueryParameterNames.SPANS_CURSOR]);
  89. const sortField = decodeScalar(location.query?.[QueryParameterNames.SPANS_SORT]);
  90. const spanDescription = decodeScalar(location.query?.['span.description'], '');
  91. let sort = decodeSorts(sortField).filter(isAValidSort)[0];
  92. if (!sort) {
  93. sort = {field: 'spm()', kind: 'desc'};
  94. }
  95. const {data, isLoading, meta, pageLinks, error} = useSpanMetrics(
  96. {
  97. search: MutableSearch.fromQueryObject({
  98. 'span.category': 'ai.pipeline',
  99. 'span.description': spanDescription ? `*${spanDescription}*` : undefined,
  100. }),
  101. fields: [
  102. 'project.id',
  103. 'span.group',
  104. 'span.description',
  105. 'spm()',
  106. 'avg(span.duration)',
  107. 'sum(span.duration)',
  108. ],
  109. sorts: [sort],
  110. limit: 25,
  111. cursor,
  112. },
  113. 'api.ai-pipelines.view'
  114. );
  115. const {data: tokensUsedData, isLoading: tokensUsedLoading} = useSpanMetrics(
  116. {
  117. search: new MutableSearch(
  118. `span.category:ai span.ai.pipeline.group:[${(data as Row[])?.map(x => x['span.group']).join(',')}]`
  119. ),
  120. fields: [
  121. 'span.ai.pipeline.group',
  122. 'sum(ai.total_tokens.used)',
  123. 'sum(ai.total_cost)',
  124. ],
  125. },
  126. 'api.performance.ai-analytics.token-usage-chart'
  127. );
  128. const rows: Row[] = (data as Row[]).map(baseRow => {
  129. const row: Row = {
  130. ...baseRow,
  131. 'sum(ai.total_tokens.used)': 0,
  132. 'sum(ai.total_cost)': 0,
  133. };
  134. if (!tokensUsedLoading) {
  135. const tokenUsedDataPoint = tokensUsedData.find(
  136. tokenRow => tokenRow['span.ai.pipeline.group'] === row['span.group']
  137. );
  138. if (tokenUsedDataPoint) {
  139. row['sum(ai.total_tokens.used)'] =
  140. tokenUsedDataPoint['sum(ai.total_tokens.used)'];
  141. row['sum(ai.total_cost)'] = tokenUsedDataPoint['sum(ai.total_cost)'];
  142. }
  143. }
  144. return row;
  145. });
  146. const handleCursor: CursorHandler = (newCursor, pathname, query) => {
  147. browserHistory.push({
  148. pathname,
  149. query: {...query, [QueryParameterNames.SPANS_CURSOR]: newCursor},
  150. });
  151. };
  152. const handleSearch = (newQuery: string) => {
  153. browserHistory.push({
  154. ...location,
  155. query: {
  156. ...location.query,
  157. 'span.description': newQuery === '' ? undefined : newQuery,
  158. [QueryParameterNames.SPANS_CURSOR]: undefined,
  159. },
  160. });
  161. };
  162. return (
  163. <VisuallyCompleteWithData
  164. id="PipelinesTable"
  165. hasData={rows.length > 0}
  166. isLoading={isLoading}
  167. >
  168. <Container>
  169. <SearchBar
  170. placeholder={t('Search for pipeline')}
  171. query={spanDescription}
  172. onSearch={handleSearch}
  173. />
  174. <GridEditable
  175. isLoading={isLoading}
  176. error={error}
  177. data={rows}
  178. columnOrder={COLUMN_ORDER}
  179. columnSortBy={[
  180. {
  181. key: sort.field,
  182. order: sort.kind,
  183. },
  184. ]}
  185. grid={{
  186. renderHeadCell: column =>
  187. renderHeadCell({
  188. column,
  189. sort,
  190. location,
  191. sortParameterName: QueryParameterNames.SPANS_SORT,
  192. }),
  193. renderBodyCell: (column, row) =>
  194. renderBodyCell(moduleURL, column, row, meta, location, organization),
  195. }}
  196. />
  197. <Pagination pageLinks={pageLinks} onCursor={handleCursor} />
  198. </Container>
  199. </VisuallyCompleteWithData>
  200. );
  201. }
  202. function renderBodyCell(
  203. moduleURL: string,
  204. column: Column,
  205. row: Row,
  206. meta: EventsMetaType | undefined,
  207. location: Location,
  208. organization: Organization
  209. ) {
  210. if (column.key === 'span.description') {
  211. if (!row['span.description']) {
  212. return <span>(unknown)</span>;
  213. }
  214. if (!row['span.group']) {
  215. return <span>{row['span.description']}</span>;
  216. }
  217. const queryString = {
  218. ...location.query,
  219. 'span.description': row['span.description'],
  220. };
  221. return (
  222. <Link
  223. to={`${moduleURL}/pipeline-type/${row['span.group']}?${qs.stringify(queryString)}`}
  224. >
  225. {row['span.description']}
  226. </Link>
  227. );
  228. }
  229. if (column.key === 'sum(ai.total_cost)') {
  230. const cost = row[column.key];
  231. if (cost) {
  232. return <span>US ${cost.toFixed(3)}</span>;
  233. }
  234. return (
  235. <span>
  236. Unknown{' '}
  237. <Tooltip
  238. title={t(
  239. "Cost is calculated for some of the most popular models, but some providers aren't yet supported."
  240. )}
  241. isHoverable
  242. >
  243. <IconInfo size="xs" />
  244. </Tooltip>
  245. </span>
  246. );
  247. }
  248. if (!meta || !meta?.fields) {
  249. return row[column.key];
  250. }
  251. const renderer = getFieldRenderer(column.key, meta.fields, false);
  252. const rendered = renderer(row, {
  253. location,
  254. organization,
  255. unit: meta.units?.[column.key],
  256. });
  257. return rendered;
  258. }
  259. const Container = styled('div')`
  260. display: flex;
  261. flex-direction: column;
  262. gap: ${space(1)};
  263. `;