Firebase Genkit

Firebase Genkit 是一个开源框架,可帮助您构建、部署和监控可正式投入使用的 依托 AI 技术的应用

Genkit 徽标

Genkit 专为应用开发者设计,可帮助您使用熟悉的模式和范式轻松将强大的 AI 功能集成到您的应用中。它由 Firebase 背后的同一支团队构建,并利用我们在构建全球数百万开发者使用的工具方面的经验。

使用 Genkit 可以创建生成自定义内容、使用语义搜索、处理非结构化输入、使用业务数据回答问题、自动做出决策、编排工具调用等的应用!

Genkit 目前支持使用 JavaScript/TypeScript (Node.js) 进行服务器端开发,并且还在积极开发 Go。

关注其开发情况,或者在其 GitHub 代码库中做出自己的贡献。

主要特征

Genkit 会帮助您完成 AI 开发历程的每一步,从原型设计开始,到在生产环境中进行监控,因此有很多值得探讨的话题。

为帮助你快速上手,我们相信你会喜欢以下 10 项 Genkit 重要功能:

1. 多种模型,一个界面

Genkit 提供了一系列插件,可让您访问开箱即用的热门模型,并具有灵活的模型抽象功能,可让您轻松集成任何模型 API 并使用由社区维护的模型。试用新模型就像更改单个参数一样简单,但每个模型都可以指定自定义配置。

import { geminiPro } from '@genkit-ai/vertexai';
import { ollama } from 'genkitx-ollama';
import { generate } from '@genkit-ai/ai';

function flipACoin(a, b) {
  return Math.random() > 0.5 ? a : b;
}

const result = await generate({
  model: flipACoin(geminiPro, 'ollama/gemma'),
  config: { temperature: 0.3, maxOutputTokens: 200 },
  prompt: 'What makes you the best LLM out there?',
});

console.log(result.text());

2. 结构化输出

使用 Zod 架构通过 Genkit 生成强类型数据。这有助于您分析非结构化文本、生成广告素材内容、选择任务,以及将结果作为结构化类型安全的对象发送回应用。

import { generate } from "@genkit-ai/ai";
import { geminiPro } from "@genkit-ai/vertexai";
import { z } from "zod";

const CreatureSchema = z.object({
  name: z.string().describe('the name of the creature'),
  hitPoints: z.number().describe('hit points, between 5 and 100'),
  attacks: z.array(z.object({
    name: z.string(),
    damage: z.number().describe('amount of damage, between 2 and 25'),
  })).describe('3 attacks the creature can use')
});

const createCreature = defineFlow({
    name: "createCreature",
    inputSchema: z.string(),
    outputSchema: CreatureSchema,
  },
  (habitat) => {
    const result = await generate({
      model: geminiPro,
      prompt: `You are a brilliant RPG designer. Generate a creature that lives in ${habitat}.`,
      output: {schema: CreatureSchema}
    });
    // strongly typed and ready to go
    return result.output();
  }
)

console.log(await createCreature("a developer conference"));

3. 多模态、多媒体

Genkit 提供了一种通用的内容格式,它支持混合使用文本、数据和任意媒体。这样,您就可以将 Genkit 用于执行任何生成任务(如图片生成)的模型,而不仅仅是 LLM。

import { imagen2, geminiProVision } from '@genkit-ai/vertexai';
import { generate } from '@genkit-ai/ai';

const imageResult = await generate({
  model: imagen2,
  prompt: 'Generate an image of a very specific historical time and place.',
});
const generatedImage = imageResult.media();

const descriptionResult = await generate({
  model: geminiProVision,
  prompt: [
    {
      text: 'What is the historical time and place represented in this picture?',
    },
    { media: generatedImage },
  ],
});
console.log(descriptionResult.text());

4.提供 LLM 工具

Genkit 支持通过工具轻松使用 LLM 进行函数调用。借助工具,AI 可以提取数据、显示界面、向数据库写入数据,或执行您可以编码的任何其他操作。

import { generate, defineTool } from '@genkit-ai/ai';
import { geminiPro } from '@genkit-ai/vertexai';
import { z } from 'zod';

const createReminder = defineTool(
  {
    name: 'createReminder',
    description: 'Use this to create reminders for things in the future',
    inputSchema: z.object({
      time: z
        .string()
        .describe('ISO timestamp string, e.g. 2024-04-03T12:23:00Z'),
      reminder: z.string().describe('the content of the reminder'),
    }),
    outputSchema: z.number().describe('the ID of the created reminder'),
  },
  (reminder) => db.reminders.create(reminder)
);

const searchNotes = defineTool(
  {
    name: 'searchNotes',
    description: "Use this to search the user's notes for people or phrases",
    inputSchema: z.string().describe('the search query'),
    outputSchema: z.object({ notes: z.array(NoteSchema) }),
  },
  (query) => db.notes.search(query)
);

const result = await generate({
  model: geminiPro,
  tools: [createReminder, searchNotes],
  prompt: `
  You are a note-taking assistant. Using the tools available, try to answer the provided query.
  If you create a reminder, describe in text the reminder you created as a response.

  Query: I took a note about a meeting with Anna - can you set a reminder for the time?
  `,
});
console.log(result.text());

5. 使用 Dotprompt 管理提示

提示工程不仅仅是调整文本。您使用的模型、提供的参数和请求的格式都会影响输出的质量。Genkit 提供了 Dotprompt,这是一种提示文件格式,可让您将所有内容整合到单个文件中,从而更轻松地进行测试和整理。

---
model: vertexai/gemini-1.0-pro
config:
  temperature: 0.9
input:
  schema:
    properties:
      location: {type: string}
      style: {type: string}
      name: {type: string}
    required: [location]
  default:
    location: a restaurant
---

You are the world's most welcoming AI assistant and are currently working at {{location}}.

Greet a guest{{#if name}} named {{name}}{{/if}}{{#if style}} in the style of {{style}}{{/if}}.

6. 在本地运行流

生成式 AI 的结果存在大量差异,因此进行实验非常重要。通过本地 Genkit 开发者界面,您可以与模型和检索器等基本的 AI 组件进行交互,并手动测试端到端流程(包括您编写的所有自定义代码)。

7. 检查轨迹

由于随机性和隐藏过程,使用 AI 调试复杂的多步骤工作流可能具有挑战性。Genkit 在开发者界面中提供了一个轨迹检查器,可让您检查流程中每个模型调用和步骤的轨迹。它可以查看生产环境中的跟踪记录,甚至可以渲染映像!

8. 开放性和可扩展性

AI 生态系统的发展速度远超任何一个团队跟上步伐。Genkit 采用开放式插件模型,可提供与新模型、检索器等的预构建集成。虽然 Genkit 团队维护着一小部分官方插件,但任何人都可以随时将自己的 Genkit 插件发布到 NPM。

找不到适用于所需特定集成的插件?没关系,Genkit 的抽象比较灵活,可让您轻松构建可集成到框架中的自定义组件,例如以下自定义 Firestore 检索器:

import { embed } from '@genkit-ai/ai/embedder';
import { Document, defineRetriever } from '@genkit-ai/ai/retriever';
import { textEmbeddingGecko } from '@genkit-ai/vertexai';
import {
  FieldValue,
  VectorQuery,
  VectorQuerySnapshot,
} from '@google-cloud/firestore';
import { Firestore } from 'firebase-admin/firestore';
import * as z from 'zod';
import { augmentedPrompt } from './prompt';

const QueryOptions = z.object({
  k: z.number().optional(),
});

const firestoreArtifactsRetriever = defineRetriever(
  {
    name: 'firestore/artifacts',
    configSchema: QueryOptions,
  },
  async (input, options) => {
    const embedding = await embed({
      embedder: textEmbeddingGecko,
      content: input,
    });

    const db = new Firestore();
    const coll = db.collection('vectors' /* your collection name */);

    const vectorQuery: VectorQuery = coll.findNearest(
      'embedding' /* the name of the field that contains the vector */,
      FieldValue.vector(embedding),
      {
        limit: options.k ?? 3,
        distanceMeasure: 'COSINE',
      }
    );

    const vectorQuerySnapshot: VectorQuerySnapshot = await vectorQuery.get();
    return {
      documents: vectorQuerySnapshot.docs.map((doc) =>
        // doc.data() represents the Firestore document. You may process
        // it as needed to generate a Genkit document object, depending on your
        // storage format.
        Document.fromText(doc.data().content.text)
      ),
    };
  }
);

9. 专为生产环境而构建

将流轻松部署到任何能够提供 Express.js 应用的平台。Genkit 使用 OpenTelemetry 和自定义元数据进行全面插桩,可进行企业级生产监控。

Google Cloud 和 Firebase 还有一些官方插件,可帮助您将数据导出到 Google Cloud 的运维套件并与 Cloud Functions for Firebase、Firebase Authentication、App Check 和 Firestore 等 Firebase 服务集成。

Cloud Trace 屏幕截图

10. 授权和安全处理

在构建任何面向公众的应用时,请务必保护存储在您系统中的数据。对于 LLM,您需要格外小心,以确保模型只访问它应该访问的数据,将工具调用的范围适当地限定为调用 LLM 的用户,并且只有经过验证的客户端应用会调用该流程。

Genkit 提供了用于管理授权政策和上下文的机制。

import { defineFlow, runFlow } from '@genkit-ai/flow';

export const selfSummaryFlow = defineFlow(
  {
    name: 'selfSummaryFlow',
    inputSchema: z.object({uid: z.string()}),
    outputSchema: z.string(),
    authPolicy: (auth, input) => {
      if (!auth) {
        throw new Error('Authorization required.');
      }
      if (input.uid !== auth.uid) {
        throw new Error('You may only summarize your own profile data.');
      }
    }
  },
  async (input) => { ... });

集成

Genkit 通过其插件系统与 AI 模型、矢量数据库、遥测平台等集成。以下插件由 Genkit 团队维护:

官方插件
googleai 生成模型:Gemini Pro、Gemini 1.5 Pro、Gemini Pro Vision
嵌入模型:Gecko 文本嵌入
vertexai 生成模型:Gemini Pro、Gemini Pro Vision、Gemini 1.5 Flash、Gemini 1.5 Pro、Imagen2、Anthropic Claude 3
嵌入模型:Gecko 文本嵌入
评估器:Vertex AI 评估
ollama 生成模型:许多本地模型,包括 Gemma、Llama 3、Mistral 等
chroma 矢量数据库:CromaDB
pinecone 矢量数据库:Pinecone
google-cloud Monitoring 工具:Google Cloud Trace、Google Cloud Logging
firebase 云部署:Cloud Functions、Firebase Authentication、App Check
矢量数据库:Cloud Firestore 矢量存储区
langchain 在 Genkit 流中使用 LangChain 链和实用程序

开始使用

阅读使用入门指南,了解如何安装 Genkit 并运行您的第一个 AI 流程。