firebase / genkit

An open source framework for building AI-powered apps with familiar code-centric patterns. Genkit makes it easy to integrate, test, and deploy sophisticated AI features to Firebase or Google Cloud.
Apache License 2.0
607 stars 74 forks source link

[JS] Auth is required at Flow #336

Closed pablosalazar7 closed 3 months ago

pablosalazar7 commented 3 months ago

Describe the bug When cloud function try to runFlow(), im getting this error -> Unhandled error Error: Auth is required at Flow

To Reproduce

  1. initialize genkit with firebase cloud functions ($ firebase init genkit)

Files in project :

index.ts

export const fn0 = functions.https.onCall(async (data, context) => {
  return (await import('./fn/fn0')).default(data, context)
})

fn0.ts

initializeApp()
configureGenkit({
  plugins: [
    firebase(),
    vertexAI({ projectId: "", location: '' }),
  ],
});
export default async (
  data: any,
  context: https.CallableContext
) => {
  const genAiFlow = await runFlow(flow0, data)
  return genAiFlow
}

flow0.ts

const flow0 = onFlow({
  name: "flow0",
  inputSchema: z.string()),
  authPolicy: firebaseAuth((user, input) => {              //<-----ERROR HERE
    if (user.uid === undefined) {
       throw new Error("Verify user to run flow");
    }
  }),
}, async (input) => {
  const prompt = `${input}`

  await generate({
    model: gemini15ProPreview,
    prompt: prompt,
    config: { temperature: 1 },
  })
    .then((llmResponse) => {
      return llmResponse
    })
    .catch((err) => {
      return false
    })
});

frontEnd

const callCFN = httpsCallable(fnsInstance, 'fn0');
  await callCFN({ ...values })
    .then((res: any) => {
      return true
    })
    .catch(error => {
      return false
    })

Additional context Works well when use Genkit Developer UI (local), im setting various vertex roles (admin, agent service, agent reasoning, user) in IAM to admin SA, but doesnt work.

pablosalazar7 commented 3 months ago

SOLUTION

in fn0.ts add "withLocalAuthContext: context.auth" (or whatever you need to pass) at runFlow options

initializeApp()
configureGenkit({
  plugins: [
    firebase(),
    vertexAI({ projectId: "", location: '' }),
  ],
});
export default async (
  data: any,
  context: https.CallableContext
) => {
  const genAiFlow = await runFlow(flow0, data,{
    withLocalAuthContext:  context.auth            //<------
})
  return genAiFlow
}