Firebase Genkit 是一种开源框架,可帮助您构建、部署和监控可正式投入使用的 AI 赋能的应用。
Genkit 专为应用开发者设计,可帮助您以熟悉的模式和范式轻松将强大的 AI 功能集成到您的应用中。它由 Firebase 背后的同一团队构建,充分利用我们在构建全球数百万开发者所用工具方面的经验。
使用 Genkit 创建具有以下功能的应用:生成自定义内容、使用语义搜索、处理非结构化输入、回答包含业务数据的问题、自主做出决策、编排工具调用,等等!
Genkit 目前支持使用 JavaScript/TypeScript (Node.js) 进行服务器端开发,并且积极进行 Go 支持。
在 GitHub 的 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 服务集成。
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 |
矢量数据库:ChromaDB |
pinecone |
矢量数据库:Pinecone |
google-cloud |
监控工具:Google Cloud Trace、Google Cloud Logging |
firebase |
云部署:Cloud Functions、Firebase Authentication、App Check 矢量数据库:Cloud Firestore 矢量存储 |
langchain |
在 Genkit 流中使用 LangChain 链和实用程序 |
开始
阅读使用入门指南,了解如何安装 Genkit 并运行您的第一个 AI 流程。