Loading...
Loading...
使用Firebase Genkit构建可投入生产的AI工作流。适用于创建流程、工具调用Agent、RAG管道、多Agent系统,或将AI部署到Firebase/Cloud Run的场景。支持TypeScript、Go和Python,同时兼容Gemini、OpenAI、Anthropic、Ollama和Vertex AI插件。
npx skill4agent add supercent-io/skills-template genkit.prompt# npm(推荐用于JavaScript/TypeScript)
npm install -g genkit-cli
# macOS/Linux二进制包
curl -sL cli.genkit.dev | bashmkdir my-genkit-app && cd my-genkit-app
npm init -y
npm pkg set type=module
npm install -D typescript tsx
npx tsc --init
mkdir src && touch src/index.ts# 核心库 + Google AI(Gemini)——免费层级,无需信用卡
npm install genkit @genkit-ai/google-genai
# 或:Vertex AI(需要GCP项目)
npm install genkit @genkit-ai/vertexai
# 或:OpenAI
npm install genkit genkitx-openai
# 或:Anthropic(Claude)
npm install genkit genkitx-anthropic
# 或:Ollama(本地模型)
npm install genkit genkitx-ollama# Google AI(Gemini)
export GEMINI_API_KEY=your_key_here
# OpenAI
export OPENAI_API_KEY=your_key_here
# Anthropic
export ANTHROPIC_API_KEY=your_key_hereimport { googleAI } from '@genkit-ai/google-genai';
import { genkit } from 'genkit';
const ai = genkit({
plugins: [googleAI()],
model: googleAI.model('gemini-2.5-flash'), // 默认模型
});import { genkit, z } from 'genkit';
import { googleAI } from '@genkit-ai/google-genai';
const ai = genkit({ plugins: [googleAI()] });
// 使用Zod定义输入/输出模式
const SummaryInputSchema = z.object({
text: z.string().describe('需要总结的文本'),
maxWords: z.number().optional().default(100),
});
const SummaryOutputSchema = z.object({
summary: z.string(),
keyPoints: z.array(z.string()),
});
export const summarizeFlow = ai.defineFlow(
{
name: 'summarizeFlow',
inputSchema: SummaryInputSchema,
outputSchema: SummaryOutputSchema,
},
async ({ text, maxWords }) => {
const { output } = await ai.generate({
model: googleAI.model('gemini-2.5-flash'),
prompt: `将以下文本总结为最多${maxWords}个单词,并提取关键点:\n\n${text}`,
output: { schema: SummaryOutputSchema },
});
if (!output) throw new Error('未生成输出内容');
return output;
}
);
// 调用流程
const result = await summarizeFlow({
text: '长文章内容...',
maxWords: 50,
});
console.log(result.summary);// 简单文本生成
const { text } = await ai.generate({
model: googleAI.model('gemini-2.5-flash'),
prompt: '用一句话解释量子计算。',
});
// 结构化输出
const { output } = await ai.generate({
prompt: '列出3种编程语言及其应用场景',
output: {
schema: z.object({
languages: z.array(z.object({
name: z.string(),
useCase: z.string(),
})),
}),
},
});
// 结合系统提示词
const { text: response } = await ai.generate({
system: '你是一名资深TypeScript工程师,请保持回答简洁。',
prompt: 'TypeScript中的interface和type有什么区别?',
});
// 多模态(图片+文本)
const { text: description } = await ai.generate({
prompt: [
{ text: '这张图片里有什么?' },
{ media: { url: 'https://example.com/image.jpg', contentType: 'image/jpeg' } },
],
});export const streamingFlow = ai.defineFlow(
{
name: 'streamingFlow',
inputSchema: z.object({ topic: z.string() }),
streamSchema: z.string(), // 每个分块的类型
outputSchema: z.object({ full: z.string() }),
},
async ({ topic }, { sendChunk }) => {
const { stream, response } = ai.generateStream({
prompt: `写一篇关于${topic}的详细文章。`,
});
for await (const chunk of stream) {
sendChunk(chunk.text); // 将每个Token流式传输给客户端
}
const { text } = await response;
return { full: text };
}
);
// 客户端消费流
const stream = streamingFlow.stream({ topic: 'AI伦理' });
for await (const chunk of stream.stream) {
process.stdout.write(chunk);
}
const finalOutput = await stream.output;import { z } from 'genkit';
// 定义工具
const getWeatherTool = ai.defineTool(
{
name: 'getWeather',
description: '获取城市当前天气',
inputSchema: z.object({ city: z.string() }),
outputSchema: z.object({ temp: z.number(), condition: z.string() }),
},
async ({ city }) => {
// 调用真实天气API
return { temp: 22, condition: 'sunny' };
}
);
const searchWebTool = ai.defineTool(
{
name: 'searchWeb',
description: '在网络上搜索信息',
inputSchema: z.object({ query: z.string() }),
outputSchema: z.string(),
},
async ({ query }) => {
// 调用搜索API
return `搜索结果:${query}`;
}
);
// 集成工具的Agent流程
export const agentFlow = ai.defineFlow(
{
name: 'agentFlow',
inputSchema: z.object({ question: z.string() }),
outputSchema: z.string(),
},
async ({ question }) => {
const { text } = await ai.generate({
prompt: question,
tools: [getWeatherTool, searchWebTool],
returnToolRequests: false, // 自动执行工具
});
return text;
}
);.prompt# src/prompts/summarize.prompt
---
model: googleai/gemini-2.5-flash
input:
schema:
text: string
style?: string
output:
schema:
summary: string
sentiment: string
---
将以下文本以{{style, default: "professional"}}风格进行总结:
{{text}}
返回包含summary和sentiment(positive/negative/neutral)的JSON格式结果。// 加载并使用dotprompt
const summarizePrompt = ai.prompt('summarize');
const { output } = await summarizePrompt({
text: '文章内容...',
style: 'casual',
});import { devLocalVectorstore } from '@genkit-ai/dev-local-vectorstore';
import { textEmbedding004 } from '@genkit-ai/google-genai';
const ai = genkit({
plugins: [
googleAI(),
devLocalVectorstore([{
indexName: 'documents',
embedder: textEmbedding004,
}]),
],
});
// 索引文档
await ai.index({
indexer: devLocalVectorstoreIndexer('documents'),
docs: [
{ content: [{ text: '文档1内容...' }], metadata: { source: 'doc1' } },
{ content: [{ text: '文档2内容...' }], metadata: { source: 'doc2' } },
],
});
// RAG流程
export const ragFlow = ai.defineFlow(
{
name: 'ragFlow',
inputSchema: z.object({ question: z.string() }),
outputSchema: z.string(),
},
async ({ question }) => {
// 检索相关文档
const docs = await ai.retrieve({
retriever: devLocalVectorstoreRetriever('documents'),
query: question,
options: { k: 3 },
});
// 基于检索到的文档生成答案
const { text } = await ai.generate({
system: '仅使用提供的上下文回答问题。',
prompt: question,
docs,
});
return text;
}
);export const chatFlow = ai.defineFlow(
{
name: 'chatFlow',
inputSchema: z.object({ message: z.string(), sessionId: z.string() }),
outputSchema: z.string(),
},
async ({ message, sessionId }) => {
const session = ai.loadSession(sessionId) ?? ai.createSession({ sessionId });
const chat = session.chat({
system: '你是一个乐于助人的助手。',
});
const { text } = await chat.send(message);
return text;
}
);// 专业Agent
const researchAgent = ai.defineFlow(
{ name: 'researchAgent', inputSchema: z.string(), outputSchema: z.string() },
async (query) => {
const { text } = await ai.generate({
system: '你是一名研究专家,收集事实并引用来源。',
prompt: query,
tools: [searchWebTool],
});
return text;
}
);
const writerAgent = ai.defineFlow(
{ name: 'writerAgent', inputSchema: z.string(), outputSchema: z.string() },
async (brief) => {
const { text } = await ai.generate({
system: '你是一名专业作家,撰写清晰、引人入胜的内容。',
prompt: brief,
});
return text;
}
);
// 编排器分配任务给专业Agent
export const contentPipelineFlow = ai.defineFlow(
{
name: 'contentPipelineFlow',
inputSchema: z.object({ topic: z.string() }),
outputSchema: z.string(),
},
async ({ topic }) => {
const research = await researchAgent(`研究主题:${topic}`);
const article = await writerAgent(`基于以下内容撰写文章:${research}`);
return article;
}
);# 启动开发者UI并连接到你的应用
genkit start -- npx tsx --watch src/index.ts
genkit start -o -- npx tsx src/index.ts # 自动打开浏览器
# 从CLI运行指定流程
genkit flow:run summarizeFlow '{"text": "Hello world", "maxWords": 10}'
# 以流式输出运行流程
genkit flow:run streamingFlow '{"topic": "AI"}' -s
# 评估流程
genkit eval:flow ragFlow --input eval-inputs.json
# 查看所有命令
genkit --help
# 禁用分析遥测
genkit config set analyticsOptOut true# 添加便捷的npm脚本
# package.json
"scripts": {
"genkit:dev": "genkit start -- npx tsx --watch src/index.ts"
}
npm run genkit:devimport { onCallGenkit } from 'firebase-functions/https';
import { defineSecret } from 'firebase-functions/params';
const apiKey = defineSecret('GOOGLE_AI_API_KEY');
export const summarize = onCallGenkit(
{ secrets: [apiKey] },
summarizeFlow
);firebase deploy --only functionsimport express from 'express';
import { expressHandler } from 'genkit/express';
const app = express();
app.use(express.json());
app.post('/summarize', expressHandler(summarizeFlow));
app.post('/chat', expressHandler(chatFlow));
app.listen(3000, () => console.log('服务器运行在3000端口'));# 构建并部署
gcloud run deploy genkit-app \
--source . \
--region us-central1 \
--set-env-vars GEMINI_API_KEY=$GEMINI_API_KEY| 插件 | 包名 | 模型 |
|---|---|---|
| Google AI | | Gemini 2.5 Flash/Pro |
| Vertex AI | | Gemini、Imagen、Claude |
| OpenAI | | GPT-4o、o1等 |
| Anthropic | | Claude 3.5/3 |
| AWS Bedrock | | Claude、Titan等 |
| Ollama | | 本地模型 |
| DeepSeek | | DeepSeek-R1 |
| xAI (Grok) | | Grok模型 |
| 插件 | 包名 |
|---|---|
| Dev Local(测试用) | |
| Pinecone | |
| pgvector | |
| Chroma | |
| Cloud Firestore | |
| LanceDB | |
ai.run()ai.run()defineFlowstreamSchemasendChunk.promptgenerate()nullGENKIT_ENV=devonCallGenkitgenerate()genkit start-- <你的运行命令>async/awaitimport { googleAI } from '@genkit-ai/google-genai';
import { genkit, z } from 'genkit';
const ai = genkit({ plugins: [googleAI()] });
export const helloFlow = ai.defineFlow(
{
name: 'helloFlow',
inputSchema: z.object({ name: z.string() }),
outputSchema: z.string(),
},
async ({ name }) => {
const { text } = await ai.generate(`用创意的方式向${name}问好。`);
return text;
}
);
// 运行流程
const greeting = await helloFlow({ name: 'World' });
console.log(greeting);import { googleAI, textEmbedding004 } from '@genkit-ai/google-genai';
import { devLocalVectorstore } from '@genkit-ai/dev-local-vectorstore';
import { genkit, z } from 'genkit';
const ai = genkit({
plugins: [
googleAI(),
devLocalVectorstore([{ indexName: 'kb', embedder: textEmbedding004 }]),
],
});
// 索引知识库文档
const indexKnowledgeBase = ai.defineFlow(
{ name: 'indexKB', inputSchema: z.array(z.string()) },
async (texts) => {
await ai.index({
indexer: devLocalVectorstoreIndexer('kb'),
docs: texts.map(text => ({ content: [{ text }] })),
});
}
);
// 使用RAG回答问题
export const answerFlow = ai.defineFlow(
{
name: 'answerFlow',
inputSchema: z.object({ question: z.string() }),
outputSchema: z.object({ answer: z.string(), sources: z.number() }),
},
async ({ question }) => {
const docs = await ai.retrieve({
retriever: devLocalVectorstoreRetriever('kb'),
query: question,
options: { k: 5 },
});
const { text } = await ai.generate({
system: '仅使用提供的上下文回答问题。如果不确定,请直接说明。',
prompt: question,
docs,
});
return { answer: text, sources: docs.length };
}
);import { googleAI } from '@genkit-ai/google-genai';
import { openAI } from 'genkitx-openai';
import { genkit, z } from 'genkit';
const ai = genkit({ plugins: [googleAI(), openAI()] });
export const compareModelsFlow = ai.defineFlow(
{
name: 'compareModelsFlow',
inputSchema: z.object({ prompt: z.string() }),
outputSchema: z.object({ gemini: z.string(), gpt4o: z.string() }),
},
async ({ prompt }) => {
const [geminiResult, gptResult] = await Promise.all([
ai.generate({ model: googleAI.model('gemini-2.5-flash'), prompt }),
ai.generate({ model: 'openai/gpt-4o', prompt }),
]);
return {
gemini: geminiResult.text,
gpt4o: gptResult.text,
};
}
);