UNPKG

@genkit-ai/ai

Version:

Genkit AI framework generative AI APIs.

1 lines 2.72 kB
{"version":3,"sources":["../../src/formats/array.ts"],"sourcesContent":["/**\n * Copyright 2024 Google LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nimport { GenkitError } from '@genkit-ai/core';\nimport { extractItems } from '../extract';\nimport type { Formatter } from './types';\n\nexport const arrayFormatter: Formatter<unknown[], unknown[]> = {\n name: 'array',\n config: {\n contentType: 'application/json',\n constrained: true,\n },\n handler: (schema) => {\n if (schema && schema.type !== 'array') {\n throw new GenkitError({\n status: 'INVALID_ARGUMENT',\n message: `Must supply an 'array' schema type when using the 'items' parser format.`,\n });\n }\n\n let instructions: string | undefined;\n if (schema) {\n instructions = `Output should be a JSON array conforming to the following schema:\n \n\\`\\`\\`\n${JSON.stringify(schema)}\n\\`\\`\\`\n `;\n }\n\n return {\n parseChunk: (chunk) => {\n // first, determine the cursor position from the previous chunks\n const cursor = chunk.previousChunks?.length\n ? extractItems(chunk.previousText).cursor\n : 0;\n // then, extract the items starting at that cursor\n const { items } = extractItems(chunk.accumulatedText, cursor);\n\n return items;\n },\n\n parseMessage: (message) => {\n const { items } = extractItems(message.text, 0);\n return items;\n },\n\n instructions,\n };\n },\n};\n"],"mappings":"AAgBA,SAAS,mBAAmB;AAC5B,SAAS,oBAAoB;AAGtB,MAAM,iBAAkD;AAAA,EAC7D,MAAM;AAAA,EACN,QAAQ;AAAA,IACN,aAAa;AAAA,IACb,aAAa;AAAA,EACf;AAAA,EACA,SAAS,CAAC,WAAW;AACnB,QAAI,UAAU,OAAO,SAAS,SAAS;AACrC,YAAM,IAAI,YAAY;AAAA,QACpB,QAAQ;AAAA,QACR,SAAS;AAAA,MACX,CAAC;AAAA,IACH;AAEA,QAAI;AACJ,QAAI,QAAQ;AACV,qBAAe;AAAA;AAAA;AAAA,EAGnB,KAAK,UAAU,MAAM,CAAC;AAAA;AAAA;AAAA,IAGpB;AAEA,WAAO;AAAA,MACL,YAAY,CAAC,UAAU;AAErB,cAAM,SAAS,MAAM,gBAAgB,SACjC,aAAa,MAAM,YAAY,EAAE,SACjC;AAEJ,cAAM,EAAE,MAAM,IAAI,aAAa,MAAM,iBAAiB,MAAM;AAE5D,eAAO;AAAA,MACT;AAAA,MAEA,cAAc,CAAC,YAAY;AACzB,cAAM,EAAE,MAAM,IAAI,aAAa,QAAQ,MAAM,CAAC;AAC9C,eAAO;AAAA,MACT;AAAA,MAEA;AAAA,IACF;AAAA,EACF;AACF;","names":[]}