0.9에서 1.0으로 이전

Genkit 1.0에는 전반적인 기능을 개선하는 여러 기능 개선사항이 도입되었습니다. 또한 몇 가지 중대한 변경사항도 있습니다. Genkit 0.9로 애플리케이션을 개발한 경우 최신 버전의 Genkit으로 업그레이드할 때 애플리케이션 코드를 업데이트해야 합니다. 이 가이드에서는 가장 중요한 변경사항을 간략히 설명하고 기존 애플리케이션을 원활하게 이전하는 방법을 설명합니다.

베타 API

Google은 불안정한 베타 API 채널을 도입하고 세션, 채팅, Genkit 클라이언트 API를 계속해서 개선하는 동안 베타 버전으로 두고 있습니다. 구체적으로 현재 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.defineStreamingFlowai.defineFlow로 통합되었습니다.
  • onFlowonCallGenkit로 대체되었습니다.
  • runai.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 인증이 이제 컨텍스트라고 합니다. 컨텍스트 내의 필드로 auth에 액세스할 수 있습니다.

이전:

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

신규:

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

onFlowfirebase-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'});

또는 messages 필드에서 멀티메시지 프롬프트를 정의할 수 있습니다.

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[]