import React, { ComponentProps, CSSProperties, ReactElement, ReactNode, FunctionComponent, HTMLProps } from 'react'; import { UnaryFunction, Observable, Subscription } from 'rxjs'; import { monacoTypes, Monaco, ButtonProps, Field, PopoverContent, Switch, SelectCommonProps } from '@grafana/ui'; import { DataSourceJsonData, DataSourceSettings, RegistryItem, SelectableValue, DataSourceApi, TimeRange, Registry, DataQuery, PanelData } from '@grafana/data'; import { Grammar } from 'prismjs'; interface OpenAIHealthDetails { configured: boolean; ok: boolean; error?: string; models?: Record; } interface OpenAIModelHealthDetails { ok: boolean; error?: string; } interface VectorHealthDetails { enabled: boolean; ok: boolean; error?: string; } /** * OpenAI API client. * * This module contains functions used to make requests to the OpenAI API via * the Grafana LLM app plugin. That plugin must be installed, enabled and configured * in order for these functions to work. * * The {@link enabled} function can be used to check if the plugin is enabled and configured. */ /** The role of a message's author. */ type Role = 'system' | 'user' | 'assistant' | 'function'; /** A message in a conversation. */ interface Message { /** The role of the message's author. */ role: Role; /** The contents of the message. content is required for all messages, and may be null for assistant messages with function calls. */ content: string; /** * The name of the author of this message. * * This is required if role is 'function', and it should be the name of the function whose response is in the content. * * May contain a-z, A-Z, 0-9, and underscores, with a maximum length of 64 characters. */ name?: string; /** * The name and arguments of a function that should be called, as generated by the model. */ function_call?: Object; } /** A function the model may generate JSON inputs for. */ interface Function { /** * The name of the function to be called. * * Must be a-z, A-Z, 0-9, or contain underscores and dashes, with a maximum length of 64. */ name: string; /** * A description of what the function does, used by the model to choose when and how to call the function. */ description?: string; parameters: Object; } interface ChatCompletionsRequest { /** * ID of the model to use. * * See the model endpoint compatibility table for details on which models work with the Chat Completions API. */ model: string; /** A list of messages comprising the conversation so far. */ messages: Message[]; /** A list of functions the model may generate JSON inputs for. */ functions?: Function[]; /** * Controls how the model responds to function calls. * * "none" means the model does not call a function, and responds to the end-user. * "auto" means the model can pick between an end-user or calling a function. * Specifying a particular function via {"name": "my_function"} forces the model to call that function. * * "none" is the default when no functions are present. "auto" is the default if functions are present. */ function_call?: 'none' | 'auto' | { name: string; }; /** * What sampling temperature to use, between 0 and 2. * Higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic. * * We generally recommend altering this or top_p but not both. */ temperature?: number; /** * An alternative to sampling with temperature, called nucleus sampling, where the model considers the results of the tokens with top_p probability mass. * So 0.1 means only the tokens comprising the top 10% probability mass are considered. * * We generally recommend altering this or temperature but not both. */ top_p?: number; /** * How many chat completion choices to generate for each input message. */ n?: number; /** * Up to 4 sequences where the API will stop generating further tokens. */ stop?: string | string[]; /** * The maximum number of tokens to generate in the chat completion. * * The total length of input tokens and generated tokens is limited by the model's context length. Example Python code for counting tokens. */ max_tokens?: number; /** * Number between -2.0 and 2.0. * * Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics. */ presence_penalty?: number; /** * Number between -2.0 and 2.0. * * Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim. */ frequency_penalty?: number; /** * Modify the likelihood of specified tokens appearing in the completion. * * Accepts a json object that maps tokens (specified by their token ID in the tokenizer) to an associated bias value from -100 to 100. * Mathematically, the bias is added to the logits generated by the model prior to sampling. The exact effect will vary per model, * but values between -1 and 1 should decrease or increase likelihood of selection; values like -100 or 100 should result in a ban * or exclusive selection of the relevant token. */ logit_bias?: { [key: string]: number; }; /** * A unique identifier representing your end-user, which can help OpenAI to monitor and detect abuse. */ user?: string; } /** A completion object from an OpenAI model. */ interface Choice { /** The message object generated by the model. */ message: Message; /** * The reason the model stopped generating text. * * This may be one of: * - stop: API returned complete message, or a message terminated by one of the stop sequences provided via the stop parameter * - length: incomplete model output due to max_tokens parameter or token limit * - function_call: the model decided to call a function * - content_filter: omitted content due to a flag from our content filters * - null: API response still in progress or incomplete */ finish_reason: string; /** The index of the completion in the list of choices. */ index: number; } /** The usage statistics for a request to OpenAPI. */ interface Usage { /** The number of tokens in the prompt. */ prompt_tokens: number; /** The number of tokens in the completion. */ completion_tokens: number; /** The total number of tokens. */ total_tokens: number; } /** The error response from the Grafana LLM app when trying to call the chat completions API. */ interface ChatCompletionsErrorResponse { /** The error message. */ error: string; } /** A response from the OpenAI Chat Completions API. */ interface ChatCompletionsResponse { /** The ID of the request. */ id: string; /** The type of object returned (e.g. 'chat.completion'). */ object: string; /** The timestamp of the request, as a UNIX timestamp. */ created: number; /** The name of the model used to generate the response. */ model: string; /** A list of completion objects (only one, unless `n > 1` in the request). */ choices: T[]; /** The number of tokens used to generate the replies, counting prompt, completion, and total. */ usage: Usage; } /** A content message returned from the model. */ interface ContentMessage { /** The content of the message. */ content: string; } /** A message returned from the model indicating that it is done. */ interface DoneMessage { done: boolean; } /** A function call message returned from the model. */ interface FunctionCallMessage { /** The name of the function to call. */ name: string; /** The arguments to the function call. */ arguments: any[]; } /** * A delta returned from a stream of chat completion responses. * * In practice this will be either a content message or a function call; * done messages are filtered out by the `streamChatCompletions` function. */ type ChatCompletionsDelta = ContentMessage | FunctionCallMessage | DoneMessage; /** A chunk included in a chat completion response. */ interface ChatCompletionsChunk { /** The delta since the previous chunk. */ delta: ChatCompletionsDelta; } /** Return true if the message is a 'content' message. */ declare function isContentMessage(message: ChatCompletionsDelta): message is ContentMessage; /** Return true if the message is a 'done' message. */ declare function isDoneMessage(message: ChatCompletionsDelta): message is DoneMessage; /** Return true if the response is an error response. */ declare function isErrorResponse(response: ChatCompletionsResponse | ChatCompletionsErrorResponse): response is ChatCompletionsErrorResponse; /** * An rxjs operator that extracts the content messages from a stream of chat completion responses. * * @returns An observable that emits the content messages. Each emission will be a string containing the * token emitted by the model. * @example Example of reading all tokens in a stream. * const stream = streamChatCompletions({ model: 'gpt-3.5-turbo', messages: [ * { role: 'system', content: 'You are a great bot.' }, * { role: 'user', content: 'Hello, bot.' }, * ]}).pipe(extractContent()); * stream.subscribe({ next: console.log, error: console.error }); * // Output: * // ['Hello', '? ', 'How ', 'are ', 'you', '?'] */ declare function extractContent(): UnaryFunction>, Observable>; /** * An rxjs operator that accumulates the content messages from a stream of chat completion responses. * * @returns An observable that emits the accumulated content messages. Each emission will be a string containing the * content of all messages received so far. * @example * const stream = streamChatCompletions({ model: 'gpt-3.5-turbo', messages: [ * { role: 'system', content: 'You are a great bot.' }, * { role: 'user', content: 'Hello, bot.' }, * ]}).pipe(accumulateContent()); * stream.subscribe({ next: console.log, error: console.error }); * // Output: * // ['Hello', 'Hello! ', 'Hello! How ', 'Hello! How are ', 'Hello! How are you', 'Hello! How are you?'] */ declare function accumulateContent(): UnaryFunction>, Observable>; /** * Make a request to OpenAI's chat-completions API via the Grafana LLM plugin proxy. */ declare function chatCompletions(request: ChatCompletionsRequest): Promise; /** * Make a streaming request to OpenAI's chat-completions API via the Grafana LLM plugin proxy. * * A stream of tokens will be returned as an `Observable`. Use the `extractContent` operator to * filter the stream to only content messages, or the `accumulateContent` operator to obtain a stream of * accumulated content messages. * * The 'done' message will not be emitted; the stream will simply end when this message is encountered. * * @example Example of reading all tokens in a stream. * const stream = streamChatCompletions({ model: 'gpt-3.5-turbo', messages: [ * { role: 'system', content: 'You are a great bot.' }, * { role: 'user', content: 'Hello, bot.' }, * ]}).pipe(extractContent()); * stream.subscribe({ next: console.log, error: console.error }); * // Output: * // ['Hello', '? ', 'How ', 'are ', 'you', '?'] * * @example Example of accumulating tokens in a stream. * const stream = streamChatCompletions({ model: 'gpt-3.5-turbo', messages: [ * { role: 'system', content: 'You are a great bot.' }, * { role: 'user', content: 'Hello, bot.' }, * ]}).pipe(accumulateContent()); * stream.subscribe({ next: console.log, error: console.error }); * // Output: * // ['Hello', 'Hello! ', 'Hello! How ', 'Hello! How are ', 'Hello! How are you', 'Hello! How are you?'] */ declare function streamChatCompletions(request: ChatCompletionsRequest): Observable>; /** Check if the OpenAI API is enabled via the LLM plugin. */ declare const health$1: () => Promise; declare const enabled$1: () => Promise; /** * Enum representing different states for a stream. * @enum {string} */ declare enum StreamStatus { IDLE = "idle", GENERATING = "generating", COMPLETED = "completed" } /** * A constant representing the timeout value in milliseconds. * @type {number} */ declare const TIMEOUT = 10000; /** * A type representing the state of an OpenAI stream. * @typedef {Object} OpenAIStreamState * @property {React.Dispatch} setMessages - A function to set messages. * @property {string} reply - The reply associated with the stream. * @property {typeof StreamStatus} streamStatus - The current status of the stream. * @property {Error|undefined} error - An optional error associated with the stream. * @property {{ * enabled: boolean|undefined; * stream?: undefined; * }|{ * enabled: boolean|undefined; * stream: Subscription; * }|undefined} value - A value that can be an object with 'enabled' and 'stream' properties or undefined. */ type OpenAIStreamState = { setMessages: React.Dispatch>; reply: string; streamStatus: StreamStatus; error: Error | undefined; value: { enabled: boolean | undefined; stream?: undefined; } | { enabled: boolean | undefined; stream: Subscription; } | undefined; }; /** * A custom React hook for managing an OpenAI stream that communicates with the provided model. * * @param {string} [model=DEFAULT_OAI_MODEL] - The OpenAI model to use for communication. * @param {number} [temperature=1] - The temperature value for text generation (default is 1). * @param {function} [notifyError] - A callback function for handling errors. * * @returns {OpenAIStreamState} - An object containing the state of the OpenAI stream. * @property {function} setMessages - A function to update the list of messages in the stream. * @property {string} reply - The most recent reply received from the OpenAI stream. * @property {StreamStatus} streamStatus - The status of the stream ("idle", "generating" or "completed"). * @property {Error|undefined} error - An error object if an error occurs, or undefined if no error. * @property {object|undefined} value - The current value of the stream. * @property {boolean|undefined} value.enabled - Indicates whether the stream is enabled (true or false). * @property {Subscription|undefined} value.stream - The stream subscription object if the stream is active, or undefined if not. */ declare function useOpenAIStream(model?: string, temperature?: number, notifyError?: (title: string, text?: string, traceId?: string) => void): OpenAIStreamState; type openai_d_Role = Role; type openai_d_Message = Message; type openai_d_Function = Function; type openai_d_ChatCompletionsRequest = ChatCompletionsRequest; type openai_d_Choice = Choice; type openai_d_Usage = Usage; type openai_d_ChatCompletionsResponse = ChatCompletionsResponse; type openai_d_ContentMessage = ContentMessage; type openai_d_DoneMessage = DoneMessage; type openai_d_FunctionCallMessage = FunctionCallMessage; type openai_d_ChatCompletionsDelta = ChatCompletionsDelta; type openai_d_ChatCompletionsChunk = ChatCompletionsChunk; declare const openai_d_isContentMessage: typeof isContentMessage; declare const openai_d_isDoneMessage: typeof isDoneMessage; declare const openai_d_isErrorResponse: typeof isErrorResponse; declare const openai_d_extractContent: typeof extractContent; declare const openai_d_accumulateContent: typeof accumulateContent; declare const openai_d_chatCompletions: typeof chatCompletions; declare const openai_d_streamChatCompletions: typeof streamChatCompletions; type openai_d_StreamStatus = StreamStatus; declare const openai_d_StreamStatus: typeof StreamStatus; declare const openai_d_TIMEOUT: typeof TIMEOUT; type openai_d_OpenAIStreamState = OpenAIStreamState; declare const openai_d_useOpenAIStream: typeof useOpenAIStream; declare namespace openai_d { export { openai_d_Role as Role, openai_d_Message as Message, openai_d_Function as Function, openai_d_ChatCompletionsRequest as ChatCompletionsRequest, openai_d_Choice as Choice, openai_d_Usage as Usage, openai_d_ChatCompletionsResponse as ChatCompletionsResponse, openai_d_ContentMessage as ContentMessage, openai_d_DoneMessage as DoneMessage, openai_d_FunctionCallMessage as FunctionCallMessage, openai_d_ChatCompletionsDelta as ChatCompletionsDelta, openai_d_ChatCompletionsChunk as ChatCompletionsChunk, openai_d_isContentMessage as isContentMessage, openai_d_isDoneMessage as isDoneMessage, openai_d_isErrorResponse as isErrorResponse, openai_d_extractContent as extractContent, openai_d_accumulateContent as accumulateContent, openai_d_chatCompletions as chatCompletions, openai_d_streamChatCompletions as streamChatCompletions, health$1 as health, enabled$1 as enabled, openai_d_StreamStatus as StreamStatus, openai_d_TIMEOUT as TIMEOUT, openai_d_OpenAIStreamState as OpenAIStreamState, openai_d_useOpenAIStream as useOpenAIStream, }; } /** * Vector search API. * * This module can be used to interact with the vector database configured * in the Grafana LLM app plugin. That plugin must be installed, enabled and configured * in order for these functions to work. * * The {@link enabled} function can be used to check if the plugin is enabled and configured. */ interface SearchResultPayload extends Record { } /** * A request to search for resources in the vector database. **/ interface SearchRequest { /** * The name of the collection to search in. **/ collection: string; /** The query to search for. */ query: string; /** * Limit the number of results returned to the top `topK` results. * * Defaults to 10. **/ topK?: number; /** Metadata filters to apply to the vector search. */ filter?: Record; } /** * The results of a vector search. * * Results will be ordered by score, descending. */ interface SearchResult { /** * The payload of the result. * * The type of this payload depends on the collection that was searched in. * Grafana core types will be added to the same module as this type as they * are implemented. **/ payload: T; /** * The score of the result. * * This is a number between 0 and 1, where 1 is the best possible match. */ score: number; } /** * Search for resources in the configured vector database. */ declare function search(request: SearchRequest): Promise>>; /** Check if the vector API is enabled and configured via the LLM plugin. */ declare const health: () => Promise; declare const enabled: () => Promise; type vector_d_SearchRequest = SearchRequest; type vector_d_SearchResult = SearchResult; declare const vector_d_search: typeof search; declare const vector_d_health: typeof health; declare const vector_d_enabled: typeof enabled; declare namespace vector_d { export { vector_d_SearchRequest as SearchRequest, vector_d_SearchResult as SearchResult, vector_d_search as search, vector_d_health as health, vector_d_enabled as enabled, }; } declare namespace index_d { export { openai_d as openai, vector_d as vector, }; } declare class LinkedToken { type: string; value: string; range: monacoTypes.IRange; previous: LinkedToken | null; next: LinkedToken | null; constructor(type: string, value: string, range: monacoTypes.IRange, previous: LinkedToken | null, next: LinkedToken | null); isKeyword(): boolean; isWhiteSpace(): boolean; isParenthesis(): boolean; isIdentifier(): boolean; isString(): boolean; isNumber(): boolean; isDoubleQuotedString(): boolean; isVariable(): boolean; isFunction(): boolean; isOperator(): boolean; isTemplateVariable(): boolean; is(type: TokenType, value?: string | number | boolean): boolean; getPreviousNonWhiteSpaceToken(): LinkedToken | null; getPreviousOfType(type: TokenType, value?: string): LinkedToken | null; getPreviousUntil(type: TokenType, ignoreTypes: TokenType[], value?: string): LinkedToken[] | null; getNextUntil(type: TokenType, ignoreTypes: TokenType[], value?: string): LinkedToken[] | null; getPreviousKeyword(): LinkedToken | null; getNextNonWhiteSpaceToken(): LinkedToken | null; getNextOfType(type: TokenType, value?: string): LinkedToken | null; } type StatementPositionResolver = (currentToken: LinkedToken | null, previousKeyword: LinkedToken | null, previousNonWhiteSpace: LinkedToken | null, previousIsSlash: Boolean) => Boolean; type SuggestionsResolver = (positionContext: T) => Promise; interface SQLMonarchLanguage extends monacoTypes.languages.IMonarchLanguage { keywords?: string[]; builtinFunctions?: string[]; logicalOperators?: string[]; comparisonOperators?: string[]; /** Used by basic languages in the monaco registry **/ operators?: string[]; } /** * Provides a context for suggestions resolver * @alpha */ interface PositionContext { position: monacoTypes.IPosition; kind: SuggestionKind[]; statementPosition: StatementPosition[]; currentToken: LinkedToken | null; range: monacoTypes.IRange; } type CustomSuggestion = Partial & { label: string; }; interface CustomSuggestionKind { id: string; suggestionsResolver: SuggestionsResolver; applyTo?: Array; overrideDefault?: boolean; } interface CustomStatementPlacement { id: string; name?: string; resolve: StatementPositionResolver; overrideDefault?: boolean; } type StatementPlacementProvider = () => CustomStatementPlacement[]; type SuggestionKindProvider = () => CustomSuggestionKind[]; interface ColumnDefinition { name: string; type?: string; description?: string; completion?: string; } interface SchemaDefinition { name: string; completion?: string; } interface TableDefinition { name: string; completion?: string; } interface TableIdentifier { table?: string; schema?: string; } interface SQLCompletionItemProvider extends Omit { /** * Allows dialect specific functions to be added to the completion list. * @alpha */ supportedFunctions?: () => Array<{ id: string; name: string; description?: string; }>; /** * Allows dialect specific operators to be added to the completion list. * @alpha */ supportedOperators?: () => Array<{ id: string; operator: string; type: OperatorType; description?: string; }>; supportedMacros?: () => Array<{ id: string; text: string; type: MacroType; args: string[]; description?: string; }>; /** * Allows custom suggestion kinds to be defined and correlate them with StatementPosition. * @alpha */ customSuggestionKinds?: SuggestionKindProvider; /** * Allows custom statement placement definition. * @alpha */ customStatementPlacement?: StatementPlacementProvider; /** * Allows providing a custom function for resolving schemas. * It's up to the consumer to decide whether the schemas are resolved via API calls or preloaded in the query editor(i.e. full db schema is preloades loaded). * @alpha */ schemas?: { resolve: () => Promise; }; /** * Allows providing a custom function for resolving db tables. * It's up to the consumer to decide whether the columns are resolved via API calls or preloaded in the query editor(i.e. full db schema is preloades loaded). * @alpha */ tables?: { resolve: (TableIdentifier: TableIdentifier | null) => Promise; parseName?: (token: LinkedToken | null | undefined) => TableIdentifier; }; /** * Allows providing a custom function for resolving table. * It's up to the consumer to decide whether the columns are resolved via API calls or preloaded in the query editor(i.e. full db schema is preloades loaded). * @alpha */ columns?: { resolve: (identifier?: TableIdentifier) => Promise; }; /** * TODO: Not sure whether or not we need this. Would like to avoid this kind of flexibility. * @alpha */ provideCompletionItems?: (model: monacoTypes.editor.ITextModel, position: monacoTypes.Position, context: monacoTypes.languages.CompletionContext, token: monacoTypes.CancellationToken, positionContext: PositionContext) => monacoTypes.languages.CompletionList; } type LanguageCompletionProvider = (m: Monaco, l?: SQLMonarchLanguage) => SQLCompletionItemProvider; declare enum OperatorType { Comparison = 0, Logical = 1 } declare enum MacroType { Value = 0, Filter = 1, Group = 2, Column = 3, Table = 4 } declare enum TokenType { Parenthesis = "delimiter.parenthesis.sql", Whitespace = "white.sql", Keyword = "keyword.sql", Delimiter = "delimiter.sql", Operator = "operator.sql", Identifier = "identifier.sql", IdentifierQuote = "identifier.quote.sql", Type = "type.sql", Function = "predefined.sql", Number = "number.sql", String = "string.sql", Variable = "variable.sql" } declare enum StatementPosition { Unknown = "unknown", SelectKeyword = "selectKeyword", WithKeyword = "withKeyword", AfterSelectKeyword = "afterSelectKeyword", AfterSelectArguments = "afterSelectArguments", AfterSelectFuncFirstArgument = "afterSelectFuncFirstArgument", SelectAlias = "selectAlias", AfterFromKeyword = "afterFromKeyword", AfterTable = "afterTable", SchemaFuncFirstArgument = "schemaFuncFirstArgument", SchemaFuncExtraArgument = "schemaFuncExtraArgument", FromKeyword = "fromKeyword", AfterFrom = "afterFrom", WhereKeyword = "whereKeyword", WhereComparisonOperator = "whereComparisonOperator", WhereValue = "whereValue", AfterWhereFunctionArgument = "afterWhereFunctionArgument", AfterGroupByFunctionArgument = "afterGroupByFunctionArgument", AfterWhereValue = "afterWhereValue", AfterGroupByKeywords = "afterGroupByKeywords", AfterGroupBy = "afterGroupBy", AfterOrderByKeywords = "afterOrderByKeywords", AfterOrderByFunction = "afterOrderByFunction", AfterOrderByDirection = "afterOrderByDirection", AfterIsOperator = "afterIsOperator", AfterIsNotOperator = "afterIsNotOperator", AfterSchema = "afterSchema" } declare enum SuggestionKind { Schemas = "schemas", Tables = "tables", Columns = "columns", SelectKeyword = "selectKeyword", WithKeyword = "withKeyword", FunctionsWithArguments = "functionsWithArguments", FromKeyword = "fromKeyword", WhereKeyword = "whereKeyword", GroupByKeywords = "groupByKeywords", OrderByKeywords = "orderByKeywords", FunctionsWithoutArguments = "functionsWithoutArguments", LimitKeyword = "limitKeyword", SortOrderDirectionKeyword = "sortOrderDirectionKeyword", ComparisonOperators = "comparisonOperators", LogicalOperators = "logicalOperators", SelectMacro = "selectMacro", TableMacro = "tableMacro", FilterMacro = "filterMacro", GroupMacro = "groupMacro", BoolValues = "boolValues", NullValue = "nullValue", NotKeyword = "notKeyword", TemplateVariables = "templateVariables", StarWildCard = "starWildCard" } declare enum CompletionItemPriority { High = "a", MediumHigh = "d", Medium = "g", MediumLow = "k", Low = "q" } declare enum CompletionItemKind { Method = 0, Function = 1, Constructor = 2, Field = 3, Variable = 4, Class = 5, Struct = 6, Interface = 7, Module = 8, Property = 9, Event = 10, Operator = 11, Unit = 12, Value = 13, Constant = 14, Enum = 15, EnumMember = 16, Keyword = 17, Text = 18, Color = 19, File = 20, Reference = 21, Customcolor = 22, Folder = 23, TypeParameter = 24, User = 25, Issue = 26, Snippet = 27 } declare enum CompletionItemInsertTextRule { KeepWhitespace = 1, InsertAsSnippet = 4 } declare enum EditorMode { Builder = "builder", Code = "code" } interface LanguageDefinition extends monacoTypes.languages.ILanguageExtensionPoint { loader?: (module: any) => Promise<{ language: SQLMonarchLanguage; conf: monacoTypes.languages.LanguageConfiguration; }>; completionProvider?: (m: Monaco, language: SQLMonarchLanguage) => SQLCompletionItemProvider; formatter?: (q: string) => string; } interface SQLEditorProps { query: string; /** * Use for inspecting the query as it changes. I.e. for validation. */ onChange?: (q: string, processQuery: boolean) => void; onBlur?: (text: string) => void; language?: LanguageDefinition; children?: (props: { formatQuery: () => void; }) => React.ReactNode; width?: number; height?: number; } declare const SQLEditor: ({ children, onBlur, onChange, query, language, width, height, }: SQLEditorProps) => React.JSX.Element; interface TestQueryModel { query: string; tokens: Array>>; } interface StatementPositionResolverTestCase { query: TestQueryModel; position: { line: number; column: number; }; } declare const singleLineFullQuery: TestQueryModel; declare const singleLineFullQueryWithAggregation: TestQueryModel; declare const multiLineFullQuery: TestQueryModel; declare const multiLineFullQueryWithAggregation: TestQueryModel; declare const singleLineEmptyQuery: TestQueryModel; declare const singleLineTwoQueries: TestQueryModel; declare const singleLineTwoQueriesWithAggregation: TestQueryModel; declare const singleLineMultipleColumns: TestQueryModel; declare const multiLineMultipleColumns: TestQueryModel; declare const testData_singleLineFullQuery: typeof singleLineFullQuery; declare const testData_singleLineFullQueryWithAggregation: typeof singleLineFullQueryWithAggregation; declare const testData_multiLineFullQuery: typeof multiLineFullQuery; declare const testData_multiLineFullQueryWithAggregation: typeof multiLineFullQueryWithAggregation; declare const testData_singleLineEmptyQuery: typeof singleLineEmptyQuery; declare const testData_singleLineTwoQueries: typeof singleLineTwoQueries; declare const testData_singleLineTwoQueriesWithAggregation: typeof singleLineTwoQueriesWithAggregation; declare const testData_singleLineMultipleColumns: typeof singleLineMultipleColumns; declare const testData_multiLineMultipleColumns: typeof multiLineMultipleColumns; declare namespace testData { export { testData_singleLineFullQuery as singleLineFullQuery, testData_singleLineFullQueryWithAggregation as singleLineFullQueryWithAggregation, testData_multiLineFullQuery as multiLineFullQuery, testData_multiLineFullQueryWithAggregation as multiLineFullQueryWithAggregation, testData_singleLineEmptyQuery as singleLineEmptyQuery, testData_singleLineTwoQueries as singleLineTwoQueries, testData_singleLineTwoQueriesWithAggregation as singleLineTwoQueriesWithAggregation, testData_singleLineMultipleColumns as singleLineMultipleColumns, testData_multiLineMultipleColumns as multiLineMultipleColumns, }; } declare const SQLEditorTestUtils: { testData: typeof testData; testStatementPosition: (expected: string, cases: StatementPositionResolverTestCase[], resolvers: () => CustomStatementPlacement[]) => void; }; declare const conf: monacoTypes.languages.LanguageConfiguration; declare const language: SQLMonarchLanguage; declare function getStandardSQLCompletionProvider(monaco: Monaco, language: SQLMonarchLanguage): SQLCompletionItemProvider; interface AccessoryButtonProps extends ButtonProps { } declare const AccessoryButton: ({ className, ...props }: AccessoryButtonProps) => React.JSX.Element; interface EditorFieldGroupProps { } declare const EditorFieldGroup: ({ children }: React.PropsWithChildren) => React.JSX.Element; interface EditorHeaderProps { } declare const EditorHeader: ({ children }: React.PropsWithChildren) => React.JSX.Element; interface EditorFieldProps extends ComponentProps { label: string; width?: number | string; optional?: boolean; tooltip?: PopoverContent; tooltipInteractive?: boolean; } declare const EditorField: (props: React.PropsWithChildren) => React.JSX.Element; interface EditorRowProps { } declare const EditorRow: ({ children }: React.PropsWithChildren) => React.JSX.Element; interface EditorListProps { items: Array>; renderItem: (item: Partial, onChangeItem: (item: Partial) => void, onDeleteItem: () => void) => React.ReactElement; onChange: (items: Array>) => void; } declare const EditorList: React.ForwardRefExoticComponent & React.RefAttributes>; interface EditorRowsProps { } declare const EditorRows: ({ children }: React.PropsWithChildren) => React.JSX.Element; declare const EditorSwitch: (props: ComponentProps) => React.JSX.Element; interface FlexItemProps { grow?: number; shrink?: number; } declare const FlexItem: ({ grow, shrink }: FlexItemProps) => React.JSX.Element; interface StackProps { direction?: CSSProperties['flexDirection']; alignItems?: CSSProperties['alignItems']; wrap?: boolean; gap?: number; flexGrow?: CSSProperties['flexGrow']; } /** * @deprecated use the Stack component from @grafana/ui instead. Available starting from @grafana/ui@10.2.3 */ declare const Stack: ({ children, ...props }: React.PropsWithChildren) => React.JSX.Element; interface InlineSelectProps extends SelectCommonProps { label?: string; } declare function InlineSelect({ label: labelProp, ...props }: InlineSelectProps): React.JSX.Element; type Child = string | undefined | ReactElement<{ className?: string; invalid?: unknown; }>; interface InputGroupProps { children: Child | Child[]; } declare const InputGroup: ({ children }: InputGroupProps) => React.JSX.Element; interface SpaceProps { v?: number; h?: number; layout?: 'block' | 'inline'; } /** * @deprecated use the Space component from @grafana/ui instead. Available starting from @grafana/ui@10.4.0 */ declare const Space: ({ v, h, layout, }: SpaceProps) => React.JSX.Element; type Props$m = { dataSourceName: string; docsLink: string; hasRequiredFields?: boolean; className?: string; }; declare const DataSourceDescription: ({ dataSourceName, docsLink, hasRequiredFields, className }: Props$m) => React.JSX.Element; type Props$l = { title: string; description?: ReactNode; isCollapsible?: boolean; isInitiallyOpen?: boolean; kind?: 'section' | 'sub-section'; className?: string; }; type Props$k = Omit; declare const ConfigSection: ({ children, ...props }: React.PropsWithChildren) => React.JSX.Element; type Props$j = Omit; declare const ConfigSubSection: ({ children, ...props }: React.PropsWithChildren) => React.JSX.Element; type Props$i = { description: string; suffix: string; feature: string; }; declare function ConfigDescriptionLink(props: Props$i): React.JSX.Element; declare enum AuthMethod { NoAuth = "NoAuth", BasicAuth = "BasicAuth", OAuthForward = "OAuthForward", CrossSiteCredentials = "CrossSiteCredentials" } interface AuthMethodSelectOption { label?: string; description?: string; } type CustomMethodId = `custom-${string}`; type CustomMethod = { id: CustomMethodId; label: string; description: string; component: ReactElement; }; type Header = { name: string; configured: boolean; }; type HeaderWithValue = Header & { value: string; }; type Props$h = { enabled: boolean; onToggle: (enabled: boolean) => void; certificateConfigured: boolean; onCertificateChange: (certificate: string) => void; onCertificateReset: () => void; tooltips?: { certificateLabel?: string; }; readOnly: boolean; }; type Props$g = { enabled: boolean; onToggle: (enabled: boolean) => void; serverName: string; clientCertificateConfigured: boolean; clientKeyConfigured: boolean; onServerNameChange: (serverName: string) => void; onClientCertificateChange: (clientCertificate: string) => void; onClientKeyChange: (clientKey: string) => void; onClientCertificateReset: () => void; onClientKeyReset: () => void; tooltips?: { serverNameLabel?: string; certificateLabel?: string; keyLabel?: string; }; readOnly: boolean; }; type Props$f = { enabled: boolean; onToggle: (enabled: boolean) => void; readOnly: boolean; }; type Props$e = { selfSignedCertificate: Omit; TLSClientAuth: Omit; skipTLSVerification: Omit; readOnly: boolean; }; type Props$d = { user?: string; passwordConfigured: boolean; userLabel?: string; userTooltip?: PopoverContent; userPlaceholder?: string; passwordLabel?: string; passwordTooltip?: PopoverContent; passwordPlaceholder?: string; onUserChange: (user: string) => void; onPasswordChange: (password: string) => void; onPasswordReset: () => void; readOnly: boolean; }; type Props$c = { headers: Header[]; onChange: (headers: HeaderWithValue[]) => void; readOnly: boolean; }; type Props$b = { selectedMethod: AuthMethod | CustomMethodId; mostCommonMethod?: AuthMethod | CustomMethodId; visibleMethods?: Array; defaultOptionsOverrides?: Partial>; customMethods?: CustomMethod[]; onAuthMethodSelect: (authType: AuthMethod | CustomMethodId) => void; basicAuth?: Omit; TLS?: Omit; customHeaders?: Omit; readOnly?: boolean; }; declare const Auth: ({ selectedMethod, mostCommonMethod, visibleMethods, defaultOptionsOverrides, customMethods, onAuthMethodSelect, basicAuth, TLS, customHeaders, readOnly, }: Props$b) => React.JSX.Element; type Config = DataSourceSettings; type OnChangeHandler = (config: C) => void; declare function convertLegacyAuthProps({ config, onChange, }: { config: C; onChange: OnChangeHandler; }): Props$b; type Props$a = { config: C; onChange: OnChangeHandler; description?: ReactNode; urlPlaceholder?: string; urlTooltip?: PopoverContent; urlLabel?: string; className?: string; }; declare const ConnectionSettings: (props: Props$a) => JSX.Element; type Props$9 = { config: C; onChange: OnChangeHandler; className?: string; }; declare const AdvancedHttpSettings: (props: Props$9) => JSX.Element; interface QueryBuilderLabelFilter { label: string; op: string; value: string; } interface QueryBuilderOperation { id: string; params: QueryBuilderOperationParamValue[]; disabled?: boolean; } interface QueryBuilderOperationDefinition extends RegistryItem { documentation?: string; params: QueryBuilderOperationParamDef[]; defaultParams: QueryBuilderOperationParamValue[]; category: string; hideFromList?: boolean; alternativesKey?: string; /** Can be used to control operation placement when adding a new operations, lower are placed first */ orderRank?: number; renderer: QueryBuilderOperationRenderer; addOperationHandler: QueryBuilderAddOperationHandler; paramChangedHandler?: QueryBuilderOnParamChangedHandler; explainHandler?: QueryBuilderExplainOperationHandler; changeTypeHandler?: (op: QueryBuilderOperation, newDef: QueryBuilderOperationDefinition) => QueryBuilderOperation; toggleable?: boolean; } type QueryBuilderAddOperationHandler = (def: QueryBuilderOperationDefinition, query: T, modeller: VisualQueryModeller) => T; type QueryBuilderExplainOperationHandler = (op: QueryBuilderOperation, def?: QueryBuilderOperationDefinition) => string; type QueryBuilderOnParamChangedHandler = (index: number, operation: QueryBuilderOperation, operationDef: QueryBuilderOperationDefinition) => QueryBuilderOperation; type QueryBuilderOperationRenderer = (model: QueryBuilderOperation, def: QueryBuilderOperationDefinition, innerQuery: string) => string; type QueryBuilderOperationParamValue = string | number | boolean; interface QueryBuilderOperationParamDef { name: string; type: 'string' | 'number' | 'boolean'; options?: string[] | number[] | Array>; hideName?: boolean; restParam?: boolean; optional?: boolean; placeholder?: string; description?: string; minWidth?: number; editor?: FunctionComponent; runQueryOnEnter?: boolean; } interface QueryBuilderOperationParamEditorProps { value?: QueryBuilderOperationParamValue; paramDef: QueryBuilderOperationParamDef; /** Parameter index */ index: number; operation: QueryBuilderOperation; operationId: string; query: any; datasource: DataSourceApi; timeRange?: TimeRange; onChange: (index: number, value: QueryBuilderOperationParamValue) => void; onRunQuery: () => void; queryModeller: VisualQueryModeller; } declare enum QueryEditorMode { Code = "code", Builder = "builder" } type QueryStats = { bytes: number; message?: string; }; interface VisualQueryModeller { getOperationsForCategory(category: string): QueryBuilderOperationDefinition[]; getAlternativeOperations(key: string): QueryBuilderOperationDefinition[]; getCategories(): string[]; getOperationDefinition(id: string): QueryBuilderOperationDefinition | undefined; renderQuery(query: VisualQuery, nested?: boolean): string; renderLabels(labels: QueryBuilderLabelFilter[]): string; innerQueryPlaceholder: string; } interface VisualQueryBinary { operator: string; vectorMatchesType?: 'on' | 'ignoring'; vectorMatches?: string; query: T; } declare const BINARY_OPERATIONS_KEY = "Binary operations"; interface VisualQuery { metric?: string; labels: QueryBuilderLabelFilter[]; operations: QueryBuilderOperation[]; binaryQueries?: Array>; } declare abstract class QueryModellerBase implements VisualQueryModeller { protected operationsRegistry: Registry; private categories; innerQueryPlaceholder: string; constructor(operationDefinitions: QueryBuilderOperationDefinition[], innerQueryPlaceholder?: string); protected setOperationCategories(categories: string[]): void; abstract renderOperations(queryString: string, operations: QueryBuilderOperation[]): string; abstract renderBinaryQueries(queryString: string, binaryQueries?: Array>): string; abstract renderLabels(labels: QueryBuilderLabelFilter[]): string; abstract renderQuery(query: VisualQuery, nested?: boolean): string; getOperationsForCategory(category: string): QueryBuilderOperationDefinition[]; getAlternativeOperations(key: string): QueryBuilderOperationDefinition[]; getCategories(): string[]; getOperationDefinition(id: string): QueryBuilderOperationDefinition | undefined; hasBinaryOp(query: VisualQuery): boolean; } interface Props$8 { labelsFilters: QueryBuilderLabelFilter[]; onChange: (labelFilters: QueryBuilderLabelFilter[]) => void; onGetLabelNames: (forLabel: Partial) => Promise; onGetLabelValues: (forLabel: Partial) => Promise; /** If set to true, component will show error message until at least 1 filter is selected */ labelFilterRequired?: boolean; multiValueSeparator?: string; } declare function LabelFilters({ labelsFilters, onChange, onGetLabelNames, onGetLabelValues, labelFilterRequired, multiValueSeparator, }: Props$8): React.JSX.Element; interface Props$7 { title?: React.ReactNode; markdown?: string; stepNumber?: number; } declare function OperationExplainedBox({ title, stepNumber, markdown, children }: React.PropsWithChildren): React.JSX.Element; interface Props$6 { query: T; datasource: DataSourceApi; onChange: (query: T) => void; onRunQuery: () => void; queryModeller: VisualQueryModeller; explainMode?: boolean; highlightedOp?: QueryBuilderOperation; timeRange?: TimeRange; isConflictingOperation?: (operation: QueryBuilderOperation, otherOperations: QueryBuilderOperation[]) => boolean; } declare function OperationList({ query, datasource, queryModeller, onChange, onRunQuery, highlightedOp, timeRange, isConflictingOperation, }: Props$6): React.JSX.Element; interface Props$5 { query: T; queryModeller: VisualQueryModeller; explainMode?: boolean; stepNumber: number; language: { grammar: Grammar; name: string; }; onMouseEnter?: (op: QueryBuilderOperation, index: number) => void; onMouseLeave?: (op: QueryBuilderOperation, index: number) => void; } declare function OperationListExplained({ query, queryModeller, stepNumber, language, onMouseEnter, onMouseLeave, }: Props$5): React.JSX.Element; declare function OperationsEditorRow({ children }: React.PropsWithChildren): React.JSX.Element; interface Props$4 { query: TVisualQuery; datasource: DataSourceApi; queryModeller: VisualQueryModeller; buildVisualQueryFromString: (queryString: string) => { query: TVisualQuery; }; buildDataQueryFromQueryString: (queryString: string) => TDataQuery; buildQueryStringFromDataQuery: (dataQuery: TDataQuery) => string; onChange: (update: TVisualQuery) => void; data?: PanelData; } declare const QueryBuilderHints: { ({ datasource, query: visualQuery, onChange, data, queryModeller, buildVisualQueryFromString, buildDataQueryFromQueryString, buildQueryStringFromDataQuery, }: Props$4): React.JSX.Element; displayName: string; }; interface Props$3 { mode: QueryEditorMode; onChange: (mode: QueryEditorMode) => void; } declare function QueryEditorModeToggle({ mode, onChange }: Props$3): React.JSX.Element; interface Props$2 extends Omit, 'value' | 'ref'> { value?: boolean; label: string; } declare function QueryHeaderSwitch({ label, ...inputProps }: Props$2): React.JSX.Element; interface Props$1 { title: string; collapsedInfo: string[]; queryStats?: QueryStats | null; } declare function QueryOptionGroup({ title, children, collapsedInfo, queryStats }: React.PropsWithChildren): React.JSX.Element; interface Props { query: string; language: { grammar: Grammar; name: string; }; className?: string; } declare function RawQuery({ query, language, className }: Props): React.JSX.Element; export { AccessoryButton, AdvancedHttpSettings, Auth, AuthMethod, Props$b as AuthProps, BINARY_OPERATIONS_KEY, ColumnDefinition, CompletionItemInsertTextRule, CompletionItemKind, CompletionItemPriority, ConfigDescriptionLink, ConfigSection, ConfigSubSection, ConnectionSettings, DataSourceDescription, EditorField, EditorFieldGroup, EditorHeader, EditorList, EditorMode, EditorRow, EditorRows, EditorSwitch, FlexItem, InlineSelect, InputGroup, LabelFilters, LanguageCompletionProvider, LanguageDefinition, LinkedToken, MacroType, OperationExplainedBox, OperationList, OperationListExplained, OperationsEditorRow, OperatorType, PositionContext, QueryBuilderHints, QueryBuilderLabelFilter, QueryBuilderOperation, QueryBuilderOperationDefinition, QueryBuilderOperationParamDef, QueryBuilderOperationParamEditorProps, QueryBuilderOperationParamValue, QueryEditorMode, QueryEditorModeToggle, QueryHeaderSwitch, QueryModellerBase, QueryOptionGroup, QueryStats, RawQuery, SQLEditor, SQLEditorTestUtils, SQLMonarchLanguage, SchemaDefinition, Space, Stack, StatementPlacementProvider, StatementPosition, SuggestionKind, SuggestionKindProvider, TableDefinition, TableIdentifier, TestQueryModel, TokenType, VisualQuery, VisualQueryBinary, VisualQueryModeller, convertLegacyAuthProps, getStandardSQLCompletionProvider, language as grafanaStandardSQLLanguage, conf as grafanaStandardSQLLanguageConf, index_d as llms };