"use strict";(self.webpackChunkgrafana=self.webpackChunkgrafana||[]).push([[1697],{31697:(Ba,fe,o)=>{o.r(fe),o.d(fe,{plugin:()=>La});var Ke=o(41466),e=o(85960);const Ye=[{title:"Request Rate",expression:"rate(http_request_total[5m])",label:"Given an HTTP request counter, this query calculates the per-second average request rate over the last 5 minutes."},{title:"95th Percentile of Request Latencies",expression:"histogram_quantile(0.95, sum(rate(prometheus_http_request_duration_seconds_bucket[5m])) by (le))",label:"Calculates the 95th percentile of HTTP request rate over 5 minute windows."},{title:"Alerts Firing",expression:'sort_desc(sum(sum_over_time(ALERTS{alertstate="firing"}[24h])) by (alertname))',label:"Sums up the alerts that have been firing over the last 24 hours."},{title:"Step",label:"Defines the graph resolution using a duration format (15s, 1m, 3h, ...). Small steps create high-resolution graphs but can be slow over larger time ranges. Using a longer step lowers the resolution and smooths the graph by producing fewer datapoints. If no step is given the resolution is calculated automatically."}],Xe=t=>e.createElement("div",null,e.createElement("h2",null,"PromQL Cheat Sheet"),Ye.map((a,r)=>e.createElement("div",{className:"cheat-sheet-item",key:r},e.createElement("div",{className:"cheat-sheet-item__title"},a.title),a.expression?e.createElement("button",{type:"button",className:"cheat-sheet-item__example",onClick:s=>t.onClickExample({refId:"A",expr:a.expression})},e.createElement("code",null,a.expression)):null,e.createElement("div",{className:"cheat-sheet-item__label"},a.label))));var L=o(81223),W=o(56375),ye=o(23757),Je=o(92369),_e=o(86755),ve=o(53628),et=o(98181),Ee=o(23270),N=o(43183),tt=o(77980),S=o(29165),l=o(66681),w=o(47257),at=o(7288),rt=o(8655),nt=o(21871),M=o(77530),U=o(72435),K=o(16972),Y=o(87438);const st=t=>{const{pattern:a,onPatternSelect:r,hasNewQueryOption:s,hasPreviousQuery:n,selectedPatternName:u,setSelectedPatternName:d}=t,i=(0,w.wW)(ot),m={grammar:Y.ZP,name:"promql"};return e.createElement(U.Z,{className:i.card},e.createElement(U.Z.Heading,null,a.name),e.createElement("div",{className:i.rawQueryContainer},e.createElement(K.U,{"aria-label":`${a.name} raw query`,query:M.Z.renderQuery({labels:[],operations:a.operations,binaryQueries:a.binaryQueries}),lang:m,className:i.rawQuery})),e.createElement(U.Z.Actions,null,u!==a.name?e.createElement(S.zx,{size:"sm","aria-label":"use this query button",onClick:()=>{n?d(a.name):r(a)}},"Use this query"):e.createElement(e.Fragment,null,e.createElement("div",{className:i.spacing},`If you would like to use this query, ${s?"you can either apply this query pattern or create a new query":"this query pattern will be applied to your current query"}.`),e.createElement(S.zx,{size:"sm","aria-label":"back button",fill:"outline",onClick:()=>d(null)},"Back"),e.createElement(S.zx,{size:"sm","aria-label":"apply query starter button",onClick:()=>{r(a)}},"Apply query"),s&&e.createElement(S.zx,{size:"sm","aria-label":"create new query button",onClick:()=>{r(a,!0)}},"Create new query"))))},ot=t=>({card:(0,l.css)`
      width: 49.5%;
      display: flex;
      flex-direction: column;
    `,rawQueryContainer:(0,l.css)`
      flex-grow: 1;
    `,rawQuery:(0,l.css)`
      background-color: ${t.colors.background.primary};
      padding: ${t.spacing(1)};
      margin-top: ${t.spacing(1)};
    `,spacing:(0,l.css)`
      margin-bottom: ${t.spacing(1)};
    `});var A=o(98100),it=o(10596);const lt=t=>{const{isOpen:a,onClose:r,onChange:s,onAddQuery:n,query:u,queries:d,app:i}=t,[m,h]=(0,e.useState)([]),[y,g]=(0,e.useState)(null),P=(0,w.wW)(ct),v=!!n,p=(0,e.useMemo)(()=>{const c=(0,A._)(u.expr??""),E=c.query.operations.length>0,x=c.query.metric,k=c.query.labels.length>0,O=c.query.binaryQueries?c.query.binaryQueries.length>0:!1;return E||x||k||O},[u.expr]),f=(c,E=!1)=>{const x=(0,A._)(E?"":u.expr);(0,N.ff)("grafana_prom_kickstart_your_query_selected",{app:i??"",editorMode:u.editorMode,selectedPattern:c.name,preSelectedOperationsCount:x.query.operations.length,preSelectedLabelsCount:x.query.labels.length,createNewQuery:v&&E}),x.query.operations=c.operations,x.query.binaryQueries=c.binaryQueries,v&&E?n({...u,refId:(0,nt.Hs)(d??[u]),expr:M.Z.renderQuery(x.query)}):s({...u,expr:M.Z.renderQuery(x.query)}),g(null),r()};return e.createElement(at.u,{"aria-label":"Kick start your query modal",isOpen:a,title:"Kick start your query",onDismiss:r},e.createElement("div",{className:P.spacing},"Kick start your query by selecting one of these queries. You can then continue to complete your query."),Object.values(it.Fz).map(c=>e.createElement(rt.U,{"aria-label":`open and close ${c} query starter card`,key:c,label:`${(0,W.capitalize)(c)} query starters`,isOpen:m.includes(c),collapsible:!0,onToggle:()=>h(E=>E.includes(c)?E.filter(x=>x!==c):[...E,c])},e.createElement("div",{className:P.cardsContainer},M.Z.getQueryPatterns().filter(E=>E.type===c).map(E=>e.createElement(st,{key:E.name,pattern:E,hasNewQueryOption:v,hasPreviousQuery:p,onPatternSelect:f,selectedPatternName:y,setSelectedPatternName:g}))))),e.createElement(S.zx,{"aria-label":"close kick start your query modal",variant:"secondary",onClick:r},"Close"))},ct=t=>({cardsContainer:(0,l.css)`
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: space-between;
    `,spacing:(0,l.css)`
      margin-bottom: ${t.spacing(1)};
    `});var ut=o(65607),mt=o(69217),be=o(36867),I=o(33485),$=o(20994),C=o(43190);const xe="PrometheusQueryEditorModeDefault";function Se(t,a,r){t.expr===""&&$.Z.set(xe,a),r({...t,editorMode:a})}function dt(t,a=I.c.Builder){if(t!=null&&t!=="")return I.c.Code;const r=$.Z.get(xe);switch(r){case I.c.Builder:case I.c.Code:return r;default:return a}}function pt(t,a,r){let s=t;t.editorMode||(s={...t,editorMode:dt(t.expr,r)}),t.expr||(s={...s,expr:"",legendFormat:C.pD.Auto}),t.range==null&&t.instant==null&&(s={...s,range:!0},a===L.zj.Explore&&(s.instant=!0));const n=t.instant&&t.range;return a===L.zj.UnifiedAlerting&&n&&(s={...s,instant:!1,range:!0}),s}var Pe=o(20079),Ce=o(90857),X=o(82564),gt=o(63153),ht=o(88556),ft=o(59694),yt=o(99149),vt=o(36796),Et=o(42763),bt=o(62254),xt=o(13086),St=o(11248),z=o(27436),J=o(15910),Te=o(75064),Pt=o(62989);const Qe=e.memo(t=>{const{nestedQuery:a,index:r,datasource:s,onChange:n,onRemove:u,onRunQuery:d,showExplain:i}=t,m=(0,w.wW)(Tt);return e.createElement("div",{className:m.card},e.createElement("div",{className:m.header},e.createElement("div",{className:m.name},"Operator"),e.createElement(z.Ph,{width:"auto",options:Ct,value:(0,St.E)(a.operator),onChange:h=>{n(r,{...a,operator:h.value})}}),e.createElement("div",{className:m.name},"Vector matches"),e.createElement("div",{className:m.vectorMatchWrapper},e.createElement(z.Ph,{width:"auto",value:a.vectorMatchesType||"on",allowCustomValue:!0,options:[{value:"on",label:"on"},{value:"ignoring",label:"ignoring"}],onChange:h=>{n(r,{...a,vectorMatchesType:h.value})}}),e.createElement(J.H,{className:m.vectorMatchInput,minWidth:20,defaultValue:a.vectorMatches,onCommitChange:h=>{n(r,{...a,vectorMatches:h.currentTarget.value,vectorMatchesType:a.vectorMatchesType||"on"})}})),e.createElement(ve.B,{grow:1}),e.createElement(Te.h,{name:"times",size:"sm",onClick:()=>u(r),tooltip:"Remove match"})),e.createElement("div",{className:m.body},e.createElement(Ee._,null,e.createElement(ue,{showExplain:i,query:a.query,datasource:s,onRunQuery:d,onChange:h=>{n(r,{...a,query:h})}}))))}),Ct=Pt.iQ.map(t=>({label:t.sign,value:t.sign}));Qe.displayName="NestedQuery";const Tt=t=>({card:(0,l.css)({label:"card",display:"flex",flexDirection:"column",gap:t.spacing(.5)}),header:(0,l.css)({label:"header",padding:t.spacing(.5,.5,.5,1),gap:t.spacing(1),display:"flex",alignItems:"center"}),name:(0,l.css)({label:"name",whiteSpace:"nowrap"}),body:(0,l.css)({label:"body",paddingLeft:t.spacing(2)}),vectorMatchInput:(0,l.css)({label:"vectorMatchInput",marginLeft:-1}),vectorMatchWrapper:(0,l.css)({label:"vectorMatchWrapper",display:"flex"})});function Qt(t){const{query:a,datasource:r,onChange:s,onRunQuery:n,showExplain:u}=t,d=a.binaryQueries??[],i=(h,y)=>{const g=[...d];g.splice(h,1,y),s({...a,binaryQueries:g})},m=h=>{const y=[...d.slice(0,h),...d.slice(h+1)];s({...a,binaryQueries:y})};return e.createElement(xt.K,{direction:"column",gap:1},d.map((h,y)=>e.createElement(Qe,{key:y.toString(),nestedQuery:h,index:y,onChange:i,datasource:r,onRemove:m,onRunQuery:n,showExplain:u})))}var Nt=o(91248),Mt=o(49199),Lt=o(55973),kt=o(24956),_=o(75682),wt=o(23351),It=o(7073),Ne=o(57652);const At=[{label:"Yes",value:"yes"},{label:"No",value:"no"}],Ft=[{label:"Too vague",value:"too vague"},{label:"Too technical",value:"too technical"},{label:"Inaccurate",value:"inaccurate"},{label:"Other",value:"other"}];function Bt(t){const{querySuggestion:a,order:r,queryExplain:s,historical:n,onChange:u,closeDrawer:d,last:i,allSuggestions:m,prompt:h}=t,[y,g]=(0,e.useState)(!1),[P,v]=(0,e.useState)(!1),[p,f]=(0,e.useState)(!1),[c,E]=(0,e.useState)({radioInput:"",text:""}),[x,k]=(0,e.useState)({radioInput:"",text:""}),O=(0,w.l4)(),b=j(O),{query:he,explanation:ka}=a,Ue=Q=>{const wa=D=>{Q==="explanation"?k({...x,radioInput:D}):E({...c,radioInput:D})},Ia=D=>{Q==="explanation"?k({...x,text:D.currentTarget.value}):E({...c,text:D.currentTarget.value})},Aa=()=>Q==="explanation"?!x.radioInput:!c.radioInput,Fa=Q==="explanation"?"Why was the explanation not helpful?":"Were the query suggestions helpful?";return e.createElement("div",{className:b.suggestionFeedback},e.createElement("div",null,e.createElement("div",{className:b.feedbackQuestion},e.createElement("h6",null,Fa),e.createElement("i",null,"(Required)")),e.createElement(wt.x,{name:"default",options:Q==="explanation"?Ft:At,value:Q==="explanation"?x.radioInput:c.radioInput,onChange:wa})),e.createElement("div",{className:(0,l.cx)(Q==="explanation"&&b.explationTextInput)},Q!=="explanation"&&e.createElement("div",{className:b.feedbackQuestion},e.createElement("h6",null,"How can we improve the query suggestions?")),e.createElement(It.K,{type:"text","aria-label":"Promqail suggestion text",placeholder:"Enter your feedback",value:Q==="explanation"?x.text:c.text,onChange:Ia,cols:100})),e.createElement("div",{className:b.submitFeedback},e.createElement(S.zx,{variant:"primary",size:"sm",disabled:Aa(),onClick:()=>{Q==="explanation"?(Me(x.radioInput,x.text,a,n,h),v(!0)):($t(c.radioInput,c.text,m??"",n,h),f(!0))}},"Submit")))};return e.createElement(e.Fragment,null,e.createElement("div",{className:b.querySuggestion},e.createElement("div",{title:he,className:(0,l.cx)(b.codeText,b.longCode)},`${r}.  ${he}`),e.createElement("div",{className:b.useButton},e.createElement(S.zx,{variant:"primary",size:"sm",onClick:()=>{(0,N.ff)("grafana_prometheus_promqail_use_query_button_clicked",{query:a.query});const Q=(0,A._)(a.query);u(Q.query),d()}},"Use"))),e.createElement("div",null,e.createElement(S.zx,{fill:"text",variant:"secondary",icon:y?"angle-up":"angle-down",onClick:()=>{g(!y),s(r-1)},className:(0,l.cx)(b.bodySmall),size:"sm"},"Explainer"),!y&&r!==5&&e.createElement("div",{className:b.textPadding}),y&&!a.explanation&&e.createElement("div",{className:b.center},e.createElement(_.$,null)),y&&a.explanation&&e.createElement(e.Fragment,null,e.createElement("div",{className:(0,l.cx)(b.bodySmall,b.explainPadding)},e.createElement("div",{className:b.textPadding},"This query is trying to answer the question:"),e.createElement("div",{className:b.textPadding},ka),e.createElement("div",{className:b.textPadding},"Learn more with this"," ",e.createElement("a",{className:b.doc,href:"https://prometheus.io/docs/prometheus/latest/querying/examples/#query-examples",target:"_blank",rel:"noopener noreferrer"},"Prometheus doc")),e.createElement("div",{className:(0,l.cx)(b.rightButtons,b.secondaryText)},"Was this explanation helpful?",e.createElement("div",{className:b.floatRight},P?"Thank you for your feedback!":e.createElement(e.Fragment,null,e.createElement(S.zx,{fill:"outline",variant:"secondary",size:"sm",className:b.leftButton,onClick:()=>{Me("Yes","",a,n,h),v(!0)}},"Yes"),e.createElement(Ne.P,{"aria-label":"Suggestion feedback",content:Ue("explanation"),placement:"bottom-end",closeButton:!0},e.createElement(S.zx,{variant:"success",size:"sm"},"No")))))),!i&&e.createElement("hr",null)),i&&e.createElement("div",{className:(0,l.cx)(b.feedbackStyle)},p?e.createElement(S.zx,{fill:"outline",variant:"secondary",size:"sm",disabled:!0},"Thank you for your feedback!"):e.createElement(Ne.P,{"aria-label":"Suggestion feedback",content:Ue("suggestion"),placement:"bottom-end",closeButton:!0},e.createElement(S.zx,{fill:"outline",variant:"secondary",size:"sm"},"Give feedback on suggestions")))))}function Me(t,a,r,s,n){const u="grafana_prometheus_promqail_explanation_feedback";(0,N.ff)(u,{helpful:t,textFeedback:a,suggestionType:s?"historical":"AI",query:r.query,explanation:r.explanation,prompt:n})}function $t(t,a,r,s,n){const u="grafana_prometheus_promqail_suggestion_feedback";(0,N.ff)(u,{helpful:t,textFeedback:a,suggestionType:s?"historical":"AI",allSuggestions:r,prompt:n})}var T=(t=>(t.Historical="historical",t.AI="AI",t))(T||{});function Le(t){const{suggestionType:a,querySuggestions:r,closeDrawer:s,nextInteraction:n,queryExplain:u,onChange:d,prompt:i}=t,[m,h]=(0,e.useState)(!1),y=(0,w.l4)(),g=j(y);let P,v,p;return a===T.Historical?(P=`Here are ${r.length} query suggestions:`,p="I want to write a prompt"):a===T.AI&&(P=P="Here is your query suggestion:",v="This query is based off of natural language descriptions of the most commonly used PromQL queries.",p="Refine prompt"),e.createElement(e.Fragment,null,a===T.Historical?e.createElement("div",{className:g.bottomMargin},P):e.createElement(e.Fragment,null,e.createElement("div",{className:g.textPadding},P),e.createElement("div",{className:(0,l.cx)(g.secondaryText,g.bottomMargin)},v)),e.createElement("div",{className:g.infoContainerWrapper},e.createElement("div",{className:g.infoContainer},r.map((f,c)=>e.createElement(Bt,{historical:a===T.Historical,querySuggestion:f,key:c,order:c+1,queryExplain:u,onChange:d,closeDrawer:s,last:c===r.length-1,allSuggestions:r.reduce((E,x)=>E+"$$"+x.query,""),prompt:i??""})))),!m&&e.createElement("div",{className:g.nextInteractionHeight},e.createElement("div",{className:(0,l.cx)(g.afterButtons,g.textPadding)},e.createElement(S.zx,{onClick:()=>{h(!0),n()},"data-testid":R.refinePrompt,fill:"outline",variant:"secondary",size:"md"},p)),e.createElement("div",{className:(0,l.cx)(g.textPadding,g.floatRight)},e.createElement(S.zx,{fill:"outline",variant:"secondary",size:"md",onClick:s},"Cancel"))))}var ke=o(21396),q=o(80203),ee=o(85445),H=o(45465),te=o(1829);async function zt(t){return(await(0,ee.i)().post("/api/plugins/grafana-llm-app/resources/vector/search",t,{headers:{"Content-Type":"application/json"}})).results}let ae=!1;const qt=async()=>{try{if(!(await(0,ee.i)().get(`${te.SR}/settings`,void 0,void 0,{showSuccessAlert:!1,showErrorAlert:!1})).enabled)return{enabled:!1,ok:!1,error:"The Grafana LLM plugin is not enabled."}}catch(r){return(0,H.o7)(String(r)),(0,H.o7)("Failed to check if the vector service is enabled. This is expected if the Grafana LLM plugin is not installed, and the above error can be ignored."),ae=!0,{enabled:!1,ok:!1,error:"The Grafana LLM plugin is not installed."}}let t;try{t=await(0,ee.i)().get(`${te.SR}/health`,void 0,void 0,{showSuccessAlert:!1,showErrorAlert:!1})}catch(r){return ae||((0,H.o7)(String(r)),(0,H.o7)("Failed to check if vector service is enabled. This is expected if the Grafana LLM plugin is not installed, and the above error can be ignored."),ae=!0),{enabled:!1,ok:!1,error:"The Grafana LLM plugin is not installed."}}const{details:a}=t;return a?.version!==void 0&&(0,te.Bv)(a.version),a?.vector===void 0?{enabled:!1,ok:!1,error:"The Grafana LLM plugin is outdated; please update it."}:typeof a.vector=="boolean"?{enabled:a.vector,ok:a.vector}:a.vector};var re=o(27170);const Rt=`You are an expert in Prometheus, the event monitoring and alerting application.

You are given relevant PromQL documentation, a type and description for a Prometheus metric, and a PromQL query on that metric. Using the provided information for reference, please explain what the output of a given query is in 1 sentences. Do not walk through what the functions do separately, make your answer concise. 

Input will be in the form:


PromQL Documentation:
<PromQL documentation>

PromQL Metrics Metadata:
<metric_name>(<metric type of the metric queried>): <description of what the metric means>

PromQL Expression: 
<PromQL query>

Examples of input and output
----------
PromQL Documentation:
A counter is a cumulative metric that represents a single monotonically increasing counter whose value can only increase or be reset to zero on restart. For example, you can use a counter to represent the number of requests served, tasks completed, or errors.
topk (largest k elements by sample value)
sum (calculate sum over dimensions)
rate(v range-vector) calculates the per-second average rate of increase of the time series in the range vector. Breaks in monotonicity (such as counter resets due to target restarts) are automatically adjusted for. 

PromQL Metrics Metadata:
traces_exporter_sent_spans(counter): Number of spans successfully sent to destination.

PromQL Expression:
topk(3, sum by(cluster) (rate(traces_exporter_sent_spans{exporter="otlp"}[5m])))

This query is trying to answer the question:
What is the top 3 clusters that have successfully sent the most number of spans to the destination?
`;function Ot({documentation:t,metricName:a,metricType:r,metricMetadata:s,query:n}){return t===""&&(t="No documentation provided."),s===""&&(s="No description provided."),`
        PromQL Documentation: 
        ${t}

        PromQL Metrics Metadata:
        ${a}(${r}): ${s}

        PromQL Expression: 
        ${n}

        This query is trying to answer the question:
    `}const Dt=`You are a Prometheus Query Language (PromQL) expert assistant inside Grafana.
When the user asks a question, respond with a valid PromQL query and only the query.

To help you answer the question, you will receive:
- List of potentially relevant PromQL templates with descriptions, ranked by semantic search score
- Prometheus metric
- Metric type
- Available Prometheus metric labels
- User question

Policy:
- Do not invent labels names, you can only use the available labels
- For rate queries, use the $__rate_interval variable`;function Wt({promql:t,question:a,metricType:r,labels:s,templates:n}){return n===""?n="No templates provided.":n=n.replace(/\n/g,`
  `),`Relevant PromQL templates:
  ${n}
  
  Prometheus metric: ${t}
  Metric type: ${r}
  Available Prometheus metric labels: ${s}
  User question: ${a}
  
  \`\`\`promql`}const ne=(0,Pe.oM)({name:"metrics-modal-state",initialState:we(),reducers:{showExplainer:(t,a)=>{t.showExplainer=a.payload},showStartingMessage:(t,a)=>{t.showStartingMessage=a.payload},indicateCheckbox:(t,a)=>{t.indicateCheckbox=a.payload},askForQueryHelp:(t,a)=>{t.askForQueryHelp=a.payload},addInteraction:(t,a)=>{const r=Ie(a.payload.suggestionType,a.payload.isLoading),s=t.interactions;t.interactions=s.concat([r])},updateInteraction:(t,a)=>{const r=a.payload.idx,s=a.payload.interaction;t.interactions=t.interactions.map((n,u)=>u===r?s:n)}}});function we(t,a){return{query:t??{metric:"",labels:[],operations:[]},showExplainer:!1,showStartingMessage:a??!0,indicateCheckbox:!1,askForQueryHelp:!1,interactions:[]}}function Ie(t,a){return{suggestionType:t,prompt:"",suggestions:[],isLoading:a??!1,explanationIsLoading:!1}}const G=[{template:"metric_a{}",description:'Get the data for "metric_a"'},{template:"avg by(c) (metric_a{})",description:'Average of all series in "metric_a" grouped by the label "c"'},{template:"count by(d) (metric_a{})",description:'Number of series in the metric "metric_a" grouped by the label "d"'},{template:"sum by(g) (sum_over_time(metric_a{}[1h]))",description:'For each series in the metric "metric_a", sum all values over 1 hour, then group those series by label "g" and sum.'},{template:"count(metric_a{})",description:'Count of series in the metric "metric_a"'},{template:"(metric_a{})",description:'Get the data for "metric_a"'},{template:"count_over_time(metric_a{}[1h])",description:"Number of series of metric_a in a 1 hour interval"},{template:"changes(metric_a{}[1m])",description:"Number of times the values of each series in metric_a have changed in 1 minute periods"},{template:"count(count by(g) (metric_a{}))",description:"Total number of series in metric_a"},{template:"last_over_time(metric_a{}[1h])",description:"For each series in metric_a, get the last value in the 1 hour period."},{template:"sum by(g) (count_over_time(metric_a{}[1h]))",description:'Grouped sum over the label "g" of the number of series of metric_a in a 1 hour period'},{template:"count(metric_a{} == 99)",description:"Number of series of metric_a that have value 99"},{template:"min(metric_a{})",description:'At each timestamp, find the minimum of all series of the metric "metric_a"'},{template:"metric_a{} != 99",description:"Series of metric_a which do not have the value 99"},{template:"metric_a{} - 99",description:"metric_a minus 99"},{template:"quantile_over_time(0.99,metric_a{}[1h])",description:"The 99th quantile of values of metric_a in 1 hour"},{template:'count_values("aaaa",metric_a{})',description:'Count number of label values for a label named "aaaa"'}],Ht=[{template:"sum by(d) (rate(metric_a{}[1h]))",description:'Sum of the rate of increase or decrease of the metric "metric_a" per 1 hour period, grouped by the label "d"'},{template:"rate(metric_a{}[1m])",description:'Rate of change of the metric "metric_a" over 1 minute'},{template:"sum by(a) (increase(metric_a{}[5m]))",description:'Taking the metric "metric_a" find the increase in 5 minute periods of each series and aggregate sum over the label "a"'},{template:"sum(rate(metric_a{}[1m]))",description:'Total rate of change of all series of metric "metric_a" in 1 minute intervals'},{template:"sum(increase(metric_a{}[10m]))",description:'Total increase for each series of metric "metric_a" in 10 minute intervals'},{template:"increase(metric_a{}[1h])",description:'Increase in all series of "metric_a" in 1 hour period'},{template:"sum by(d) (irate(metric_a{}[1h]))",description:'Sum of detailed rate of change of the metric "metric_a" over 1 hour grouped by label "d"'},{template:"irate(metric_a{}[1h])",description:'Detailed rate of change of the metric "metric_a" over 1 hour'},{template:"avg by(d) (rate(metric_a{}[1h]))",description:'Taking the rate of change of the metric "metric_a" in a 1 hour period, group by the label "d" and find the average of each group'},{template:"topk(5,sum by(g) (rate(metric_a{}[1h])))",description:'Top 5 of the summed groups "g" of the rate of change of metric_a'},{template:"sum(rate(metric_a{}[1h])) / sum(rate(metric_a{}[1h]))",description:"Relative sums of metric_a with different labels"},{template:"histogram_quantile(99,rate(metric_a{}[1h]))",description:"99th percentile of the rate of change of metric_a in 1 hour periods"},{template:"avg(rate(metric_a{}[1m]))",description:"Average of the rate of all series of metric_a in 1 minute periods"},{template:"rate(metric_a{}[5m]) > 99",description:"Show series of metric_a only if their rate over 5 minutes is greater than 99"},{template:"count by(g) (rate(metric_a{}[1h]))",description:'Count of series of metric_a over all labels "g"'}],Gt=[{template:"histogram_quantile(99,sum by(le) (rate(metric_a{}[1h])))",description:'Calculate the rate at which the metric "metric_a" is increasing or decreasing, summed over each bucket label "le", and then calculates the 99th percentile of those rates.'},{template:"histogram_quantile(99,sum by(g) (metric_a{}))",description:'99th percentile of the sum of metric_a grouped by label "g"'},{template:"histogram_quantile(99,sum by(g) (irate(metric_a{}[1h])))",description:'99th percentile of the grouped by "g" sum of the rate of each series in metric_a in an hour'},{template:"histogram_quantile(99,metric_a{})",description:"99th percentile of metric_a"}],Vt=[{template:"sum by(c) (metric_a{})",description:'Sum the metric "metric_a" by each value in label "c"'},{template:"sum(metric_a{})",description:'Total sum of all the series of the metric named "metric_a"'},{template:"max by(dd) (metric_a{})",description:'Grouping the series the metric "metric_a" by the label "dd", get the maximum value of each group'},{template:"max(metric_a{})",description:'Maximum value of all series of the metric "metric_a" '},{template:"avg(metric_a{})",description:'Average value of all the series of metric "metric_a"'},{template:"metric_a{} > 99",description:'Show only the series of metric "metric_a" which currently have value greater than 99'},{template:"metric_a{} / 99",description:'Values for "metric_a" all divided by 99'},{template:"metric_a{} == 99",description:"Show series of metric_a that have value 99"},{template:"sum_over_time(metric_a{}[1h])",description:"Sum each series of metric_a over 1 hour"},{template:"avg_over_time(metric_a{}[1h])",description:"Average of each series of metric_a in a 1 hour period"},{template:"sum(sum_over_time(metric_a{}[1h]))",description:"Sum of all values in all series in a 1 hour period"},{template:"delta(metric_a{}[1m])",description:'Span or delta (maximum - minimum) of values of the metric "metric_a" in a 1 minute period. '},{template:"avg by(g) (avg_over_time(metric_a{}[1h]))",description:'For 1 hour, take each series and find the average, then group by label "g" and find the average of each group'},{template:"max_over_time(metric_a{}[1h])",description:'Maximum values of each series in metric "metric_a" in a 1 hour period'},{template:"metric_a{} * 99",description:"Values of metric_a multiplied by 99"},{template:"metric_a{} < 99",description:"Series of metric_a that have values less than 99"},{template:"max by() (max_over_time(metric_a{}[1h]))",description:"Find maximum value of all series in 1 hour periods"},{template:"topk(99,metric_a{})",description:"First 5 series of metric_a that have the highest values"},{template:"min by(g) (metric_a{})",description:'Minimum values of the series of metric_a grouped by label "g"'},{template:"topk(10,sum by(g) (metric_a{}))",description:"Top 10 of the series of metric_a grouped and summed by the label 'g'"},{template:"avg(avg_over_time(metric_a{}[1h]))",description:"Average of all values inside a 1 hour period"},{template:"quantile by(h) (0.95,metric_a{})",description:'Calculate 95th percentile of metric_a when aggregated by the label "h"'},{template:"avg by(g) (metric_a{} > 99)",description:'Taking all series of metric_a with value greater than 99, group by label "g" and find the average of each group'},{template:"sum(metric_a{}) / 99",description:"Sum of all series of metric_a divided by 99"},{template:"count(sum by(g) (metric_a{}))",description:'Number of series of metric_a grouped by the label "g"'},{template:"max(max_over_time(metric_a{}[1h]))",description:"Find the max value of all series of metric_a in a 1 hour period"}];function F(t,a,r){return{query:t.template.replace("metric_a",a).replace("{}",r),explanation:t.description.replace("metric_a",a)}}function Zt(t,a,r){let s=[];switch(a){case"counter":s=s.concat(Ht.map(n=>F(n,t,r)).sort(()=>Math.random()-.5).slice(0,2)),s=s.concat(G.map(n=>F(n,t,r)).sort(()=>Math.random()-.5).slice(0,3));break;case"gauge":s=s.concat(Vt.map(n=>F(n,t,r)).sort(()=>Math.random()-.5).slice(0,2)),s=s.concat(G.map(n=>F(n,t,r)).sort(()=>Math.random()-.5).slice(0,3));break;case"histogram":s=s.concat(Gt.map(n=>F(n,t,r)).sort(()=>Math.random()-.5).slice(0,2)),s=s.concat(G.map(n=>F(n,t,r)).sort(()=>Math.random()-.5).slice(0,3));break;default:s=s.concat(G.map(n=>F(n,t,r)).sort(()=>Math.random()-.5).slice(0,5));break}return s}const Ae="gpt-3.5-turbo-1106",jt="grafana.promql.templates",{updateInteraction:se}=ne.actions;function Ut(t,a,r){let s="",n="";const u=(0,A._)(t);r.languageProvider.metricsMetadata&&(n=(0,re.nW)(a,r.languageProvider.metricsMetadata)??"",s=(0,re.ws)(a,r.languageProvider.metricsMetadata)??"");const d=u.query.operations.map(i=>{const m=M.Z.getOperationDef(i.id);if(!m)return"";const h=m.renderer(i,m,"<expr>"),y=m.explainHandler?m.explainHandler(i,m):m.documentation;return y?`### ${h}:
${y}`:""}).filter(i=>i!=="").join(`
`);return[{role:"system",content:Rt},{role:"user",content:Ot({documentation:d,metricName:a,metricType:n,metricMetadata:s,query:t})}]}function Kt({promql:t,question:a,metricType:r,labels:s,templates:n}){return[{role:"system",content:Dt},{role:"user",content:Wt({promql:t,question:a,metricType:r,labels:s,templates:n})}]}async function Fe(t,a,r,s,n,u){const d=s.suggestions[n].query,i=Ut(d,r.metric,u),m=s;return q.lA({model:Ae,messages:i,temperature:0}).pipe(q.XE()).subscribe(h=>{const y=m.suggestions.map((P,v)=>n===v?{query:m.suggestions[n].query,explanation:h}:P),g={idx:a,interaction:{...m,suggestions:y,explanationIsLoading:!1}};t(se(g))})}function V(t,a){for(const r of t)if(!a.includes(r))return!1;return!0}function Yt(t,a){if(new Set(["up","scrape_duration_seconds","scrape_samples_post_metric_relabeling","scrape_series_added","scrape_samples_scraped","ALERTS","ALERTS_FOR_STATE"]).has(t))return"counter";if(t.startsWith(":"))return"gauge";if(t.endsWith("_info")||t.endsWith("_created")||t.endsWith("_total"))return"counter";const s=t.lastIndexOf("_");if(s<0)return"gauge";const[n,u]=[t.slice(0,s),t.slice(s+1)];if(["bucket","count","sum"].includes(u)){let i=[`${n}_bucket`,`${n}_count`,`${n}_sum`,n];return V(i,a)?"histogram,summary":(i=[`${n}_bucket`,`${n}_count`,`${n}_sum`],V(i,a)?"histogram":(i=[`${n}_sum`,`${n}_count`,n],V(i,a)?"summary":"counter"))}const d=[`${t}_sum`,`${t}_count`,t];return V(d,a)?a.includes(`${t}_bucket`)?"histogram,summary":"summary":"gauge"}function Xt(t){return t.map(a=>({metric_type:{$eq:a}}))}function Jt(t){return t.endsWith("_bucket")||t.endsWith("_count")||t.endsWith("_sum")?t.slice(0,t.lastIndexOf("_")):t}async function _t(){const t=q.am().then(r=>r.ok),a=qt().then(r=>r.ok);return Promise.all([t,a]).then(r=>r.every(s=>s))}async function oe(t,a,r,s,n,u){const d=u||Ie(T.Historical);let i="";if(n.languageProvider.metricsMetadata||await n.languageProvider.loadMetricsMetadata(),n.languageProvider.metricsMetadata){const m=Jt(r.metric);i=(0,re.nW)(m,n.languageProvider.metricsMetadata)??""}if(i===""&&(i=Yt(r.metric,n.languageProvider.metrics)),d.suggestionType===T.Historical)return new Promise(m=>setTimeout(()=>{const h=Zt(r.metric,i,M.Z.renderLabels(r.labels)),y={idx:a,interaction:{...d,suggestions:h,isLoading:!1}};t(se(y)),m()},1e3));{const m=await n.languageProvider.fetchSeriesLabelsMatch(r.metric);let h={metric:r.metric,labels:Object.keys(m).filter(v=>v!=="__name__").join(",")},y=[];u?.suggestionType===T.AI&&(h={...h,prompt:u.prompt},y=await zt({query:u.prompt,collection:jt,topK:5,filter:{$or:Xt(i.split(",").concat(["*"]))}}),(0,N.ff)("grafana_prometheus_promqail_vector_results",{metric:r.metric,prompt:u.prompt,results:y}));const g=y.map(v=>`${v.payload.promql} | ${v.payload.description} (score=${(v.score*100).toFixed(1)})`).join(`
`),P=Kt({promql:r.metric,question:u?u.prompt:"",metricType:i,labels:s.join(", "),templates:g});return q.lA({model:Ae,messages:P,temperature:.5}).pipe(q.XE()).subscribe(v=>{const p={idx:a,interaction:{...d,suggestions:[{query:v,explanation:""}],isLoading:!1}};t(se(p))})}}const{showStartingMessage:ea,indicateCheckbox:ta,addInteraction:Z,updateInteraction:ie}=ne.actions,le="SKIP_STARTING_MESSAGE",aa=t=>{const{query:a,closeDrawer:r,onChange:s,datasource:n}=t,u=$.Z.getBool(le,!1),[d,i]=(0,e.useReducer)(ne.reducer,we(a,!u)),[m,h]=(0,e.useState)([]),y=d.interactions.reduce((f,c)=>f+c.suggestions.length,0),g=(0,e.useRef)(null),P=()=>{g&&g?.current?.scrollIntoView({behavior:"smooth"})};(0,e.useEffect)(()=>{P()},[d.interactions.length,y]),(0,e.useEffect)(()=>{(async()=>{let c;n.hasLabelsMatchAPISupport()?c=await n.languageProvider.fetchSeriesLabelsMatch(a.metric):c=await n.languageProvider.fetchSeriesLabels(a.metric),h(Object.keys(c))})()},[a,n]);const v=(0,w.l4)(),p=j(v);return e.createElement("div",{className:p.containerPadding},e.createElement("div",{className:p.header},e.createElement("h3",null,"Query advisor"),e.createElement(S.zx,{icon:"times",fill:"text",variant:"secondary",onClick:r})),e.createElement("div",null,e.createElement("div",{className:p.iconSection},e.createElement("img",{src:ke,alt:"AI logo color"})," Assistant"),d.showStartingMessage?e.createElement(e.Fragment,null,e.createElement("div",{className:p.dataList},e.createElement("ol",null,e.createElement("li",{className:p.textPadding},"Query Advisor suggests queries based on a metric and requests you type in."),e.createElement("li",{className:p.textPadding},"Query Advisor sends Prometheus metrics, labels and metadata to the LLM provider you've configured. Be sure to align its usage with your company's internal policies."),e.createElement("li",{className:p.textPadding},"An AI-suggested query may not fully answer your question. Always take a moment to understand a query before you use it."))),e.createElement(Mt.b,{title:"",severity:"info",key:"promqail-llm-app",className:(0,l.cx)(p.textPadding,p.noMargin)},"Query Advisor is currently in Private Preview. Feedback is appreciated and can be provided on explanations and suggestions."),e.createElement("div",{className:p.textPadding},e.createElement(Lt.X,{checked:d.indicateCheckbox,value:d.indicateCheckbox,onChange:()=>{const f=$.Z.getBool(le,!1);$.Z.set(le,!f),i(ta(!f))},label:"Don't show this message again"})),e.createElement("div",{className:p.rightButtonsWrapper},e.createElement("div",{className:p.rightButtons},e.createElement(S.zx,{className:p.leftButton,fill:"outline",variant:"secondary",onClick:r},"Cancel"),e.createElement(S.zx,{fill:"solid",variant:"primary",onClick:()=>i(ea(!1)),"data-testid":R.securityInfoButton},"Continue")))):e.createElement("div",{className:p.bodySmall},e.createElement("div",{className:p.textPadding},"Here is the metric you have selected:"),e.createElement("div",{className:p.infoContainerWrapper},e.createElement("div",{className:p.infoContainer},e.createElement("table",{className:p.metricTable},e.createElement("tbody",null,e.createElement("tr",null,e.createElement("td",{className:p.metricTableName},"metric"),e.createElement("td",{className:p.metricTableValue},d.query.metric),e.createElement("td",null,e.createElement(S.zx,{fill:"outline",variant:"secondary",onClick:r,className:p.metricTableButton,size:"sm"},"Choose new metric"))),d.query.labels.map((f,c)=>{const E=c===0?"labels":"";return e.createElement("tr",{key:`${f.label}-${c}`},e.createElement("td",null,E),e.createElement("td",{className:p.metricTableValue},`${f.label}${f.op}${f.value}`),e.createElement("td",null," "))}))))),!d.askForQueryHelp&&d.interactions.length===0&&e.createElement(e.Fragment,null,e.createElement("div",{className:p.queryQuestion},"Do you know what you want to query?"),e.createElement("div",{className:p.rightButtonsWrapper},e.createElement("div",{className:p.rightButtons},e.createElement(S.zx,{className:p.leftButton,fill:"solid",variant:"secondary","data-testid":R.clickForHistorical,onClick:()=>{const c=T.Historical;i(Z({suggestionType:c,isLoading:!0})),(0,N.ff)("grafana_prometheus_promqail_know_what_you_want_to_query",{promVisualQuery:a,doYouKnow:"no"}),oe(i,0,a,m,n)}},"No"),e.createElement(S.zx,{fill:"solid",variant:"primary","data-testid":R.clickForAi,onClick:()=>{(0,N.ff)("grafana_prometheus_promqail_know_what_you_want_to_query",{promVisualQuery:a,doYouKnow:"yes"});const f=!1,c=T.AI;i(Z({suggestionType:c,isLoading:f}))}},"Yes")))),d.interactions.map((f,c)=>e.createElement("div",{key:c},f.suggestionType===T.AI?e.createElement(e.Fragment,null,e.createElement("div",{className:p.textPadding},"What kind of data do you want to see with your metric?"),e.createElement("div",{className:(0,l.cx)(p.secondaryText,p.bottomMargin)},e.createElement("div",null,"You do not need to enter in a metric or a label again in the prompt."),e.createElement("div",null,"Example: I want to monitor request latency, not errors.")),e.createElement("div",{className:p.inputPadding},e.createElement(kt.I,{value:f.prompt,spellCheck:!1,placeholder:"Enter prompt",disabled:f.suggestions.length>0,onChange:E=>{const x=E.currentTarget.value,k={idx:c,interaction:{...f,prompt:x}};i(ie(k))}})),f.suggestions.length===0?f.isLoading?e.createElement(e.Fragment,null,e.createElement("div",{className:p.loadingMessageContainer},"Waiting for OpenAI ",e.createElement(_.$,{className:p.floatRight}))):e.createElement(e.Fragment,null,e.createElement("div",{className:p.rightButtonsWrapper},e.createElement("div",{className:p.rightButtons},e.createElement(S.zx,{className:p.leftButton,fill:"outline",variant:"secondary",onClick:r},"Cancel"),e.createElement(S.zx,{className:p.leftButton,fill:"outline",variant:"secondary",onClick:()=>{const E={...f,suggestionType:T.Historical,isLoading:!0},x={idx:c,interaction:E};(0,N.ff)("grafana_prometheus_promqail_suggest_query_instead",{promVisualQuery:a}),i(ie(x)),oe(i,c,a,m,n,E)}},"Suggest queries instead"),e.createElement(S.zx,{fill:"solid",variant:"primary","data-testid":R.submitPrompt+c,onClick:()=>{const E={...f,isLoading:!0},x={idx:c,interaction:E};(0,N.ff)("grafana_prometheus_promqail_prompt_submitted",{promVisualQuery:a,prompt:f.prompt}),i(ie(x)),oe(i,c,a,m,n,f)}},"Submit")))):e.createElement(Le,{suggestionType:T.AI,querySuggestions:f.suggestions,closeDrawer:r,nextInteraction:()=>{const x=T.AI;i(Z({suggestionType:x,isLoading:!1}))},queryExplain:E=>f.suggestions[E].explanation===""?Fe(i,c,a,f,E,n):f.suggestions[E].explanation,onChange:s,prompt:f.prompt??""})):f.isLoading?e.createElement(e.Fragment,null,e.createElement("div",{className:p.loadingMessageContainer},"Waiting for OpenAI ",e.createElement(_.$,{className:p.floatRight}))):e.createElement(Le,{suggestionType:T.Historical,querySuggestions:f.suggestions,closeDrawer:r,nextInteraction:()=>{const x=T.AI;i(Z({suggestionType:x,isLoading:!1}))},queryExplain:E=>f.suggestions[E].explanation===""?Fe(i,c,a,f,E,n):f.suggestions[E].explanation,onChange:s,prompt:f.prompt??""}))))),e.createElement("div",{ref:g}))},j=t=>({sectionPadding:(0,l.css)({padding:"20px"}),header:(0,l.css)({display:"flex",button:{marginLeft:"auto"}}),iconSection:(0,l.css)({padding:"0 0 10px 0",color:`${t.colors.text.secondary}`,img:{paddingRight:"4px"}}),rightButtonsWrapper:(0,l.css)({display:"flex"}),rightButtons:(0,l.css)({marginLeft:"auto"}),leftButton:(0,l.css)({marginRight:"10px"}),dataList:(0,l.css)({padding:"0px 28px 0px 28px"}),textPadding:(0,l.css)({paddingBottom:"12px"}),containerPadding:(0,l.css)({padding:"28px"}),infoContainer:(0,l.css)({border:`${t.colors.border.strong}`,padding:"16px",backgroundColor:`${t.colors.background.secondary}`,borderRadius:"8px",borderBottomLeftRadius:0}),infoContainerWrapper:(0,l.css)({paddingBottom:"24px"}),metricTable:(0,l.css)({width:"100%"}),metricTableName:(0,l.css)({width:"15%"}),metricTableValue:(0,l.css)({fontFamily:`${t.typography.fontFamilyMonospace}`,fontSize:`${t.typography.bodySmall.fontSize}`,overflow:"scroll",textWrap:"nowrap",maxWidth:"150px",width:"60%",maskImage:"linear-gradient(to right, rgba(0, 0, 0, 1) 90%, rgba(0, 0, 0, 0))"}),metricTableButton:(0,l.css)({float:"right"}),queryQuestion:(0,l.css)({textAlign:"end",padding:"8px 0"}),secondaryText:(0,l.css)({color:`${t.colors.text.secondary}`}),loadingMessageContainer:(0,l.css)({border:`${t.colors.border.strong}`,padding:"16px",backgroundColor:`${t.colors.background.secondary}`,marginBottom:"20px",borderRadius:"8px",color:`${t.colors.text.secondary}`,fontStyle:"italic"}),floatRight:(0,l.css)({float:"right"}),codeText:(0,l.css)({fontFamily:`${t.typography.fontFamilyMonospace}`,fontSize:`${t.typography.bodySmall.fontSize}`}),bodySmall:(0,l.css)({fontSize:`${t.typography.bodySmall.fontSize}`}),explainPadding:(0,l.css)({paddingLeft:"26px"}),bottomMargin:(0,l.css)({marginBottom:"20px"}),topPadding:(0,l.css)({paddingTop:"22px"}),doc:(0,l.css)({textDecoration:"underline"}),afterButtons:(0,l.css)({display:"flex",justifyContent:"flex-end"}),feedbackStyle:(0,l.css)({margin:0,textAlign:"right",paddingTop:"22px",paddingBottom:"22px"}),nextInteractionHeight:(0,l.css)({height:"88px"}),center:(0,l.css)({display:"flex",alignItems:"center",justifyContent:"center"}),inputPadding:(0,l.css)({paddingBottom:"24px"}),querySuggestion:(0,l.css)({display:"flex",flexWrap:"nowrap"}),longCode:(0,l.css)({width:"90%",textWrap:"nowrap",overflow:"scroll",maskImage:"linear-gradient(to right, rgba(0, 0, 0, 1) 90%, rgba(0, 0, 0, 0))",div:{display:"inline-block"}}),useButton:(0,l.css)({marginLeft:"auto"}),suggestionFeedback:(0,l.css)({textAlign:"left"}),feedbackQuestion:(0,l.css)({display:"flex",padding:"8px 0px",h6:{marginBottom:0},i:{marginTop:"1px"}}),explationTextInput:(0,l.css)({paddingLeft:"24px"}),submitFeedback:(0,l.css)({padding:"16px 0"}),noMargin:(0,l.css)({margin:0}),enableButtonTooltip:(0,l.css)({padding:8}),enableButtonTooltipText:(0,l.css)({color:`${t.colors.text.secondary}`,ul:{marginLeft:16}}),link:(0,l.css)({color:`${t.colors.text.link} !important`})}),R={promQail:"prom-qail",securityInfoButton:"security-info-button",clickForHistorical:"click-for-historical",clickForAi:"click-for-ai",submitPrompt:"submit-prompt",refinePrompt:"refine-prompt"};var ce=o(14607);function ra(t){const{llmAppEnabled:a,metric:r,setShowDrawer:s}=t,n=!a,u=!r,d=(0,w.l4)(),i=j(d),m=()=>e.createElement(S.zx,{variant:"secondary",onClick:()=>{(0,N.ff)("grafana_prometheus_promqail_ai_button_clicked",{metric:r}),s(!0)},disabled:!r||!a},e.createElement("img",{height:16,src:ke,alt:"AI logo black and white"}),"\xA0","Get query suggestions"),h=e.createElement(ce.u,{content:"First, select a metric.",placement:"bottom-end"},m()),y=e.createElement(ce.u,{interactive:!0,placement:"auto-end",content:e.createElement("div",{className:i.enableButtonTooltip},e.createElement("h6",null,"Query Advisor is disabled"),e.createElement("div",{className:i.enableButtonTooltipText},"To enable Query Advisor you must:"),e.createElement("div",{className:i.enableButtonTooltipText},e.createElement("ul",null,e.createElement("li",null,e.createElement("a",{href:"https://grafana.com/docs/grafana-cloud/alerting-and-irm/machine-learning/llm-plugin/",target:"_blank",rel:"noreferrer noopener",className:i.link},"Install and enable the LLM plugin")),e.createElement("li",null,"Select a metric"))))},m());return n?y:u?h:m()}const Be=Ce.config.featureToggles.prometheusPromQAIL,ue=e.memo(t=>{const{datasource:a,query:r,onChange:s,onRunQuery:n,data:u,showExplain:d}=t,[i,m]=(0,e.useState)(),[h,y]=(0,e.useState)(!1),[g,P]=(0,e.useState)(!1),v={grammar:Y.ZP,name:"promql"},p=a.getInitHints();return(0,e.useEffect)(()=>{async function f(){const c=await _t();P(c)}f()},[]),e.createElement(e.Fragment,null,Be&&h&&e.createElement(gt.d,{closeOnMaskClick:!1,onClose:()=>y(!1)},e.createElement(aa,{query:r,closeDrawer:()=>y(!1),onChange:s,datasource:a})),e.createElement(X.p,null,e.createElement(bt.U,{query:r,onChange:s,datasource:a})),p.length?e.createElement("div",{className:"query-row-break"},e.createElement("div",{className:"prom-query-field-info text-warning"},p[0].label," ",p[0].fix?e.createElement("button",{type:"button",className:"text-warning"},p[0].fix.label):null)):null,d&&e.createElement(ht.B,{stepNumber:1,title:e.createElement(K.U,{query:`${r.metric} ${M.Z.renderLabels(r.labels)}`,lang:v})},Nt.A),e.createElement(vt.B,null,e.createElement(ft.P,{queryModeller:M.Z,datasource:a,query:r,onChange:s,onRunQuery:n,highlightedOp:i}),Be&&e.createElement("div",{className:(0,l.css)({padding:"0 0 0 6px"})},e.createElement(ra,{llmAppEnabled:g,metric:r.metric,setShowDrawer:y})),e.createElement(Et.L,{datasource:a,query:r,onChange:s,data:u,queryModeller:M.Z,buildVisualQueryFromString:A._})),d&&e.createElement(yt.V,{lang:v,query:r,stepNumber:2,queryModeller:M.Z,onMouseEnter:f=>m(f),onMouseLeave:()=>m(void 0)}),r.binaryQueries&&r.binaryQueries.length>0&&e.createElement(Qt,{query:r,datasource:a,onChange:s,onRunQuery:n,showExplain:d}))});ue.displayName="PromQueryBuilder";var na=o(33614);function sa({query:t}){return t?e.createElement(X.p,null,e.createElement(na.s,null,e.createElement(K.U,{query:t,lang:{grammar:Y.ZP,name:"promql"}}))):null}var oa=o(74463);const me=Ce.config.featureToggles.prometheusMetricEncyclopedia;function ia(t){const{query:a,onChange:r,onRunQuery:s,datasource:n,data:u,showExplain:d}=t,[i,m]=(0,e.useReducer)($e.reducer,{expr:a.expr});(0,e.useEffect)(()=>{m(ua(a.expr)),me&&m(ma({useBackend:a.useBackend??!1,disableTextWrap:a.disableTextWrap??!1,fullMetaSearch:a.fullMetaSearch??!1,includeNullMetadata:a.includeNullMetadata??!0}))},[a]),(0,e.useEffect)(()=>{n.languageProvider.start(u?.timeRange)},[u?.timeRange,n.languageProvider]);const h=y=>{const g=M.Z.renderQuery(y);if(m(ca({visQuery:y,expr:g})),me){const P=(0,oa.Gw)(y);r({...t.query,expr:g,...P})}else r({...t.query,expr:g})};return i.visQuery?e.createElement(e.Fragment,null,e.createElement(ue,{query:i.visQuery,datasource:n,onChange:h,onRunQuery:s,data:u,showExplain:d}),e.createElement(sa,{query:a.expr})):null}const la={expr:""},$e=(0,Pe.oM)({name:"prom-builder-container",initialState:la,reducers:{visualQueryChange:(t,a)=>{t.expr=a.payload.expr,t.visQuery=a.payload.visQuery},exprChanged:(t,a)=>{if(!t.visQuery||t.expr!==a.payload){t.expr=a.payload;const r=(0,A._)(a.payload??"");t.visQuery=r.query}},setMetricsModalSettings:(t,a)=>{t.visQuery&&me&&(t.visQuery.useBackend=a.payload.useBackend,t.visQuery.disableTextWrap=a.payload.disableTextWrap,t.visQuery.fullMetaSearch=a.payload.fullMetaSearch,t.visQuery.includeNullMetadata=a.payload.includeNullMetadata)}}}),{visualQueryChange:ca,exprChanged:ua,setMetricsModalSettings:ma}=$e.actions;var B=o(73688),da=o(44294),ze=o(5106),qe=o(69690),Re=o(68921),pa=o(114);function ga({datasource:t,onChange:a,query:r,...s}){const[n,u]=(0,e.useState)(null),d=(0,w.wW)(ha),i=(0,qe.Z)(n);(0,e.useEffect)(()=>{t.exemplarsAvailable?r.instant&&!r.range?(u("Exemplars are not available for instant queries"),a(!1)):(u(null),i&&!n&&a(!0)):(u("Exemplars for this query are not available"),a(!1))},[t.exemplarsAvailable,r.instant,r.range,a,i,n]);const m=(0,l.cx)({[d.activeIcon]:!!r.exemplar},d.eyeIcon);return e.createElement(pa.W,{width:"auto","data-testid":s["data-testid"]},e.createElement(ce.u,{content:n??""},e.createElement("div",{className:d.iconWrapper},"Exemplars",e.createElement(Te.h,{name:"eye",tooltip:r.exemplar?"Disable query with exemplars":"Enable query with exemplars",disabled:!!n,className:m,onClick:()=>{a(!r.exemplar)}}))))}function ha(t){return{eyeIcon:(0,l.css)`
      margin-left: ${t.spacing(2)};
    `,activeIcon:(0,l.css)`
      color: ${t.colors.primary.main};
    `,iconWrapper:(0,l.css)`
      display: flex;
      align-items: center;
    `}}const fa=(0,e.memo)(({query:t,datasource:a,onChange:r,onRunQuery:s})=>{const n=Oe(!0),u=(0,qe.Z)(t),d=(0,e.useCallback)(g=>{(!(0,W.isEqual)(t,u)||g!==t.exemplar)&&r({...t,exemplar:g})},[u,t,r]);function i(g){r({...t,interval:g})}function m(g){g.currentTarget.value!==t.interval&&i(g.currentTarget.value)}function h(g){g.key==="Enter"&&g.shiftKey&&s()}const y=De(t,r);return e.createElement("div",{"aria-label":"Prometheus extra field",className:"gf-form-inline","data-testid":de.extraFieldEditor},e.createElement("div",{"data-testid":de.queryTypeField,className:(0,l.cx)("gf-form explore-input-margin",(0,l.css)`
            flex-wrap: nowrap;
          `),"aria-label":"Query type field"},e.createElement(Re.c,{width:"auto"},"Query type"),e.createElement(ze.S,{options:n,value:t.range&&t.instant?"both":t.instant?"instant":"range",onChange:y})),e.createElement("div",{"data-testid":de.stepField,className:(0,l.cx)("gf-form",(0,l.css)`
            flex-wrap: nowrap;
          `),"aria-label":"Step field"},e.createElement(Re.c,{width:6,tooltip:"Time units and built-in variables can be used here, for example: $__interval, $__rate_interval, 5s, 1m, 3h, 1d, 1y (Default if no unit is specified: s)"},"Min step"),e.createElement("input",{type:"text",className:"gf-form-input width-4",placeholder:"auto",onChange:m,onKeyDown:h,value:t.interval??""})),e.createElement(ga,{onChange:d,datasource:a,query:t}))});fa.displayName="PromExploreExtraField";function Oe(t){const a=[{value:"range",label:"Range",description:"Run query over a range of time"},{value:"instant",label:"Instant",description:'Run query against a single point in time. For this query, the "To" time is used'}];return t&&a.push({value:"both",label:"Both",description:"Run an Instant query and a Range query"}),a}function De(t,a){return r=>{a(r==="instant"?{...t,instant:!0,range:!1,exemplar:!1}:r==="range"?{...t,instant:!1,range:!0}:{...t,instant:!0,range:!0})}}const de={extraFieldEditor:"prom-editor-extra-field",stepField:"prom-editor-extra-field-step",queryTypeField:"prom-editor-extra-field-query-type"};var ya=o(15880);const pe=[{label:"Auto",value:C.pD.Auto,description:"Only includes unique labels"},{label:"Verbose",value:C.pD.Verbose,description:"All label names and values"},{label:"Custom",value:C.pD.Custom,description:"Provide a naming template"}],We=e.memo(({legendFormat:t,onChange:a,onRunQuery:r})=>{const s=He(t),n=(0,e.useRef)(null),u=i=>{let m=i.currentTarget.value;m.length===0&&(m=C.pD.Auto),m!==t&&(a(m),r())},d=i=>{switch(i.value){case C.pD.Auto:a(C.pD.Auto);break;case C.pD.Custom:a("{{label_name}}"),setTimeout(()=>{n.current?.focus(),n.current?.setSelectionRange(2,12,"forward")},10);break;case C.pD.Verbose:a("");break}r()};return e.createElement(B.S,{label:"Legend",tooltip:"Series name override or template. Ex. {{hostname}} will be replaced with label value for hostname."},e.createElement(e.Fragment,null,s===C.pD.Custom&&e.createElement(J.H,{id:"legendFormat",minWidth:22,placeholder:"auto",defaultValue:t,onCommitChange:u,ref:n}),s!==C.pD.Custom&&e.createElement(z.Ph,{inputId:"legend.mode",isSearchable:!1,placeholder:"Select legend mode",options:pe,width:22,onChange:d,value:pe.find(i=>i.value===s)})))});We.displayName="PromQueryLegendEditor";function He(t){return t===C.pD.Auto?C.pD.Auto:t==null||t===""?C.pD.Verbose:C.pD.Custom}function va(t){const a=He(t);return a!==C.pD.Custom?pe.find(r=>r.value===a)?.label:t}const Ge=e.memo(({query:t,app:a,onChange:r,onRunQuery:s})=>{const n=v=>{r({...t,format:v.value}),s()},u=v=>{r({...t,interval:v.currentTarget.value}),s()},d=Oe(a===L.zj.Explore||a===L.zj.Correlations||a===L.zj.PanelEditor),i=De(t,r),m=v=>{const p=v.currentTarget.checked;r({...t,exemplar:p}),s()},h=v=>{r({...t,intervalFactor:v.value}),s()},y=ge.find(v=>v.value===t.format)||ge[0],g=Ea(t),P=d.find(v=>v.value===g).label;return e.createElement(X.p,null,e.createElement(ya.d,{title:"Options",collapsedInfo:ba(t,y.label,P,a)},e.createElement(We,{legendFormat:t.legendFormat,onChange:v=>r({...t,legendFormat:v}),onRunQuery:s}),e.createElement(B.S,{label:"Min step",tooltip:e.createElement(e.Fragment,null,"An additional lower limit for the step parameter of the Prometheus query and for the"," ",e.createElement("code",null,"$__interval")," and ",e.createElement("code",null,"$__rate_interval")," variables.")},e.createElement(J.H,{type:"text","aria-label":"Set lower limit for the step parameter",placeholder:"auto",minWidth:10,onCommitChange:u,defaultValue:t.interval})),e.createElement(B.S,{label:"Format"},e.createElement(z.Ph,{value:y,allowCustomValue:!0,onChange:n,options:ge})),e.createElement(B.S,{label:"Type"},e.createElement(ze.S,{options:d,value:g,onChange:i})),Ve(t,a)&&e.createElement(B.S,{label:"Exemplars"},e.createElement(da.r,{value:t.exemplar||!1,onChange:m})),t.intervalFactor&&t.intervalFactor>1&&e.createElement(B.S,{label:"Resolution"},e.createElement(z.Ph,{"aria-label":"Select resolution",isSearchable:!1,options:Ze,onChange:h,value:Ze.find(v=>v.value===t.intervalFactor)}))))});function Ve(t,a){return!(a===L.zj.UnifiedAlerting||!t.range)}function Ea(t){return t.range&&t.instant?"both":t.instant?"instant":"range"}function ba(t,a,r,s){const n=[];return n.push(`Legend: ${va(t.legendFormat)}`),n.push(`Format: ${a}`),n.push(`Step: ${t.interval??"auto"}`),n.push(`Type: ${r}`),Ve(t,s)&&(t.exemplar?n.push("Exemplars: true"):n.push("Exemplars: false")),n}Ge.displayName="PromQueryBuilderOptions";var xa=o(68513);const ge=[{label:"Time series",value:"time_series"},{label:"Table",value:"table"},{label:"Heatmap",value:"heatmap"}],Ze=(0,W.map)([1,2,3,4,5,10],t=>({value:t,label:"1/"+t})),je=e.memo(t=>{const{onChange:a,onRunQuery:r,data:s,app:n,onAddQuery:u,datasource:{defaultEditor:d},queries:i}=t,[m,h]=(0,e.useState)(!1),[y,g]=(0,e.useState)(!1),[P,v]=(0,e.useState)(!1),{flag:p,setFlag:f}=(0,be.P5)(be.ar),c=pt(t.query,n,d),E=c.editorMode,x=(0,e.useCallback)(b=>{if((0,N.ff)("user_grafana_prometheus_editor_mode_clicked",{newEditor:b,previousEditor:c.editorMode??"",newQuery:!c.expr,app:n??""}),b===I.c.Builder&&(0,A._)(c.expr||"").errors.length){h(!0);return}Se(c,b,a)},[a,c,n]);(0,e.useEffect)(()=>{v(!1)},[s]);const k=b=>{(0,W.isEqual)(b,t.query)||v(!0),a(b)},O=b=>{f(b.currentTarget.checked)};return e.createElement(e.Fragment,null,e.createElement(tt.s,{isOpen:m,title:"Parsing error: Switch to the builder mode?",body:"There is a syntax error, or the query structure cannot be visualized when switching to the builder mode. Parts of the query may be lost. ",confirmText:"Continue",onConfirm:()=>{Se(c,I.c.Builder,a),h(!1)},onDismiss:()=>h(!1)}),e.createElement(lt,{isOpen:y,onClose:()=>g(!1),query:c,queries:i,app:n,onChange:a,onAddQuery:u}),e.createElement(_e.K,null,e.createElement(S.zx,{"data-testid":Je.wl.components.QueryBuilder.queryPatterns,variant:"secondary",size:"sm",onClick:()=>g(b=>!b)},"Kick start your query"),e.createElement(mt.n,{label:"Explain",value:p,onChange:O}),e.createElement(ve.B,{grow:1}),n!==L.zj.Explore&&n!==L.zj.Correlations&&e.createElement(S.zx,{variant:P?"primary":"secondary",size:"sm",onClick:r,icon:s?.state===ye.Gu.Loading?"spinner":void 0,disabled:s?.state===ye.Gu.Loading},"Run queries"),e.createElement(ut.k,{mode:E,onChange:x})),e.createElement(et.T,{v:.5}),e.createElement(Ee._,null,E===I.c.Code&&e.createElement(xa.j,{...t,query:c,showExplain:p,onChange:k}),E===I.c.Builder&&e.createElement(ia,{query:c,datasource:t.datasource,onChange:k,onRunQuery:t.onRunQuery,data:s,showExplain:p}),e.createElement(Ge,{query:c,app:t.app,onChange:a,onRunQuery:r})))});je.displayName="PromQueryEditorSelector";var Sa=o(8864);function Pa(t){const{datasource:a,query:r,range:s,data:n,onChange:u,onRunQuery:d}=t;return e.createElement(Sa.Z,{datasource:a,query:r,onRunQuery:d,onChange:u,history:[],range:s,data:n,"data-testid":Ca.editor})}const Ca={editor:"prom-editor-cloud-alerting"};function Ta(t){const{app:a}=t;switch(a){case L.zj.CloudAlerting:return e.createElement(Pa,{...t});default:return e.createElement(je,{...t})}}const Qa=(0,e.memo)(Ta);var Na=o(28017),Ma=o(63779);const La=new Ke.hf(Ma.vQ).setQueryEditor(Qa).setConfigEditor(Na.Z5).setQueryEditorHelp(Xe)}}]);

//# sourceMappingURL=1697.ba74e2de8c65e37f1de4.js.map