-
${t.model} ${t.provider?`(${t.provider})`:""}
-
-
-
-
-
- | Cost Type |
- Per Request |
- ${null!==t.daily_cost?"Daily | ":""}
- ${null!==t.monthly_cost?"Monthly | ":""}
-
-
- | Input Cost |
- ${tL(t.input_cost_per_request)} |
- ${null!==t.daily_cost?`${tL(t.daily_input_cost)} | `:""}
- ${null!==t.monthly_cost?`${tL(t.monthly_input_cost)} | `:""}
-
-
- | Output Cost |
- ${tL(t.output_cost_per_request)} |
- ${null!==t.daily_cost?`${tL(t.daily_output_cost)} | `:""}
- ${null!==t.monthly_cost?`${tL(t.monthly_output_cost)} | `:""}
-
-
- | Margin/Fee |
- ${tL(t.margin_cost_per_request)} |
- ${null!==t.daily_cost?`${tL(t.daily_margin_cost)} | `:""}
- ${null!==t.monthly_cost?`${tL(t.monthly_margin_cost)} | `:""}
-
-
- | Total |
- ${tL(t.cost_per_request)} |
- ${null!==t.daily_cost?`${tL(t.daily_cost)} | `:""}
- ${null!==t.monthly_cost?`${tL(t.monthly_cost)} | `:""}
-
-
-
- `}).join("")}
-
-
-
-
- `;t.document.write(l),t.document.close(),t.onload=()=>{t.print()}})(e),a(!1)},children:[(0,t.jsx)(tT.FilePdfOutlined,{className:"mr-3 text-red-500"}),"Export as PDF"]}),(0,t.jsxs)("button",{className:"flex items-center w-full px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors",onClick:()=>{(e=>{let t=e.entries.filter(e=>null!==e.result),s=[["LLM Multi-Model Cost Estimate Report"],["Generated",new Date().toLocaleString()],[""]];for(let a of(s.push(["COMBINED TOTALS"],["Total Per Request",e.totals.cost_per_request.toString()],["Total Daily",e.totals.daily_cost?.toString()||"-"],["Total Monthly",e.totals.monthly_cost?.toString()||"-"],["Margin Per Request",e.totals.margin_per_request.toString()],["Daily Margin",e.totals.daily_margin?.toString()||"-"],["Monthly Margin",e.totals.monthly_margin?.toString()||"-"],[""]),s.push(["Model","Provider","Input Tokens","Output Tokens","Requests/Day","Requests/Month","Cost/Request","Daily Cost","Monthly Cost","Input Cost/Req","Output Cost/Req","Margin/Req"]),t)){let e=a.result;s.push([e.model,e.provider||"-",e.input_tokens.toString(),e.output_tokens.toString(),e.num_requests_per_day?.toString()||"-",e.num_requests_per_month?.toString()||"-",e.cost_per_request.toString(),e.daily_cost?.toString()||"-",e.monthly_cost?.toString()||"-",e.input_cost_per_request.toString(),e.output_cost_per_request.toString(),e.margin_cost_per_request.toString()])}let a=new Blob([s.map(e=>e.map(e=>`"${e}"`).join(",")).join("\n")],{type:"text/csv;charset=utf-8;"}),l=window.URL.createObjectURL(a),r=document.createElement("a");r.href=l,r.download=`cost_estimate_multi_model_${new Date().toISOString().split("T")[0]}.csv`,document.body.appendChild(r),r.click(),document.body.removeChild(r),window.URL.revokeObjectURL(l)})(e),a(!1)},children:[(0,t.jsx)(tP,{className:"mr-3 text-green-600"}),"Export as CSV"]})]})]}):null},tE=e=>null==e?"-":0===e?"$0":e<1e-4?`$${e.toExponential(2)}`:e<1?`$${e.toFixed(4)}`:`$${(0,tC.formatNumberWithCommas)(e,2,!0)}`,tO=({result:e,loading:s,timePeriod:a})=>{let l="day"===a?"Daily":"Monthly",r="day"===a?e.daily_cost:e.monthly_cost,i="day"===a?e.daily_input_cost:e.monthly_input_cost,n="day"===a?e.daily_output_cost:e.monthly_output_cost,o="day"===a?e.daily_margin_cost:e.monthly_margin_cost,d="day"===a?e.num_requests_per_day:e.num_requests_per_month;return(0,t.jsxs)("div",{className:"space-y-3 bg-gray-50 p-4 rounded-lg",children:[s&&(0,t.jsxs)("div",{className:"flex items-center gap-2 text-gray-500 text-sm",children:[(0,t.jsx)(eS.Spin,{indicator:(0,t.jsx)(tN.LoadingOutlined,{spin:!0}),size:"small"}),(0,t.jsx)("span",{children:"Updating..."})]}),(0,t.jsxs)("div",{className:"grid grid-cols-4 gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(e_.Text,{className:"text-xs text-gray-500 block",children:"Total/Request"}),(0,t.jsx)(e_.Text,{className:"text-base font-semibold text-blue-600",children:tE(e.cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(e_.Text,{className:"text-xs text-gray-500 block",children:"Input Cost"}),(0,t.jsx)(e_.Text,{className:"text-sm",children:tE(e.input_cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(e_.Text,{className:"text-xs text-gray-500 block",children:"Output Cost"}),(0,t.jsx)(e_.Text,{className:"text-sm",children:tE(e.output_cost_per_request)})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(e_.Text,{className:"text-xs text-gray-500 block",children:"Margin Fee"}),(0,t.jsx)(e_.Text,{className:`text-sm ${e.margin_cost_per_request>0?"text-amber-600":""}`,children:tE(e.margin_cost_per_request)})]})]}),null!==r&&(0,t.jsxs)("div",{className:"grid grid-cols-4 gap-4 pt-2 border-t border-gray-200",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)(e_.Text,{className:"text-xs text-gray-500 block",children:[l," Total (",null==d?"-":(0,tC.formatNumberWithCommas)(d,0,!0)," req)"]}),(0,t.jsx)(e_.Text,{className:`text-base font-semibold ${"day"===a?"text-green-600":"text-purple-600"}`,children:tE(r)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(e_.Text,{className:"text-xs text-gray-500 block",children:[l," Input"]}),(0,t.jsx)(e_.Text,{className:"text-sm",children:tE(i)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(e_.Text,{className:"text-xs text-gray-500 block",children:[l," Output"]}),(0,t.jsx)(e_.Text,{className:"text-sm",children:tE(n)})]}),(0,t.jsxs)("div",{children:[(0,t.jsxs)(e_.Text,{className:"text-xs text-gray-500 block",children:[l," Margin Fee"]}),(0,t.jsx)(e_.Text,{className:`text-sm ${(o??0)>0?"text-amber-600":""}`,children:tE(o)})]})]}),(e.input_cost_per_token||e.output_cost_per_token)&&(0,t.jsxs)("div",{className:"text-xs text-gray-400 pt-2 border-t border-gray-200",children:["Token Pricing: "," ",e.input_cost_per_token&&(0,t.jsxs)("span",{children:["Input $",(0,tC.formatNumberWithCommas)(1e6*e.input_cost_per_token,2),"/1M"]}),e.input_cost_per_token&&e.output_cost_per_token&&" | ",e.output_cost_per_token&&(0,t.jsxs)("span",{children:["Output $",(0,tC.formatNumberWithCommas)(1e6*e.output_cost_per_token,2),"/1M"]})]})]})},tz=({multiResult:e,timePeriod:s})=>{let[a,l]=(0,i.useState)(new Set),r=e.entries.filter(e=>null!==e.result),n=e.entries.filter(e=>e.loading),o=e.entries.filter(e=>null!==e.error),d=r.length>0,c=n.length>0,u=o.length>0;if(!d&&!c&&!u)return(0,t.jsx)("div",{className:"py-6 text-center border border-dashed border-gray-300 rounded-lg bg-gray-50",children:(0,t.jsx)(e_.Text,{className:"text-gray-500",children:"Select models above to see cost estimates"})});if(!d&&c&&!u)return(0,t.jsxs)("div",{className:"py-6 text-center",children:[(0,t.jsx)(eS.Spin,{indicator:(0,t.jsx)(tN.LoadingOutlined,{spin:!0})}),(0,t.jsx)(e_.Text,{className:"text-gray-500 block mt-2",children:"Calculating costs..."})]});if(!d&&u)return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(_.Divider,{className:"my-4"}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(e_.Text,{className:"text-base font-semibold text-gray-900",children:"Cost Estimates"}),c&&(0,t.jsx)(eS.Spin,{indicator:(0,t.jsx)(tN.LoadingOutlined,{spin:!0}),size:"small"})]}),o.map(e=>(0,t.jsxs)("div",{className:"text-sm text-red-600 bg-red-50 p-3 rounded-lg border border-red-200",children:[(0,t.jsxs)("span",{className:"font-medium",children:[e.entry.model||"Unknown model",": "]}),e.error]},e.entry.id))]});let x=e.totals.margin_per_request>0,p="day"===s?"Daily":"Monthly",h=[{title:"Model",dataIndex:"model",key:"model",render:(e,s)=>(0,t.jsxs)("div",{className:"flex flex-col gap-1",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"font-medium text-sm",children:e}),s.provider&&(0,t.jsx)(b.Tag,{color:"blue",className:"text-xs",children:s.provider}),s.loading&&(0,t.jsx)(eS.Spin,{indicator:(0,t.jsx)(tN.LoadingOutlined,{spin:!0}),size:"small"})]}),s.error&&(0,t.jsxs)("div",{className:"text-xs text-red-600 bg-red-50 px-2 py-1 rounded",children:["⚠️ ",s.error]}),s.hasZeroCost&&!s.error&&(0,t.jsx)("div",{className:"text-xs text-amber-600 bg-amber-50 px-2 py-1 rounded",children:"⚠️ No pricing data found for this model. Set base_model in config."})]})},{title:"Per Request",dataIndex:"cost_per_request",key:"cost_per_request",align:"right",render:(e,s)=>s.error?(0,t.jsx)("span",{className:"text-gray-400",children:"-"}):(0,t.jsx)("span",{className:"font-mono text-sm",children:tE(e)})},{title:"Margin Fee",dataIndex:"margin_cost_per_request",key:"margin_cost_per_request",align:"right",render:(e,s)=>s.error?(0,t.jsx)("span",{className:"text-gray-400",children:"-"}):(0,t.jsx)("span",{className:`font-mono text-sm ${(e??0)>0?"text-amber-600":"text-gray-400"}`,children:tE(e)})},{title:p,dataIndex:"day"===s?"daily_cost":"monthly_cost",key:"period_cost",align:"right",render:(e,s)=>s.error?(0,t.jsx)("span",{className:"text-gray-400",children:"-"}):(0,t.jsx)("span",{className:"font-mono text-sm",children:tE(e)})},{title:"",key:"expand",width:40,render:(e,s)=>s.error?null:(0,t.jsx)(m.Button,{size:"xs",variant:"light",onClick:()=>{var e;return e=s.id,void l(t=>{let s=new Set(t);return s.has(e)?s.delete(e):s.add(e),s})},className:"text-gray-400 hover:text-gray-600",children:a.has(s.id)?(0,t.jsx)(tw.DownOutlined,{}):(0,t.jsx)(tk.RightOutlined,{})})}],g=e.entries.filter(e=>e.entry.model).map(e=>({key:e.entry.id,id:e.entry.id,model:e.result?.model||e.entry.model,provider:e.result?.provider,cost_per_request:e.result?.cost_per_request??null,margin_cost_per_request:e.result?.margin_cost_per_request??null,daily_cost:e.result?.daily_cost??null,monthly_cost:e.result?.monthly_cost??null,error:e.error,loading:e.loading,hasZeroCost:e.result&&0===e.result.cost_per_request}));return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)(_.Divider,{className:"my-4"}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(e_.Text,{className:"text-base font-semibold text-gray-900",children:"Cost Estimates"}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[c&&(0,t.jsx)(eS.Spin,{indicator:(0,t.jsx)(tN.LoadingOutlined,{spin:!0}),size:"small"}),(0,t.jsx)(tD,{multiResult:e})]})]}),(0,t.jsxs)(ec.Card,{size:"small",className:"bg-gradient-to-r from-slate-50 to-blue-50 border-slate-200",children:[(0,t.jsxs)(t_.Row,{gutter:[16,8],children:[(0,t.jsx)(tv.Col,{xs:24,sm:12,children:(0,t.jsx)(tg,{title:(0,t.jsx)("span",{className:"text-xs",children:"Total Per Request"}),value:tE(e.totals.cost_per_request),valueStyle:{color:"#1890ff",fontSize:"18px",fontFamily:"monospace"}})}),(0,t.jsx)(tv.Col,{xs:24,sm:12,children:(0,t.jsx)(tg,{title:(0,t.jsxs)("span",{className:"text-xs",children:["Total ",p]}),value:tE("day"===s?e.totals.daily_cost:e.totals.monthly_cost),valueStyle:{color:"day"===s?"#52c41a":"#722ed1",fontSize:"18px",fontFamily:"monospace"}})})]}),x&&(0,t.jsxs)(t_.Row,{gutter:[16,8],className:"mt-3 pt-3 border-t border-slate-200",children:[(0,t.jsxs)(tv.Col,{xs:24,sm:12,children:[(0,t.jsx)("div",{className:"text-xs text-gray-500",children:"Margin Fee/Request"}),(0,t.jsx)("div",{className:"text-sm font-mono text-amber-600",children:tE(e.totals.margin_per_request)})]}),(0,t.jsxs)(tv.Col,{xs:24,sm:12,children:[(0,t.jsxs)("div",{className:"text-xs text-gray-500",children:[p," Margin Fee"]}),(0,t.jsx)("div",{className:"text-sm font-mono text-amber-600",children:tE("day"===s?e.totals.daily_margin:e.totals.monthly_margin)})]})]})]}),g.length>0&&(0,t.jsx)(tt.Table,{columns:h,dataSource:g,pagination:!1,size:"small",className:"border border-gray-200 rounded-lg",expandable:{expandedRowKeys:Array.from(a),expandedRowRender:e=>{let a=r.find(t=>t.entry.id===e.id);return a?.result?(0,t.jsx)("div",{className:"py-2",children:(0,t.jsx)(tO,{result:a.result,loading:a.loading,timePeriod:s})}):null},showExpandColumn:!1}})]})},tR=()=>({id:`entry-${Date.now()}-${Math.random().toString(36).substr(2,9)}`,model:"",input_tokens:1e3,output_tokens:500,num_requests_per_day:void 0,num_requests_per_month:void 0}),tB=({accessToken:e,models:s})=>{let[a,r]=(0,i.useState)([tR()]),[n,o]=(0,i.useState)("month"),{debouncedFetchForEntry:d,removeEntry:c,getMultiModelResult:m}=function(e){let[t,s]=(0,i.useState)(new Map),a=(0,i.useRef)(new Map),r=(0,i.useCallback)(async t=>{if(!e||!t.model)return void s(e=>{let s=new Map(e);return s.set(t.id,{entry:t,result:null,loading:!1,error:null}),s});s(e=>{let s=new Map(e),a=s.get(t.id);return s.set(t.id,{entry:t,result:a?.result??null,loading:!0,error:null}),s});try{let a=(0,l.getProxyBaseUrl)(),r=a?`${a}/cost/estimate`:"/cost/estimate",i={model:t.model,input_tokens:t.input_tokens||0,output_tokens:t.output_tokens||0,num_requests_per_day:t.num_requests_per_day||null,num_requests_per_month:t.num_requests_per_month||null},n=await fetch(r,{method:"POST",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(i)});if(n.ok){let e=await n.json();s(s=>{let a=new Map(s);return a.set(t.id,{entry:t,result:e,loading:!1,error:null}),a})}else{let e=await n.json(),a=e.detail?.error||e.detail||"Failed to estimate cost";s(e=>{let s=new Map(e);return s.set(t.id,{entry:t,result:null,loading:!1,error:a}),s})}}catch(e){console.error("Error estimating cost:",e),s(e=>{let s=new Map(e);return s.set(t.id,{entry:t,result:null,loading:!1,error:"Network error"}),s})}},[e]),n=(0,i.useCallback)(e=>{let t=a.current.get(e.id);t&&clearTimeout(t);let s=setTimeout(()=>{r(e)},500);a.current.set(e.id,s)},[r]),o=(0,i.useCallback)(e=>{let t=a.current.get(e);t&&(clearTimeout(t),a.current.delete(e)),s(t=>{let s=new Map(t);return s.delete(e),s})},[]);return(0,i.useEffect)(()=>{let e=a.current;return()=>{e.forEach(e=>clearTimeout(e)),e.clear()}},[]),{debouncedFetchForEntry:n,removeEntry:o,getMultiModelResult:(0,i.useCallback)(e=>{let s=e.map(e=>{let s=t.get(e.id);return{entry:e,result:s?.result??null,loading:s?.loading??!1,error:s?.error??null}}),a=0,l=null,r=null,i=0,n=null,o=null;for(let e of s)e.result&&(a+=e.result.cost_per_request,i+=e.result.margin_cost_per_request,null!==e.result.daily_cost&&(l=(l??0)+e.result.daily_cost),null!==e.result.daily_margin_cost&&(n=(n??0)+e.result.daily_margin_cost),null!==e.result.monthly_cost&&(r=(r??0)+e.result.monthly_cost),null!==e.result.monthly_margin_cost&&(o=(o??0)+e.result.monthly_margin_cost));return{entries:s,totals:{cost_per_request:a,daily_cost:l,monthly_cost:r,margin_per_request:i,daily_margin:n,monthly_margin:o}}},[t])}}(e),u=(0,i.useCallback)((e,t,s)=>{r(a=>{let l=a.map(a=>a.id===e?{...a,[t]:s}:a),r=l.find(t=>t.id===e);return r&&r.model&&d(r),l})},[d]),x=(0,i.useCallback)(e=>{o(e),r(t=>t.map(t=>({...t,num_requests_per_day:"day"===e?t.num_requests_per_day:void 0,num_requests_per_month:"month"===e?t.num_requests_per_month:void 0})))},[]),p=(0,i.useCallback)(()=>{r(e=>[...e,tR()])},[]),h=(0,i.useCallback)(e=>{r(t=>t.filter(t=>t.id!==e)),c(e)},[c]),j=m(a),y=[{title:"Model",dataIndex:"model",key:"model",width:"35%",render:(e,a)=>(0,t.jsx)(g.Select,{showSearch:!0,placeholder:"Select a model",value:a.model||void 0,onChange:e=>u(a.id,"model",e),optionFilterProp:"label",filterOption:(e,t)=>String(t?.label??"").toLowerCase().includes(e.toLowerCase()),options:s.map(e=>({value:e,label:e})),style:{width:"100%"},size:"small"})},{title:"Input Tokens",dataIndex:"input_tokens",key:"input_tokens",width:"18%",render:(e,s)=>(0,t.jsx)(ts.InputNumber,{min:0,value:s.input_tokens,onChange:e=>u(s.id,"input_tokens",e??0),style:{width:"100%"},size:"small",formatter:e=>`${e}`.replace(/\B(?=(\d{3})+(?!\d))/g,",")})},{title:"Output Tokens",dataIndex:"output_tokens",key:"output_tokens",width:"18%",render:(e,s)=>(0,t.jsx)(ts.InputNumber,{min:0,value:s.output_tokens,onChange:e=>u(s.id,"output_tokens",e??0),style:{width:"100%"},size:"small",formatter:e=>`${e}`.replace(/\B(?=(\d{3})+(?!\d))/g,",")})},{title:`Requests/${"day"===n?"Day":"Month"}`,dataIndex:"day"===n?"num_requests_per_day":"num_requests_per_month",key:"num_requests",width:"20%",render:(e,s)=>(0,t.jsx)(ts.InputNumber,{min:0,value:"day"===n?s.num_requests_per_day:s.num_requests_per_month,onChange:e=>u(s.id,"day"===n?"num_requests_per_day":"num_requests_per_month",e??void 0),style:{width:"100%"},size:"small",placeholder:"-",formatter:e=>e?`${e}`.replace(/\B(?=(\d{3})+(?!\d))/g,","):""})},{title:"",key:"actions",width:50,render:(e,s)=>(0,t.jsx)(A.Button,{type:"text",icon:(0,t.jsx)(eh.DeleteOutlined,{}),onClick:()=>h(s.id),disabled:1===a.length,danger:!0,size:"small"})}];return(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsx)("div",{className:"flex items-center justify-end mb-2",children:(0,t.jsxs)(f.Radio.Group,{value:n,onChange:e=>x(e.target.value),size:"small",optionType:"button",buttonStyle:"solid",children:[(0,t.jsx)(f.Radio.Button,{value:"day",children:"Per Day"}),(0,t.jsx)(f.Radio.Button,{value:"month",children:"Per Month"})]})}),(0,t.jsx)(tt.Table,{columns:y,dataSource:a,rowKey:"id",pagination:!1,size:"small",footer:()=>(0,t.jsx)(A.Button,{type:"dashed",onClick:p,icon:(0,t.jsx)(P.PlusOutlined,{}),className:"w-full",children:"Add Another Model"})}),(0,t.jsx)(tz,{multiResult:j,timePeriod:n})]})};var tq=e.i(270377),t$=e.i(778917),tU=e.i(664659);let tV=({items:e,children:s="Docs",className:a=""})=>{let[l,r]=(0,i.useState)(!1),n=(0,i.useRef)(null);return(0,i.useEffect)(()=>{let e=e=>{n.current&&!n.current.contains(e.target)&&r(!1)};return l&&document.addEventListener("mousedown",e),()=>{document.removeEventListener("mousedown",e)}},[l]),(0,t.jsxs)("div",{className:`relative inline-block ${a}`,ref:n,children:[(0,t.jsxs)("button",{type:"button",onClick:()=>r(!l),className:"inline-flex items-center gap-1 text-gray-500 hover:text-gray-700 text-xs transition-colors focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-1 rounded px-2 py-1","aria-expanded":l,"aria-haspopup":"true",children:[(0,t.jsx)("span",{children:s}),(0,t.jsx)(tU.ChevronDown,{className:`h-3 w-3 transition-transform ${l?"rotate-180":""}`,"aria-hidden":"true"})]}),l&&(0,t.jsx)("div",{className:"absolute right-0 mt-1 w-56 bg-white rounded-lg shadow-lg border border-gray-200 py-1 z-50",children:e.map((e,s)=>(0,t.jsxs)("a",{href:e.href,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between px-4 py-2 text-sm text-gray-700 hover:bg-gray-50 transition-colors",onClick:()=>r(!1),children:[(0,t.jsx)("span",{children:e.label}),(0,t.jsx)(t$.ExternalLink,{className:"h-3.5 w-3.5 text-gray-400 flex-shrink-0 ml-2","aria-hidden":"true"})]},s))})]})};var tG=e.i(673709);let tH=()=>{let[e,s]=(0,i.useState)(""),[a,l]=(0,i.useState)(""),r=(0,i.useMemo)(()=>{let t=parseFloat(e),s=parseFloat(a);if(isNaN(t)||isNaN(s)||0===t||0===s)return null;let l=t+s,r=s/l*100;return{originalCost:l.toFixed(10),finalCost:t.toFixed(10),discountAmount:s.toFixed(10),discountPercentage:r.toFixed(2)}},[e,a]);return(0,t.jsxs)("div",{className:"space-y-4 pt-2",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(e_.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Cost Calculation"}),(0,t.jsxs)(e_.Text,{className:"text-xs text-gray-600",children:["Discounts are applied to provider costs: ",(0,t.jsx)("code",{className:"bg-gray-100 px-1.5 py-0.5 rounded text-xs",children:"final_cost = base_cost × (1 - discount%/100)"})]})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(e_.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Example"}),(0,t.jsx)(e_.Text,{className:"text-xs text-gray-600",children:"A 5% discount on a $10.00 request results in: $10.00 × (1 - 0.05) = $9.50"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)(e_.Text,{className:"font-medium text-gray-900 text-sm mb-1",children:"Valid Range"}),(0,t.jsx)(e_.Text,{className:"text-xs text-gray-600",children:"Discount percentages must be between 0% and 100%"})]}),(0,t.jsxs)("div",{className:"pt-4 border-t border-gray-200",children:[(0,t.jsx)(e_.Text,{className:"font-medium text-gray-900 text-sm mb-2",children:"Validating Discounts"}),(0,t.jsx)(e_.Text,{className:"text-xs text-gray-600 mb-3",children:"Make a test request and check the response headers to verify discounts are applied:"}),(0,t.jsx)(tG.default,{language:"bash",code:`curl -X POST -i http://your-proxy:4000/chat/completions \\
- -H "Content-Type: application/json" \\
- -H "Authorization: Bearer sk-1234" \\
- -d '{
- "model": "gemini/gemini-2.5-pro",
- "messages": [{"role": "user", "content": "Hello"}]
- }'`}),(0,t.jsx)(e_.Text,{className:"text-xs text-gray-600 mt-3 mb-2",children:"Look for these headers in the response:"}),(0,t.jsxs)("div",{className:"space-y-1.5",children:[(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded text-xs font-mono text-gray-800 whitespace-nowrap",children:"x-litellm-response-cost"}),(0,t.jsx)(e_.Text,{className:"text-xs text-gray-600",children:"Final cost after discount"})]}),(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded text-xs font-mono text-gray-800 whitespace-nowrap",children:"x-litellm-response-cost-original"}),(0,t.jsx)(e_.Text,{className:"text-xs text-gray-600",children:"Original cost before discount"})]}),(0,t.jsxs)("div",{className:"flex items-start gap-3",children:[(0,t.jsx)("code",{className:"bg-gray-100 px-2 py-1 rounded text-xs font-mono text-gray-800 whitespace-nowrap",children:"x-litellm-response-cost-discount-amount"}),(0,t.jsx)(e_.Text,{className:"text-xs text-gray-600",children:"Amount discounted"})]})]})]}),(0,t.jsxs)("div",{className:"pt-4 border-t border-gray-200",children:[(0,t.jsx)(e_.Text,{className:"font-medium text-gray-900 text-sm mb-3",children:"Discount Calculator"}),(0,t.jsx)(e_.Text,{className:"text-xs text-gray-600 mb-3",children:"Enter values from your response headers to verify the discount:"}),(0,t.jsxs)("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mb-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs font-medium text-gray-700 mb-1",children:"Response Cost (x-litellm-response-cost)"}),(0,t.jsx)(eV.TextInput,{placeholder:"0.0171938125",value:e,onValueChange:s,className:"text-sm"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-xs font-medium text-gray-700 mb-1",children:"Discount Amount (x-litellm-response-cost-discount-amount)"}),(0,t.jsx)(eV.TextInput,{placeholder:"0.0009049375",value:a,onValueChange:l,className:"text-sm"})]})]}),r&&(0,t.jsxs)("div",{className:"bg-blue-50 border border-blue-200 rounded-lg p-4",children:[(0,t.jsx)(e_.Text,{className:"text-sm font-medium text-blue-900 mb-2",children:"Calculated Results"}),(0,t.jsxs)("div",{className:"space-y-2",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(e_.Text,{className:"text-xs text-blue-800",children:"Original Cost:"}),(0,t.jsxs)("code",{className:"text-xs font-mono text-blue-900",children:["$",r.originalCost]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(e_.Text,{className:"text-xs text-blue-800",children:"Final Cost:"}),(0,t.jsxs)("code",{className:"text-xs font-mono text-blue-900",children:["$",r.finalCost]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between",children:[(0,t.jsx)(e_.Text,{className:"text-xs text-blue-800",children:"Discount Amount:"}),(0,t.jsxs)("code",{className:"text-xs font-mono text-blue-900",children:["$",r.discountAmount]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-between pt-2 border-t border-blue-300",children:[(0,t.jsx)(e_.Text,{className:"text-xs font-semibold text-blue-900",children:"Discount Applied:"}),(0,t.jsxs)(e_.Text,{className:"text-sm font-bold text-blue-900",children:[r.discountPercentage,"%"]})]})]})]})]})]})};var tK=e.i(689020);let tW=[{label:"Custom pricing for models",href:"https://docs.litellm.ai/docs/proxy/custom_pricing"},{label:"Spend tracking",href:"https://docs.litellm.ai/docs/proxy/cost_tracking"}],tQ=({userID:e,userRole:s,accessToken:a})=>{let[r,n]=(0,i.useState)(void 0),[o,d]=(0,i.useState)(""),[c,x]=(0,i.useState)(!0),[h,g]=(0,i.useState)(!1),[j,y]=(0,i.useState)(!1),[f,b]=(0,i.useState)(void 0),[_,v]=(0,i.useState)("percentage"),[N,w]=(0,i.useState)(""),[k,C]=(0,i.useState)(""),[S,T]=(0,i.useState)([]),[I]=p.Form.useForm(),[F]=p.Form.useForm(),[A,P]=u.Modal.useModal(),L="proxy_admin"===s||"Admin"===s,{discountConfig:M,fetchDiscountConfig:D,handleAddProvider:E,handleRemoveProvider:O,handleDiscountChange:z}=function({accessToken:e}){let[t,s]=(0,i.useState)({}),a=(0,i.useCallback)(async()=>{try{let t=(0,l.getProxyBaseUrl)(),a=t?`${t}/config/cost_discount_config`:"/config/cost_discount_config",r=await fetch(a,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(r.ok){let e=await r.json();s(e.values||{})}else console.error("Failed to fetch discount config")}catch(e){console.error("Error fetching discount config:",e),eM.default.fromBackend("Failed to fetch discount configuration")}},[e]),r=(0,i.useCallback)(async t=>{try{let s=(0,l.getProxyBaseUrl)(),r=s?`${s}/config/cost_discount_config`:"/config/cost_discount_config",i=await fetch(r,{method:"PATCH",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(i.ok)eM.default.success("Discount configuration updated successfully"),await a();else{let e=await i.json(),t=e.detail?.error||e.detail||"Failed to update settings";eM.default.fromBackend(t)}}catch(e){console.error("Error updating discount config:",e),eM.default.fromBackend("Failed to update discount configuration")}},[e,a]),n=(0,i.useCallback)(async(e,a)=>{if(!e||!a)return eM.default.fromBackend("Please select a provider and enter discount percentage"),!1;let l=parseFloat(a);if(isNaN(l)||l<0||l>100)return eM.default.fromBackend("Discount must be between 0% and 100%"),!1;let i=e6(e);if(!i)return eM.default.fromBackend("Invalid provider selected"),!1;if(t[i])return eM.default.fromBackend(`Discount for ${e4.Providers[e]} already exists. Edit it in the table above.`),!1;let n={...t,[i]:l/100};return s(n),await r(n),!0},[t,r]),o=(0,i.useCallback)(async e=>{let a={...t};delete a[e],s(a),await r(a)},[t,r]),d=(0,i.useCallback)(async(e,a)=>{let l=parseFloat(a);if(!isNaN(l)&&l>=0&&l<=1){let a={...t,[e]:l};s(a),await r(a)}},[t,r]);return{discountConfig:t,setDiscountConfig:s,fetchDiscountConfig:a,saveDiscountConfig:r,handleAddProvider:n,handleRemoveProvider:o,handleDiscountChange:d}}({accessToken:a}),{marginConfig:R,fetchMarginConfig:B,handleAddMargin:q,handleRemoveMargin:$,handleMarginChange:U}=function({accessToken:e}){let[t,s]=(0,i.useState)({}),a=(0,i.useCallback)(async()=>{try{let t=(0,l.getProxyBaseUrl)(),a=t?`${t}/config/cost_margin_config`:"/config/cost_margin_config",r=await fetch(a,{method:"GET",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"}});if(r.ok){let e=await r.json();s(e.values||{})}else console.error("Failed to fetch margin config")}catch(e){console.error("Error fetching margin config:",e),eM.default.fromBackend("Failed to fetch margin configuration")}},[e]),r=(0,i.useCallback)(async t=>{try{let s=(0,l.getProxyBaseUrl)(),r=s?`${s}/config/cost_margin_config`:"/config/cost_margin_config",i=await fetch(r,{method:"PATCH",headers:{[(0,l.getGlobalLitellmHeaderName)()]:`Bearer ${e}`,"Content-Type":"application/json"},body:JSON.stringify(t)});if(i.ok)eM.default.success("Margin configuration updated successfully"),await a();else{let e=await i.json(),t=e.detail?.error||e.detail||"Failed to update settings";eM.default.fromBackend(t)}}catch(e){console.error("Error updating margin config:",e),eM.default.fromBackend("Failed to update margin configuration")}},[e,a]),n=(0,i.useCallback)(async e=>{let a,l,{selectedProvider:i,marginType:n,percentageValue:o,fixedAmountValue:d}=e;if(!i)return eM.default.fromBackend("Please select a provider"),!1;if("global"===i)a="global";else{let e=e6(i);if(!e)return eM.default.fromBackend("Invalid provider selected"),!1;a=e}if(t[a]){let e="global"===a?"Global":e4.Providers[i];return eM.default.fromBackend(`Margin for ${e} already exists. Edit it in the table above.`),!1}if("percentage"===n){let e=parseFloat(o);if(isNaN(e)||e<0||e>1e3)return eM.default.fromBackend("Percentage must be between 0% and 1000%"),!1;l=e/100}else{let e=parseFloat(d);if(isNaN(e)||e<0)return eM.default.fromBackend("Fixed amount must be non-negative"),!1;l={fixed_amount:e}}let c={...t,[a]:l};return s(c),await r(c),!0},[t,r]),o=(0,i.useCallback)(async e=>{let a={...t};delete a[e],s(a),await r(a)},[t,r]),d=(0,i.useCallback)(async(e,a)=>{let l={...t,[e]:a};s(l),await r(l)},[t,r]);return{marginConfig:t,setMarginConfig:s,fetchMarginConfig:a,saveMarginConfig:r,handleAddMargin:n,handleRemoveMargin:o,handleMarginChange:d}}({accessToken:a});(0,i.useEffect)(()=>{a&&(Promise.all([D(),B()]).finally(()=>{x(!1)}),(async()=>{try{let e=await (0,tK.fetchAvailableModels)(a);T(e.map(e=>e.model_group))}catch(e){console.error("Error fetching models:",e)}})())},[a,D,B]);let V=async()=>{await E(r,o)&&(n(void 0),d(""),g(!1))},G=async(e,s)=>{A.confirm({title:"Remove Provider Discount",icon:(0,t.jsx)(tq.ExclamationCircleOutlined,{}),content:`Are you sure you want to remove the discount for ${s}?`,okText:"Remove",okType:"danger",cancelText:"Cancel",onOk:()=>O(e)})},H=async()=>{await q({selectedProvider:f,marginType:_,percentageValue:N,fixedAmountValue:k})&&(b(void 0),w(""),C(""),v("percentage"),y(!1))},K=async(e,s)=>{A.confirm({title:"Remove Provider Margin",icon:(0,t.jsx)(tq.ExclamationCircleOutlined,{}),content:`Are you sure you want to remove the margin for ${s}?`,okText:"Remove",okType:"danger",cancelText:"Cancel",onOk:()=>$(e)})};return a?(0,t.jsxs)("div",{className:"w-full p-8",children:[P,(0,t.jsx)("div",{className:"flex flex-col md:flex-row items-start md:items-center justify-between mb-6",children:(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)(eb.Title,{children:"Cost Tracking Settings"}),(0,t.jsx)(tV,{items:tW})]}),(0,t.jsx)(e_.Text,{className:"text-gray-500 mt-1",children:"Configure cost discounts and margins for different LLM providers. Changes are saved automatically."})]})}),(0,t.jsxs)("div",{className:"bg-white rounded-lg shadow w-full max-w-full space-y-4",children:[L&&(0,t.jsxs)(eq.Accordion,{children:[(0,t.jsx)(e$.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(e_.Text,{className:"text-lg font-semibold text-gray-900",children:"Provider Discounts"}),(0,t.jsx)(e_.Text,{className:"text-sm text-gray-500 mt-1",children:"Apply percentage-based discounts to reduce costs for specific providers"})]})}),(0,t.jsx)(eU.AccordionBody,{className:"px-0",children:(0,t.jsxs)(eN.TabGroup,{children:[(0,t.jsxs)(ew.TabList,{className:"px-6 pt-4",children:[(0,t.jsx)(ev.Tab,{children:"Discounts"}),(0,t.jsx)(ev.Tab,{children:"Test It"})]}),(0,t.jsxs)(eC.TabPanels,{children:[(0,t.jsx)(ek.TabPanel,{children:(0,t.jsxs)("div",{className:"p-6",children:[(0,t.jsx)("div",{className:"flex justify-end mb-4",children:(0,t.jsx)(m.Button,{onClick:()=>g(!0),children:"+ Add Provider Discount"})}),c?(0,t.jsx)("div",{className:"py-12 text-center",children:(0,t.jsx)(e_.Text,{className:"text-gray-500",children:"Loading configuration..."})}):Object.keys(M).length>0?(0,t.jsx)(e8,{discountConfig:M,onDiscountChange:z,onRemoveProvider:G}):(0,t.jsxs)("div",{className:"py-16 px-6 text-center",children:[(0,t.jsx)("svg",{className:"mx-auto h-12 w-12 text-gray-400 mb-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),(0,t.jsx)(e_.Text,{className:"text-gray-700 font-medium mb-2",children:"No provider discounts configured"}),(0,t.jsx)(e_.Text,{className:"text-gray-500 text-sm",children:'Click "Add Provider Discount" to get started'})]})]})}),(0,t.jsx)(ek.TabPanel,{children:(0,t.jsx)("div",{className:"px-6 pb-4",children:(0,t.jsx)(tH,{})})})]})]})})]}),L&&(0,t.jsxs)(eq.Accordion,{children:[(0,t.jsx)(e$.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(e_.Text,{className:"text-lg font-semibold text-gray-900",children:"Fee/Price Margin"}),(0,t.jsx)(e_.Text,{className:"text-sm text-gray-500 mt-1",children:"Add fees or margins to LLM costs for internal billing and cost recovery"})]})}),(0,t.jsx)(eU.AccordionBody,{className:"px-0",children:(0,t.jsxs)("div",{className:"p-6",children:[(0,t.jsx)("div",{className:"flex justify-end mb-4",children:(0,t.jsx)(m.Button,{onClick:()=>y(!0),children:"+ Add Provider Margin"})}),c?(0,t.jsx)("div",{className:"py-12 text-center",children:(0,t.jsx)(e_.Text,{className:"text-gray-500",children:"Loading configuration..."})}):Object.keys(R).length>0?(0,t.jsx)(e9,{marginConfig:R,onMarginChange:U,onRemoveProvider:K}):(0,t.jsxs)("div",{className:"py-16 px-6 text-center",children:[(0,t.jsx)("svg",{className:"mx-auto h-12 w-12 text-gray-400 mb-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:(0,t.jsx)("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),(0,t.jsx)(e_.Text,{className:"text-gray-700 font-medium mb-2",children:"No provider margins configured"}),(0,t.jsx)(e_.Text,{className:"text-gray-500 text-sm",children:'Click "Add Provider Margin" to get started'})]})]})})]}),(0,t.jsxs)(eq.Accordion,{defaultOpen:!0,children:[(0,t.jsx)(e$.AccordionHeader,{className:"px-6 py-4",children:(0,t.jsxs)("div",{className:"flex flex-col items-start w-full",children:[(0,t.jsx)(e_.Text,{className:"text-lg font-semibold text-gray-900",children:"Pricing Calculator"}),(0,t.jsx)(e_.Text,{className:"text-sm text-gray-500 mt-1",children:"Estimate LLM costs based on expected token usage and request volume"})]})}),(0,t.jsx)(eU.AccordionBody,{className:"px-0",children:(0,t.jsx)("div",{className:"p-6",children:(0,t.jsx)(tB,{accessToken:a,models:S})})})]})]}),(0,t.jsx)(u.Modal,{title:(0,t.jsx)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:(0,t.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add Provider Discount"})}),open:h,width:1e3,onCancel:()=>{g(!1),I.resetFields(),n(void 0),d("")},footer:null,className:"top-8",styles:{body:{padding:"24px"},header:{padding:"24px 24px 0 24px",border:"none"}},children:(0,t.jsxs)("div",{className:"mt-6",children:[(0,t.jsx)(e_.Text,{className:"text-sm text-gray-600 mb-6",children:"Select a provider and set its discount percentage. Enter a value between 0% and 100% (e.g., 5 for a 5% discount)."}),(0,t.jsx)(p.Form,{form:I,onFinish:()=>{V()},layout:"vertical",className:"space-y-6",children:(0,t.jsx)(e7,{discountConfig:M,selectedProvider:r,newDiscount:o,onProviderChange:n,onDiscountChange:d,onAddProvider:V})})]})}),(0,t.jsx)(u.Modal,{title:(0,t.jsx)("div",{className:"flex items-center space-x-3 pb-4 border-b border-gray-100",children:(0,t.jsx)("h2",{className:"text-xl font-semibold text-gray-900",children:"Add Provider Margin"})}),open:j,width:1e3,onCancel:()=>{y(!1),F.resetFields(),b(void 0),w(""),C(""),v("percentage")},footer:null,className:"top-8",styles:{body:{padding:"24px"},header:{padding:"24px 24px 0 24px",border:"none"}},children:(0,t.jsxs)("div",{className:"mt-6",children:[(0,t.jsx)(e_.Text,{className:"text-sm text-gray-600 mb-6",children:'Select a provider (or "Global" for all providers) and configure the margin. You can use percentage-based or fixed amount.'}),(0,t.jsx)(p.Form,{form:F,layout:"vertical",className:"space-y-6",children:(0,t.jsx)(te,{marginConfig:R,selectedProvider:f,marginType:_,percentageValue:N,fixedAmountValue:k,onProviderChange:b,onMarginTypeChange:v,onPercentageChange:w,onFixedAmountChange:C,onAddProvider:H})})]})})]}):null};var tY=e.i(226898),tJ=e.i(973706),tX=e.i(447566),tZ=e.i(602073),t0=e.i(313603),t1=e.i(266027),t2=e.i(309426),t4=e.i(350967),t5=e.i(653496),t6=e.i(149192),t3=e.i(788191);let t8=`Evaluate whether this guardrail's decision was correct.
-Analyze the user input, the guardrail action taken, and determine if it was appropriate.
-
-Consider:
-— Was the user's intent genuinely harmful or policy-violating?
-— Was the guardrail's action (block / flag / pass) appropriate?
-— Could this be a false positive or false negative?
-
-Return a structured verdict with confidence and justification.`,t7=`{
- "verdict": "correct" | "false_positive" | "false_negative",
- "confidence": 0.0,
- "justification": "string",
- "risk_category": "string",
- "suggested_action": "keep" | "adjust threshold" | "add allowlist"
-}
-`;function t9({open:e,onClose:s,guardrailName:a,accessToken:l,onRunEvaluation:r}){let[n,o]=(0,i.useState)(t8),[d,c]=(0,i.useState)(t7),[m,x]=(0,i.useState)(null),[p,h]=(0,i.useState)([]),[y,f]=(0,i.useState)(!1);(0,i.useEffect)(()=>{if(!e||!l)return void h([]);let t=!1;return f(!0),(0,tK.fetchAvailableModels)(l).then(e=>{t||h(e)}).catch(()=>{t||h([])}).finally(()=>{t||f(!1)}),()=>{t=!0}},[e,l]);let b=p.map(e=>({value:e.model_group,label:e.model_group}));return(0,t.jsxs)(u.Modal,{title:"Evaluation Settings",open:e,onCancel:s,width:640,footer:null,closeIcon:(0,t.jsx)(t6.CloseOutlined,{}),destroyOnClose:!0,children:[(0,t.jsx)("p",{className:"text-sm text-gray-500 mb-4",children:a?`Configure AI evaluation for ${a}`:"Configure AI evaluation for re-running on logs"}),(0,t.jsxs)("div",{className:"space-y-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-1.5",children:[(0,t.jsx)("label",{className:"text-sm font-medium text-gray-700",children:"Evaluation Prompt"}),(0,t.jsx)("button",{type:"button",onClick:()=>o(t8),className:"text-xs text-indigo-600 hover:text-indigo-700",children:"Reset to default"})]}),(0,t.jsx)(j.Input.TextArea,{value:n,onChange:e=>o(e.target.value),rows:6,className:"font-mono text-sm"}),(0,t.jsx)("p",{className:"text-xs text-gray-400 mt-1",children:"System prompt sent to the evaluation model. Output is structured via response_format."})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1.5",children:"Response Schema"}),(0,t.jsx)("p",{className:"text-xs text-gray-400 mb-1",children:"response_format: json_schema"}),(0,t.jsx)(j.Input.TextArea,{value:d,onChange:e=>c(e.target.value),rows:6,className:"font-mono text-sm"})]}),(0,t.jsxs)("div",{children:[(0,t.jsx)("label",{className:"block text-sm font-medium text-gray-700 mb-1.5",children:"Model"}),(0,t.jsx)(g.Select,{placeholder:y?"Loading models…":"Select a model",value:m??void 0,onChange:x,options:b,style:{width:"100%"},showSearch:!0,optionFilterProp:"label",loading:y,notFoundContent:l?"No models available":"Sign in to see models"})]})]}),(0,t.jsxs)("div",{className:"flex items-center justify-end gap-2 mt-6 pt-4 border-t border-gray-100",children:[(0,t.jsx)(A.Button,{onClick:s,children:"Cancel"}),(0,t.jsx)(A.Button,{type:"primary",icon:(0,t.jsx)(t3.PlayCircleOutlined,{}),onClick:()=>{m&&(r?.({prompt:n,schema:d,model:m}),s())},disabled:!m,children:"Run Evaluation"})]})]})}var se=e.i(245704),st=e.i(166540);e.i(3565);var ss=e.i(502626);let sa={blocked:{icon:t6.CloseOutlined,color:"text-red-600",bg:"bg-red-50",border:"border-red-200",label:"Blocked"},passed:{icon:se.CheckCircleOutlined,color:"text-green-600",bg:"bg-green-50",border:"border-green-200",label:"Passed"},flagged:{icon:ep.WarningOutlined,color:"text-amber-600",bg:"bg-amber-50",border:"border-amber-200",label:"Flagged"}};function sl({guardrailName:e,filterAction:s="all",logs:a=[],logsLoading:r=!1,totalLogs:n,accessToken:o=null,startDate:d="",endDate:c=""}){let[m,u]=(0,i.useState)(10),[x,p]=(0,i.useState)(s),[h,g]=(0,i.useState)(null),[j,y]=(0,i.useState)(!1),f=a.filter(e=>"all"===x||e.action===x).slice(0,m),b=n??a.length,_=d?(0,st.default)(d).utc().format("YYYY-MM-DD HH:mm:ss"):(0,st.default)().subtract(24,"hours").utc().format("YYYY-MM-DD HH:mm:ss"),v=c?(0,st.default)(c).utc().endOf("day").format("YYYY-MM-DD HH:mm:ss"):(0,st.default)().utc().format("YYYY-MM-DD HH:mm:ss"),{data:N}=(0,t1.useQuery)({queryKey:["spend-log-by-request",h,_,v],queryFn:async()=>o&&h?await (0,l.uiSpendLogsCall)({accessToken:o,start_date:_,end_date:v,page:1,page_size:10,params:{request_id:h}}):null,enabled:!!(o&&h&&j)}),w=N?.data?.[0]??null;return(0,t.jsxs)("div",{className:"bg-white border border-gray-200 rounded-lg",children:[(0,t.jsx)("div",{className:"p-4 border-b border-gray-200",children:(0,t.jsxs)("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)("h3",{className:"text-base font-semibold text-gray-900",children:e?`Logs — ${e}`:"Request Logs"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:r?"Loading…":a.length>0?`Showing ${f.length} of ${b} entries`:"No logs for this period. Select a guardrail and date range."})]}),a.length>0&&(0,t.jsxs)("div",{className:"flex items-center gap-4",children:[(0,t.jsx)("div",{className:"flex items-center gap-1",children:["all","blocked","flagged","passed"].map(e=>(0,t.jsx)(A.Button,{type:x===e?"primary":"default",size:"small",onClick:()=>p(e),children:e.charAt(0).toUpperCase()+e.slice(1)},e))}),(0,t.jsx)("div",{className:"h-4 w-px bg-gray-200"}),(0,t.jsxs)("div",{className:"flex items-center gap-1",children:[(0,t.jsx)("span",{className:"text-xs text-gray-500 mr-1",children:"Sample:"}),[10,50,100].map(e=>(0,t.jsx)(A.Button,{type:m===e?"primary":"default",size:"small",onClick:()=>u(e),children:e},e))]})]})]})}),r&&(0,t.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,t.jsx)(eS.Spin,{})}),!r&&0===f.length&&(0,t.jsx)("div",{className:"py-12 text-center text-sm text-gray-500",children:"No logs to display. Adjust filters or date range."}),!r&&f.length>0&&(0,t.jsx)("div",{className:"divide-y divide-gray-100",children:f.map(e=>{let s=sa[e.action],a=s.icon;return(0,t.jsxs)("button",{type:"button",onClick:()=>{g(e.id),y(!0)},className:"w-full text-left px-4 py-3 hover:bg-gray-50 transition-colors flex items-start gap-3",children:[(0,t.jsx)(a,{className:`w-4 h-4 mt-0.5 flex-shrink-0 ${s.color}`}),(0,t.jsxs)("div",{className:"flex-1 min-w-0",children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-1 flex-wrap",children:[(0,t.jsx)("span",{className:`inline-flex items-center px-2 py-0.5 text-xs font-medium rounded border ${s.bg} ${s.color} ${s.border}`,children:s.label}),(0,t.jsx)("span",{className:"text-xs text-gray-400",children:e.timestamp}),(0,t.jsx)("span",{className:"text-xs text-gray-400",children:"·"}),e.model&&(0,t.jsx)("span",{className:"text-xs text-gray-500",children:e.model})]}),(0,t.jsx)("p",{className:"text-sm text-gray-800 truncate",children:e.input_snippet??e.input??"—"})]}),(0,t.jsx)(tw.DownOutlined,{className:"w-4 h-4 text-gray-400 flex-shrink-0 mt-1"})]},e.id)})}),(0,t.jsx)(ss.LogDetailsDrawer,{open:j,onClose:()=>{y(!1),g(null)},logEntry:w,accessToken:o,allLogs:w?[w]:[],startTime:_})]})}function sr({label:e,value:s,valueColor:a="text-gray-900",icon:l,subtitle:r}){return(0,t.jsxs)("div",{className:"h-full bg-white border border-gray-200 rounded-lg p-5 flex flex-col",children:[(0,t.jsxs)("div",{className:"flex items-center justify-between mb-1",children:[(0,t.jsx)("span",{className:"text-sm font-medium text-gray-600",children:e}),l&&(0,t.jsx)("span",{className:"text-gray-400",children:l})]}),(0,t.jsx)("div",{className:`text-3xl font-semibold ${a} tracking-tight`,children:s}),r&&(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-1",children:r})]})}let si={healthy:{bg:"bg-green-50",text:"text-green-700",dot:"bg-green-500"},warning:{bg:"bg-amber-50",text:"text-amber-700",dot:"bg-amber-500"},critical:{bg:"bg-red-50",text:"text-red-700",dot:"bg-red-500"}};function sn({guardrailId:e,onBack:s,accessToken:a=null,startDate:r,endDate:n}){let[o,d]=(0,i.useState)("overview"),[c,m]=(0,i.useState)(!1),[u,x]=(0,i.useState)(1),{data:p,isLoading:h,error:g}=(0,t1.useQuery)({queryKey:["guardrails-usage-detail",e,r,n],queryFn:()=>(0,l.getGuardrailsUsageDetail)(a,e,r,n),enabled:!!a&&!!e}),{data:j,isLoading:y}=(0,t1.useQuery)({queryKey:["guardrails-usage-logs",e,u,50],queryFn:()=>(0,l.getGuardrailsUsageLogs)(a,{guardrailId:e,page:u,pageSize:50,startDate:r,endDate:n}),enabled:!!a&&!!e}),f=(0,i.useMemo)(()=>(j?.logs??[]).map(e=>({id:e.id,timestamp:e.timestamp,action:e.action,score:e.score,model:e.model,input_snippet:e.input_snippet,output_snippet:e.output_snippet,reason:e.reason})),[j?.logs]),b=p?{name:p.guardrail_name,description:p.description??"",status:p.status,provider:p.provider,type:p.type,requestsEvaluated:p.requestsEvaluated,failRate:p.failRate,avgScore:p.avgScore,avgLatency:p.avgLatency}:{name:e,description:"",status:"healthy",provider:"—",type:"—",requestsEvaluated:0,failRate:0,avgScore:void 0,avgLatency:void 0},_=si[b.status]??si.healthy;return h&&!p?(0,t.jsx)("div",{className:"flex items-center justify-center py-12",children:(0,t.jsx)(eS.Spin,{size:"large"})}):g&&!p?(0,t.jsxs)("div",{children:[(0,t.jsx)(A.Button,{type:"link",icon:(0,t.jsx)(tX.ArrowLeftOutlined,{}),onClick:s,className:"pl-0 mb-4",children:"Back to Overview"}),(0,t.jsx)("p",{className:"text-red-600",children:"Failed to load guardrail details."})]}):(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"mb-6",children:[(0,t.jsx)(A.Button,{type:"link",icon:(0,t.jsx)(tX.ArrowLeftOutlined,{}),onClick:s,className:"pl-0 mb-4",children:"Back to Overview"}),(0,t.jsxs)("div",{className:"flex items-start justify-between",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-3 mb-1",children:[(0,t.jsx)(tZ.SafetyOutlined,{className:"text-xl text-gray-400"}),(0,t.jsx)("h1",{className:"text-xl font-semibold text-gray-900",children:b.name}),(0,t.jsxs)("span",{className:`inline-flex items-center gap-1.5 px-2.5 py-0.5 text-xs font-medium rounded-full ${_.bg} ${_.text}`,children:[(0,t.jsx)("span",{className:`w-1.5 h-1.5 rounded-full ${_.dot}`}),b.status.charAt(0).toUpperCase()+b.status.slice(1)]})]}),(0,t.jsx)("p",{className:"text-sm text-gray-500 ml-8",children:b.description})]}),(0,t.jsxs)("div",{className:"flex items-center gap-2",children:[(0,t.jsx)("span",{className:"inline-flex items-center px-2.5 py-1 text-xs font-medium rounded-md bg-indigo-50 text-indigo-700 border border-indigo-200",children:b.provider}),(0,t.jsx)(A.Button,{type:"default",icon:(0,t.jsx)(t0.SettingOutlined,{}),onClick:()=>m(!0),title:"Evaluation settings"})]})]})]}),(0,t.jsx)(t5.Tabs,{activeKey:o,onChange:d,items:[{key:"overview",label:"Overview"},{key:"logs",label:"Logs"}]}),"overview"===o&&(0,t.jsxs)("div",{className:"space-y-6 mt-4",children:[(0,t.jsxs)(t4.Grid,{numItems:2,numItemsMd:5,className:"gap-4",children:[(0,t.jsx)(t2.Col,{children:(0,t.jsx)(sr,{label:"Requests Evaluated",value:b.requestsEvaluated.toLocaleString()})}),(0,t.jsx)(t2.Col,{children:(0,t.jsx)(sr,{label:"Fail Rate",value:`${b.failRate}%`,valueColor:b.failRate>15?"text-red-600":b.failRate>5?"text-amber-600":"text-green-600",subtitle:`${Math.round(b.requestsEvaluated*b.failRate/100).toLocaleString()} blocked`,icon:b.failRate>15?(0,t.jsx)(ep.WarningOutlined,{className:"text-red-400"}):void 0})}),(0,t.jsx)(t2.Col,{children:(0,t.jsx)(sr,{label:"Avg. latency added",value:null!=b.avgLatency?`${Math.round(b.avgLatency)}ms`:"—",valueColor:null!=b.avgLatency?b.avgLatency>150?"text-red-600":b.avgLatency>50?"text-amber-600":"text-green-600":"text-gray-500",subtitle:null!=b.avgLatency?"Per request (avg)":"No data"})})]}),(0,t.jsx)(sl,{guardrailName:b.name,filterAction:"all",logs:f,logsLoading:y,totalLogs:j?.total??0,accessToken:a,startDate:r,endDate:n})]}),"logs"===o&&(0,t.jsx)("div",{className:"mt-4",children:(0,t.jsx)(sl,{guardrailName:b.name,logs:f,logsLoading:y,totalLogs:j?.total??0,accessToken:a,startDate:r,endDate:n})}),(0,t.jsx)(t9,{open:c,onClose:()=>m(!1),guardrailName:b.name,accessToken:a})]})}let so={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M917 211.1l-199.2 24c-6.6.8-9.4 8.9-4.7 13.6l59.3 59.3-226 226-101.8-101.7c-6.3-6.3-16.4-6.2-22.6 0L100.3 754.1a8.03 8.03 0 000 11.3l45 45.2c3.1 3.1 8.2 3.1 11.3 0L433.3 534 535 635.7c6.3 6.2 16.4 6.2 22.6 0L829 364.5l59.3 59.3a8.01 8.01 0 0013.6-4.7l24-199.2c.7-5.1-3.7-9.5-8.9-8.8z"}}]},name:"rise",theme:"outlined"};var sd=i.forwardRef(function(e,t){return i.createElement(tA.default,(0,tI.default)({},e,{ref:t,icon:so}))}),sc=e.i(584935);function sm({data:e}){let s=e&&e.length>0?e:[];return(0,t.jsxs)(ef.Card,{className:"bg-white border border-gray-200",children:[(0,t.jsx)(eb.Title,{className:"text-base font-semibold text-gray-900 mb-4",children:"Request Outcomes Over Time"}),(0,t.jsx)("div",{className:"h-80 min-h-[280px]",children:s.length>0?(0,t.jsx)(sc.BarChart,{data:s,index:"date",categories:["passed","blocked"],colors:["green","red"],valueFormatter:e=>e.toLocaleString(),yAxisWidth:48,showLegend:!0,stack:!0}):(0,t.jsx)("div",{className:"flex items-center justify-center h-full text-sm text-gray-500",children:"No chart data for this period"})})]})}let su={Bedrock:"bg-orange-100 text-orange-700 border-orange-200","Google Cloud":"bg-sky-100 text-sky-700 border-sky-200",LiteLLM:"bg-indigo-100 text-indigo-700 border-indigo-200",Custom:"bg-gray-100 text-gray-600 border-gray-200"};function sx({accessToken:e=null,startDate:s,endDate:a,onSelectGuardrail:r}){let[n,o]=(0,i.useState)("failRate"),[d,c]=(0,i.useState)("desc"),[m,u]=(0,i.useState)(!1),{data:x,isLoading:p,error:h}=(0,t1.useQuery)({queryKey:["guardrails-usage-overview",s,a],queryFn:()=>(0,l.getGuardrailsUsageOverview)(e,s,a),enabled:!!e}),g=x?.rows??[],j=(0,i.useMemo)(()=>{let e,t,s,a;return x?{totalRequests:x.totalRequests??0,totalBlocked:x.totalBlocked??0,passRate:String(x.passRate??0),avgLatency:g.length?Math.round(g.reduce((e,t)=>e+(t.avgLatency??0),0)/g.length):0,count:g.length}:(e=g.reduce((e,t)=>e+t.requestsEvaluated,0),t=g.reduce((e,t)=>e+Math.round(t.requestsEvaluated*t.failRate/100),0),s=e>0?((1-t/e)*100).toFixed(1):"0",{totalRequests:e,totalBlocked:t,passRate:s,avgLatency:(a=g.filter(e=>null!=e.avgLatency)).length>0?Math.round(a.reduce((e,t)=>e+(t.avgLatency??0),0)/a.length):0,count:g.length})},[x,g]),y=x?.chart,f=(0,i.useMemo)(()=>[...g].sort((e,t)=>{let s="desc"===d?-1:1,a=e[n]??0,l=t[n]??0;return(Number(a)-Number(l))*s}),[g,n,d]),b=[{title:"Guardrail",dataIndex:"name",key:"name",render:(e,s)=>(0,t.jsx)("button",{type:"button",className:"text-sm font-medium text-gray-900 hover:text-indigo-600 text-left",onClick:()=>r(s.id),children:e})},{title:"Provider",dataIndex:"provider",key:"provider",render:e=>(0,t.jsx)("span",{className:`inline-flex items-center px-2 py-0.5 text-xs font-medium rounded border ${su[e]??su.Custom}`,children:e})},{title:"Requests",dataIndex:"requestsEvaluated",key:"requestsEvaluated",align:"right",sorter:!0,sortOrder:"requestsEvaluated"===n?"desc"===d?"descend":"ascend":null,render:e=>e.toLocaleString()},{title:"Fail Rate",dataIndex:"failRate",key:"failRate",align:"right",sorter:!0,sortOrder:"failRate"===n?"desc"===d?"descend":"ascend":null,render:(e,s)=>(0,t.jsxs)("span",{className:e>15?"text-red-600":e>5?"text-amber-600":"text-green-600",children:[e,"%","up"===s.trend&&(0,t.jsx)("span",{className:"ml-1 text-xs text-red-400",children:"↑"}),"down"===s.trend&&(0,t.jsx)("span",{className:"ml-1 text-xs text-green-400",children:"↓"})]})},{title:"Avg. latency added",dataIndex:"avgLatency",key:"avgLatency",align:"right",sorter:!0,sortOrder:"avgLatency"===n?"desc"===d?"descend":"ascend":null,render:e=>(0,t.jsx)("span",{className:null==e?"text-gray-400":e>150?"text-red-600":e>50?"text-amber-600":"text-green-600",children:null!=e?`${e}ms`:"—"})},{title:"Status",dataIndex:"status",key:"status",align:"center",render:e=>(0,t.jsxs)("span",{className:"inline-flex items-center gap-1.5",children:[(0,t.jsx)("span",{className:`w-2 h-2 rounded-full ${"healthy"===e?"bg-green-500":"warning"===e?"bg-amber-500":"bg-red-500"}`}),(0,t.jsx)("span",{className:"text-xs text-gray-600 capitalize",children:e})]})}],_=["failRate","requestsEvaluated","avgLatency"];return(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-start justify-between mb-5",children:[(0,t.jsxs)("div",{children:[(0,t.jsxs)("div",{className:"flex items-center gap-2 mb-1",children:[(0,t.jsx)(tZ.SafetyOutlined,{className:"text-lg text-indigo-500"}),(0,t.jsx)("h1",{className:"text-xl font-semibold text-gray-900",children:"Guardrails Monitor"})]}),(0,t.jsx)("p",{className:"text-sm text-gray-500",children:"Monitor guardrail performance across all requests"})]}),(0,t.jsx)("div",{className:"flex items-center gap-3",children:(0,t.jsx)(A.Button,{type:"default",icon:(0,t.jsx)(tS.DownloadOutlined,{}),title:"Coming soon",children:"Export Data"})})]}),(0,t.jsxs)(t4.Grid,{numItems:2,numItemsLg:5,className:"gap-4 mb-6 items-stretch",children:[(0,t.jsx)(t2.Col,{className:"flex flex-col",children:(0,t.jsx)(sr,{label:"Total Evaluations",value:j.totalRequests.toLocaleString()})}),(0,t.jsx)(t2.Col,{className:"flex flex-col",children:(0,t.jsx)(sr,{label:"Blocked Requests",value:j.totalBlocked.toLocaleString(),valueColor:"text-red-600",icon:(0,t.jsx)(ep.WarningOutlined,{className:"text-red-400"})})}),(0,t.jsx)(t2.Col,{className:"flex flex-col",children:(0,t.jsx)(sr,{label:"Pass Rate",value:`${j.passRate}%`,valueColor:"text-green-600",icon:(0,t.jsx)(sd,{className:"text-green-400"})})}),(0,t.jsx)(t2.Col,{className:"flex flex-col",children:(0,t.jsx)(sr,{label:"Avg. latency added",value:`${j.avgLatency}ms`,valueColor:j.avgLatency>150?"text-red-600":j.avgLatency>50?"text-amber-600":"text-green-600"})}),(0,t.jsx)(t2.Col,{className:"flex flex-col",children:(0,t.jsx)(sr,{label:"Active Guardrails",value:j.count})})]}),(0,t.jsx)("div",{className:"mb-6",children:(0,t.jsx)(sm,{data:y})}),(0,t.jsxs)(ef.Card,{className:"bg-white border border-gray-200 rounded-lg",children:[(p||h)&&(0,t.jsxs)("div",{className:"px-6 py-4 border-b border-gray-200 flex items-center gap-2",children:[p&&(0,t.jsx)(eS.Spin,{size:"small"}),h&&(0,t.jsx)("span",{className:"text-sm text-red-600",children:"Failed to load data. Try again."})]}),(0,t.jsxs)("div",{className:"px-6 py-4 border-b border-gray-200 flex items-start justify-between gap-4",children:[(0,t.jsxs)("div",{children:[(0,t.jsx)(eb.Title,{className:"text-base font-semibold text-gray-900",children:"Guardrail Performance"}),(0,t.jsx)("p",{className:"text-xs text-gray-500 mt-0.5",children:"Click a guardrail to view details, logs, and configuration"})]}),(0,t.jsx)("div",{className:"flex items-center gap-2",children:(0,t.jsx)(A.Button,{type:"default",icon:(0,t.jsx)(t0.SettingOutlined,{}),onClick:()=>u(!0),title:"Evaluation settings"})})]}),(0,t.jsx)(tt.Table,{columns:b,dataSource:f,rowKey:"id",pagination:!1,loading:p,onChange:(e,t,s)=>{s?.field&&_.includes(s.field)&&(o(s.field),c("ascend"===s.order?"asc":"desc"))},locale:0!==g.length||p?void 0:{emptyText:"No data for this period"},onRow:e=>({onClick:()=>r(e.id),style:{cursor:"pointer"}})})]}),(0,t.jsx)(t9,{open:m,onClose:()=>u(!1),accessToken:e})]})}let sp=new Date,sh=new Date;function sg({accessToken:e=null}){let[s,a]=(0,i.useState)({type:"overview"}),r=(0,i.useMemo)(()=>new Date(sh),[]),n=(0,i.useMemo)(()=>new Date(sp),[]),[o,d]=(0,i.useState)({from:r,to:n}),c=o.from?(0,l.formatDate)(o.from):"",m=o.to?(0,l.formatDate)(o.to):"",u=(0,i.useCallback)(e=>{d(e)},[]);return(0,t.jsxs)("div",{className:"p-6 w-full min-w-0 flex-1",children:[(0,t.jsx)("div",{className:"flex items-center justify-end mb-4",children:(0,t.jsx)(tJ.default,{value:o,onValueChange:u,label:"",showTimeRange:!1})}),"overview"===s.type?(0,t.jsx)(sx,{accessToken:e,startDate:c,endDate:m,onSelectGuardrail:e=>{a({type:"detail",guardrailId:e})}}):(0,t.jsx)(sn,{guardrailId:s.guardrailId,onBack:()=>{a({type:"overview"})},accessToken:e,startDate:c,endDate:m})]})}sh.setDate(sh.getDate()-7);var sj=e.i(487304),sy=e.i(760221);e.i(111790);var sf=e.i(280881),sb=e.i(934879),s_=e.i(402874),sv=e.i(797305),sN=e.i(109799),sw=e.i(747871),sk=e.i(56567),sC=e.i(468133),sS=e.i(871943),sT=e.i(502547),sI=e.i(278587),sF=e.i(655913),sA=e.i(38419),sP=e.i(78334),sL=e.i(555436),sM=e.i(284614),sD=e.i(389083),sE=e.i(206929),sO=e.i(35983),sz=e.i(898586),sR=e.i(9314),sB=e.i(552130),sq=e.i(533882),s$=e.i(651904),sU=e.i(460285),sV=e.i(435451),sG=e.i(916940),sH=e.i(127952),sK=e.i(902555),sW=e.i(162386);let sQ=(e,t,s)=>"Admin"===e||!!s&&!!t&&s.some(e=>e.members?.some(e=>e.user_id===t&&"org_admin"===e.user_role)),sY=(e,t,s)=>"Admin"===e?s||[]:s&&t?s.filter(e=>e.members?.some(e=>e.user_id===t&&"org_admin"===e.user_role)):[],sJ=({teams:e,searchParams:s,accessToken:a,setTeams:r,userID:n,userRole:o,organizations:d,premiumUser:c=!1})=>{let x,h,y,f;console.log(`organizations: ${JSON.stringify(d)}`);let{data:b}=(0,sN.useOrganizations)(),[_,v]=(0,i.useState)(""),[N,w]=(0,i.useState)(null),[k,S]=(0,i.useState)(null),[F,P]=(0,i.useState)(!1),[L,M]=(0,i.useState)({team_id:"",team_alias:"",organization_id:"",sort_by:"created_at",sort_order:"desc"});(0,i.useEffect)(()=>{console.log(`inside useeffect - ${_}`),a&&(0,eR.fetchTeams)(a,n,o,N,r),e6()},[_]);let[D]=p.Form.useForm(),[E]=p.Form.useForm(),{Title:O,Paragraph:z}=sz.Typography,[R,B]=(0,i.useState)(""),[q,$]=(0,i.useState)(!1),[U,V]=(0,i.useState)(null),[G,H]=(0,i.useState)(null),[K,W]=(0,i.useState)(!1),[Q,Y]=(0,i.useState)(!1),[J,X]=(0,i.useState)(!1),[Z,ee]=(0,i.useState)(!1),[et,es]=(0,i.useState)([]),[ea,ei]=(0,i.useState)(!1),[en,eo]=(0,i.useState)(null),[ed,ec]=(0,i.useState)([]),[em,ex]=(0,i.useState)({}),[ep,eh]=(0,i.useState)(!1),[eg,ej]=(0,i.useState)([]),[eb,eS]=(0,i.useState)([]),[eT,eI]=(0,i.useState)({}),[eF,eA]=(0,i.useState)([]),[eP,eL]=(0,i.useState)([]),[eD,eE]=(0,i.useState)(!1),[eO,ez]=(0,i.useState)({}),[eB,eH]=(0,i.useState)(null),[eK,eW]=(0,i.useState)(0);(0,i.useEffect)(()=>{let e;console.log(`currentOrgForCreateTeam: ${k}`);let t=(e=[],k&&k.models.length>0?(console.log(`organization.models: ${k.models}`),e=k.models):e=et,(0,T.unfurlWildcardModelsInList)(e,et));console.log(`models: ${t}`),ec(t),D.setFieldValue("models",[])},[k,et]),(0,i.useEffect)(()=>{if(Q){let e=sY(o,n,d);if(1===e.length){let t=e[0];D.setFieldValue("organization_id",t.organization_id),S(t)}else D.setFieldValue("organization_id",N?.organization_id||null),S(N)}},[Q,o,n,d,N]),(0,i.useEffect)(()=>{let e=async()=>{try{if(null==a)return;let e=(await (0,l.getPoliciesList)(a)).policies.map(e=>e.policy_name);eS(e)}catch(e){console.error("Failed to fetch policies:",e)}};(async()=>{try{if(null==a)return;let e=(await (0,l.getGuardrailsList)(a)).guardrails.map(e=>e.guardrail_name);ej(e)}catch(e){console.error("Failed to fetch guardrails:",e)}})(),e()},[a]);let eQ=async()=>{try{if(null==a)return;let e=await (0,l.fetchMCPAccessGroups)(a);eL(e)}catch(e){console.error("Failed to fetch MCP access groups:",e)}};(0,i.useEffect)(()=>{eQ()},[a]),(0,i.useEffect)(()=>{e&&ex(e.reduce((e,t)=>(e[t.team_id]={keys:t.keys||[],team_info:{members_with_roles:t.members_with_roles||[]}},e),{}))},[e]);let e2=async e=>{eo(e),ei(!0)},e4=async()=>{if(null!=en&&null!=e&&null!=a)try{eh(!0),await (0,l.teamDeleteCall)(a,en.team_id),await (0,eR.fetchTeams)(a,n,o,N,r),eM.default.success("Team deleted successfully")}catch(e){eM.default.fromBackend("Error deleting the team: "+e)}finally{eh(!1),ei(!1),eo(null)}};(0,i.useEffect)(()=>{(async()=>{try{if(null===n||null===o||null===a)return;let e=await (0,T.fetchAvailableModelsForTeamOrKey)(n,o,a);e&&es(e)}catch(e){console.error("Error fetching user models:",e)}})()},[a,n,o,e]);let e5=async t=>{try{if(console.log(`formValues: ${JSON.stringify(t)}`),null!=a){let s=t?.team_alias,i=e?.map(e=>e.team_alias)??[],n=t?.organization_id||N?.organization_id;if(""===n||"string"!=typeof n?t.organization_id=null:t.organization_id=n.trim(),i.includes(s))throw Error(`Team alias ${s} already exists, please pick another alias`);if(eM.default.info("Creating Team"),eF.length>0){let e={};if(t.metadata)try{e=JSON.parse(t.metadata)}catch(e){console.warn("Invalid JSON in metadata field, starting with empty object")}e={...e,logging:eF.filter(e=>e.callback_name)},t.metadata=JSON.stringify(e)}if(t.secret_manager_settings&&"string"==typeof t.secret_manager_settings)if(""===t.secret_manager_settings.trim())delete t.secret_manager_settings;else try{t.secret_manager_settings=JSON.parse(t.secret_manager_settings)}catch(e){throw Error("Failed to parse secret manager settings: "+e)}if(t.allowed_vector_store_ids&&t.allowed_vector_store_ids.length>0||t.allowed_mcp_servers_and_groups&&(t.allowed_mcp_servers_and_groups.servers?.length>0||t.allowed_mcp_servers_and_groups.accessGroups?.length>0||t.allowed_mcp_servers_and_groups.toolPermissions)){if(t.object_permission={},t.allowed_vector_store_ids&&t.allowed_vector_store_ids.length>0&&(t.object_permission.vector_stores=t.allowed_vector_store_ids,delete t.allowed_vector_store_ids),t.allowed_mcp_servers_and_groups){let{servers:e,accessGroups:s}=t.allowed_mcp_servers_and_groups;e&&e.length>0&&(t.object_permission.mcp_servers=e),s&&s.length>0&&(t.object_permission.mcp_access_groups=s),delete t.allowed_mcp_servers_and_groups}t.mcp_tool_permissions&&Object.keys(t.mcp_tool_permissions).length>0&&(t.object_permission||(t.object_permission={}),t.object_permission.mcp_tool_permissions=t.mcp_tool_permissions,delete t.mcp_tool_permissions)}if(t.allowed_mcp_access_groups&&t.allowed_mcp_access_groups.length>0&&(t.object_permission||(t.object_permission={}),t.object_permission.mcp_access_groups=t.allowed_mcp_access_groups,delete t.allowed_mcp_access_groups),t.allowed_agents_and_groups){let{agents:e,accessGroups:s}=t.allowed_agents_and_groups;t.object_permission||(t.object_permission={}),e&&e.length>0&&(t.object_permission.agents=e),s&&s.length>0&&(t.object_permission.agent_access_groups=s),delete t.allowed_agents_and_groups}Object.keys(eO).length>0&&(t.model_aliases=eO),eB?.router_settings&&Object.values(eB.router_settings).some(e=>null!=e&&""!==e)&&(t.router_settings=eB.router_settings);let o=await (0,l.teamCreateCall)(a,t);null!==e?r([...e,o]):r([o]),console.log(`response for team create call: ${o}`),eM.default.success("Team created"),D.resetFields(),eA([]),ez({}),eH(null),eW(e=>e+1),Y(!1)}}catch(e){console.error("Error creating the team:",e),eM.default.fromBackend("Error creating the team: "+e)}},e6=()=>{v(new Date().toLocaleString())},e3=(e,t)=>{let s={...L,[e]:t};M(s),a&&(0,l.v2TeamListCall)(a,s.organization_id||null,null,s.team_id||null,s.team_alias||null).then(e=>{e&&e.teams&&r(e.teams)}).catch(e=>{console.error("Error fetching teams:",e)})};return(0,t.jsx)("div",{className:"w-full mx-4 h-[75vh]",children:(0,t.jsx)(t4.Grid,{numItems:1,className:"gap-2 p-8 w-full mt-2",children:(0,t.jsxs)(t2.Col,{numColSpan:1,className:"flex flex-col gap-2",children:[sQ(o,n,d)&&(0,t.jsx)(m.Button,{className:"w-fit",onClick:()=>Y(!0),children:"+ Create New Team"}),G?(0,t.jsx)(sk.default,{teamId:G,onUpdate:e=>{r(t=>{if(null==t)return t;let s=t.map(t=>e.team_id===t.team_id?(0,tC.updateExistingKeys)(t,e):t);return a&&(0,eR.fetchTeams)(a,n,o,N,r),s})},onClose:()=>{H(null),W(!1)},accessToken:a,is_team_admin:(e=>{if(null==e||null==e.members_with_roles)return!1;for(let t=0;t