從 0.9 遷移至 1.0

Genkit 1.0 推出了許多功能強化項目,可改善整體功能;此外,也包含一些破壞性變更。如果您一直使用 Genkit 0.9 開發應用程式,升級至最新版 Genkit 時,您必須更新應用程式程式碼。本指南將概略說明最重要的變更,並說明如何順利遷移現有應用程式。

Beta 版 API

我們將推出不穩定的 Beta 版 API 管道,並在持續改良的同時,將會話、聊天和 Genkit 用戶端 API 保留在 Beta 版。具體來說,以下函式目前位於 beta 命名空間:

  • ai.chat
  • ai.createSession
  • ai.loadSession
  • ai.currentSession
  • ai.defineFormat
  • ai.defineInterrupt

舊版:

import { genkit } from 'genkit';
const ai = genkit({...})
const session = ai.createSession({ ... })

新功能:

import { genkit } from 'genkit/beta';
const ai = genkit({...})
const session = ai.createSession({ ... })

舊版:

import { runFlow, streamFlow } from 'genkit/client';

新功能:

import { runFlow, streamFlow } from 'genkit/beta/client';

隆重推出全新 @genkit-ai/express 套件

這個新套件包含實用工具,可讓您更輕鬆地使用 Genkit 建構 Express.js 伺服器。如需進一步瞭解相關資訊,請參閱這個頁面

startFlowServer 已從 Genkit 物件的一部分移至這個新的 @genkit-ai/express 套件;如要使用 startFlowServer,您必須更新匯入項目。

舊版:

const ai = genkit({ ... });
ai.startFlowServer({
  flows: [myFlow1, myFlow2],
});

新功能:

import { startFlowServer } from '@genkit-ai/express';
startFlowServer({
  flows: [myFlow1, myFlow2],
});

流程的異動

1.0 版的流程有幾項變更:

  • ai.defineStreamingFlow 已整合至 ai.defineFlow
  • onFlow 已由 onCallGenkit 取代。
  • run 已移至 ai.run
  • 使用驗證機制時,系統會進行一些變更。

自訂追蹤區塊的 run 函式已移至 genkit 物件的一部分;請改用 ai.run 叫用該函式。

舊版:

ai.defineFlow({name: 'banana'}, async (input) => {
  const step = await run('myCode', async () => {
    return 'something'
  });
})

新功能:

ai.defineFlow({name: 'banana'}, async (input) => {
  const step = await ai.run('myCode', async () => {
    return 'something'
  });
})

ai.defineStreamingFlow 已遭移除,請改用 ai.defineFlow。此外,streamingCallback 已移至流程函式的第二個引數內的欄位,現在稱為 sendChunk

舊版:

const flow = ai.defineStreamingFlow({name: 'banana'}, async (input, streamingCallback) => {
  streamingCallback({chunk: 1});
})

const {stream} = await flow()
for await (const chunk of stream) {
  // ...
}

新功能:

const flow = ai.defineFlow({name: 'banana'}, async (input, {context, sendChunk}) => {
  sendChunk({chunk: 1});
})

const {stream, output} = flow.stream(input);
for await (const chunk of stream) {
  // ...
}

FlowAuth 驗證現在稱為 context。您可以將驗證權當做情境中的欄位來存取:

舊版:

ai.defineFlow({name: 'banana'}, async (input) => {
  const auth = getFlowAuth();
  // ...
})

新功能:

ai.defineFlow({name: 'banana'}, async (input, { context }) => {
  const auth = context.auth;
})

onFlow 已移至 firebase-functions/https 套件,並重新命名為 onCallGenkit。以下程式碼片段示範如何使用。

import { onFlow } from "@genkit-ai/firebase/functions";

export const generatePoem = onFlow(
  ai,
  {
    name: "jokeTeller",
    inputSchema: z.string().nullable(),
    outputSchema: z.string(),
    streamSchema: z.string(),
  },
  async (type, streamingCallback) => {
    const { stream, response } = await ai.generateStream(
      `Tell me a longish ${type ?? "dad"} joke.`
    );
    for await (const chunk of stream) {
      streamingCallback(chunk.text);
    }
    return (await response).text;
  }
);

新功能:

import { onCallGenkit } from "firebase-functions/https";
import { defineSecret } from "firebase-functions/params";
import { genkit, z } from "genkit";

const apiKey = defineSecret("GOOGLE_GENAI_API_KEY");

const ai = genkit({
  plugins: [googleAI()],
  model: gemini15Flash,
});

export const jokeTeller = ai.defineFlow(
  {
    name: "jokeTeller",
    inputSchema: z.string().nullable(),
    outputSchema: z.string(),
    streamSchema: z.string(),
  },
  async (type, { sendChunk }) => {
    const { stream, response } = ai.generateStream(
      `Tell me a longish ${type ?? "dad"} joke.`
    );
    for await (const chunk of stream) {
      sendChunk(chunk.text);
    }
    return (await response).text;
  }
);

export const tellJoke = onCallGenkit({ secrets: [apiKey] }, jokeTeller);

defineFlow 已移除驗證政策。處理驗證政策現在取決於伺服器。

舊版:

export const simpleFlow = ai.defineFlow(
  {
    name: 'simpleFlow',
    authPolicy: (auth, input) => {
      // auth policy
    },
  },
  async (input) => {
    // Flow logic here...
  }
);

以下程式碼片段顯示在 Express 中處理驗證的範例。

新功能:

import { UserFacingError } from 'genkit';
import { ContextProvider, RequestData } from 'genkit/context';
import { expressHandler, startFlowServer } from '@genkit-ai/express';

const context: ContextProvider<Context> = (req: RequestData) => {
  return {
    auth: parseAuthToken(req.headers['authorization']),
  };
};

export const simpleFlow = ai.defineFlow(
  {
    name: 'simpleFlow',
  },
  async (input, { context }) => {
    if (!context.auth) {
      throw new UserFacingError("UNAUTHORIZED", "Authorization required.");
    }
    if (input.uid !== context.auth.uid) {
      throw new UserFacingError("UNAUTHORIZED", "You may only summarize your own profile data.");
    }
    // Flow logic here...
  }
);

const app = express();
app.use(express.json());
app.post(
  '/simpleFlow',
  expressHandler(simpleFlow, { context })
);
app.listen(8080);

// or

startFlowServer(
  flows: [withContextProvider(simpleFlow, context)],
  port: 8080
);

詳情請參閱驗證說明文件

以下程式碼片段顯示在 Firebase 的 Cloud Functions 中處理驗證的範例:

import { genkit } from 'genkit';
import { onCallGenkit } from 'firebase-functions/https';

const ai = genkit({ ... });;

const simpleFlow = ai.defineFlow({
  name: 'simpleFlow',
}, async (input) => {
  // Flow logic here...
});

export const selfSummary = onCallGenkit({
  authPolicy: (auth, data) => auth?.token?.['email_verified'] && auth?.token?.['admin'],
}, simpleFlow);

提示

我們對提示進行了幾項變更和改善。

您可以為提示和系統訊息分別定義範本:

const hello = ai.definePrompt({
  name: 'hello',
  system: 'talk like a pirate.',
  prompt: 'hello {{ name }}',
  input: {
    schema: z.object({
      name: z.string()
    })
  }
});
const { text } = await hello({name: 'Genkit'});

或者,您也可以在訊息欄位中定義多則訊息提示:

const hello = ai.definePrompt({
  name: 'hello',
  messages: '{{ role "system" }} talk like a pirate. {{ role "user" }} hello {{ name }}',
  input: {
    schema: z.object({
      name: z.string()
    })
  }
});

您可以使用函式,而非提示範本:

ai.definePrompt({
  name: 'hello',
  prompt: async (input, { context }) => {
    return `hello ${input.name}`
  },
  input: {
    schema: z.object({
      name: z.string()
    })
  }
});

您可以在提示中存取內容 (包括驗證資訊):

const hello = ai.definePrompt({
  name: 'hello',
  messages: 'hello {{ @auth.email }}',
});

串流函式不需要 await

舊版:

const { stream, response } = await ai.generateStream(`hi`);
const { stream, output } = await myflow.stream(`hi`);

新功能:

const { stream, response } = ai.generateStream(`hi`);
const { stream, output } = myflow.stream(`hi`);

嵌入有新的傳回類型

我們已新增對多模態嵌入的支援。Embed 會傳回嵌入物件陣列,而非單一嵌入向量,每個嵌入物件都包含嵌入向量和中繼資料。

舊版:

const response = await ai.embed({embedder, content, options});  // returns number[]

新功能:

const response = await ai.embed({embedder, content, options}); // returns Embedding[]
const firstEmbeddingVector = response[0].embedding;  // is number[]