import {z} from 'zod' export type AIGuardMessageContentText = string; export type AIGuardImageURL = {url: string}; export type AIGuardContentPartType = 'text' | 'image_url'; export type AIGuardContentPart = {image_url?: AIGuardImageURL | undefined, text?: string | undefined, type: AIGuardContentPartType}; export type AIGuardMessageContentParts = Array; export type AIGuardMessageContent = AIGuardMessageContentText | AIGuardMessageContentParts; export type AIGuardMessageRole = 'user' | 'assistant' | 'system' | 'developer' | 'tool'; export type AIGuardToolCallFunction = {arguments: string, name: string}; export type AIGuardToolCall = {function: AIGuardToolCallFunction, id: string}; export type AIGuardMessage = {content?: AIGuardMessageContent | undefined, role: AIGuardMessageRole, tool_call_id?: string | undefined, tool_calls?: Array | undefined}; export type AIGuardCodingAgent = string; export type AIGuardGlobalConfidenceThreshold = number; export type AIGuardConfidenceThreshold = {flagging_global?: number | undefined} | {[key: string]: number}; export type AIGuardConfidenceThresholdOverride = AIGuardGlobalConfidenceThreshold | AIGuardConfidenceThreshold; export type AIGuardToolPolicyAction = 'PASS' | 'BLOCK' | 'EVALUATE'; export type AIGuardMeta = {coding_agent?: AIGuardCodingAgent | undefined, confidence_threshold?: AIGuardConfidenceThresholdOverride | undefined, env?: string | undefined, is_sds_enabled_override?: boolean | undefined, service?: string | undefined, tool_policies?: {[key: string]: AIGuardToolPolicyAction} | undefined}; export type AIGuardEvaluateRequestDataAttributes = {messages: Array, meta?: AIGuardMeta | undefined}; export type AIGuardEvaluationType = 'evaluations'; export type AIGuardEvaluateRequestData = {attributes: AIGuardEvaluateRequestDataAttributes, type: AIGuardEvaluationType}; export type AIGuardEvaluateRequest = {data: AIGuardEvaluateRequestData}; export type CreateApiApiV2AiGuardEvaluateArgs = {body: AIGuardEvaluateRequest}; export type CreateApiApiV2AiGuardEvaluateOptions = {baseUrl?: string | undefined, apiKeyAuth?: string | undefined, appKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const aIGuardAction = z.enum(["ALLOW", "DENY", "ABORT"]); export const aIGuardRedactionReplacement = z.object({path: z.string(), replacement: z.string()}); export const aIGuardScfwOutcome = z.enum(["ALLOW", "WARN", "BLOCK"]); export const aIGuardScfwMatchedRule = z.object({outcome: aIGuardScfwOutcome, rule: z.string()}); export const aIGuardScfwPackageFinding = z.object({ecosystem: z.string(), matched_rules: z.array(aIGuardScfwMatchedRule).optional(), name: z.string(), outcome: aIGuardScfwOutcome, version: z.string()}); export const aIGuardScfwFindings = z.object({packages: z.array(aIGuardScfwPackageFinding).optional(), recommended_action: aIGuardScfwOutcome}); export const aIGuardSdsFindingLocation = z.object({end_index_exclusive: z.number().int(), path: z.string(), start_index: z.number().int()}); export const aIGuardSdsFinding = z.object({category: z.string(), location: aIGuardSdsFindingLocation, rule_display_name: z.string(), rule_tag: z.string()}); export const aIGuardEvaluateAttributesResponse = z.object({action: aIGuardAction, global_prob: z.number().optional(), is_blocking_enabled: z.boolean(), reason: z.string(), redaction_replacements: z.array(aIGuardRedactionReplacement).optional(), scfw_findings: aIGuardScfwFindings.optional(), sds_findings: z.array(aIGuardSdsFinding).optional(), tag_probs: z.record(z.string(), z.number()).nullable(), tags: z.array(z.string())}); export const aIGuardEvaluationType = z.literal("evaluations"); export const aIGuardEvaluateDataResponse = z.object({attributes: aIGuardEvaluateAttributesResponse, id: z.string(), type: aIGuardEvaluationType}); export const aIGuardEvaluateResponse = z.object({data: aIGuardEvaluateDataResponse}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * Evaluate an AI Guard request * * POST /api/v2/ai-guard/evaluate * * Also accepts auth: AuthZ */ export const createApiApiV2AiGuardEvaluate = async (args: CreateApiApiV2AiGuardEvaluateArgs, options?: CreateApiApiV2AiGuardEvaluateOptions) => { const {baseUrl = "https://api.datadoghq.com", fetch: fetchFn = fetch, apiKeyAuth, appKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (apiKeyAuth !== undefined) headers.set("DD-API-KEY", apiKeyAuth) if (appKeyAuth !== undefined) headers.set("DD-APPLICATION-KEY", appKeyAuth) const url = `${baseUrl.replace(/\/+$/, '')}/api/v2/ai-guard/evaluate${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(aIGuardEvaluateResponse, await res.json()) };