Skip to content

feat(js): typed context#4860

Open
Ehesp wants to merge 2 commits intofirebase:mainfrom
Ehesp:ehesp/js-action-types
Open

feat(js): typed context#4860
Ehesp wants to merge 2 commits intofirebase:mainfrom
Ehesp:ehesp/js-action-types

Conversation

@Ehesp
Copy link
Member

@Ehesp Ehesp commented Feb 27, 2026

Currently when dealing with Context in Genkit, the type returned everywhere is a static ActionContext, which looks like:

interface ActionContext {
    /** Information about the currently authenticated user if provided. */
    auth?: Record<string, any>;
    [additionalContext: string]: any;
}

When providing context within Genkit, e.g. within flows, you lose all type-safety:

const flow = ai.defineFlow(..., 
  async (input, { context }) => {
    context.hello('world');
  }
);

flow(..., {
  context: {
    hello: (value: string) => console.log(value),
  }
});

Here, context.hello is an any type. This means you end up having to write your own definitions, and casting context:

const flow = ai.defineFlow(..., 
  async (input, { context }) => {
    const ctx = context as unknown as { hello: (value: string) => void };
    ctx.hello('world');
  }
);

This then doesn't scale, as context is inherited everywhere, and it becomes a bit PITA to type, resulting in bad DX.

This PR enables typed and inferred context typing:

Inferred:

const ai = genkit({
  context: {
    hello: (name: string) => `Hello, ${name}!`,
  },
});

ai.defineFlow(..., 
  // context.hello is typed!
  async (input, { context }) => context.hello(input)
);

Declared:

type MyContext = {
  hello: (name: string) => void;
}

const ai = genkit<MyContext>({
  context: {
    hello: (name) => `Hello, ${name}!`,
  },
});

ai.defineFlow(..., 
  // context = MyContext & ActionContext
  async (input, { context }) => context.hello(input)
);

Additionally, context returned from actions is currently typed as ActionContext | undefined, which caused more issues having to do context?.something. However looking at the code, context is always defined, even if the result is an empty object:

              context: {
                ...actionFn.__registry?.context,
                ...(options?.context ?? getContext()),
              },

So this PR also removes the | undefined type (happy to be proved wrong here!). Note, I don't think this is a breaking change.

Because this PR allows typed context, I'd of ideally liked to remove the [additionalContext: string]: any; within ActionContext:

interface ActionContext {
    /** Information about the currently authenticated user if provided. */
    auth?: Record<string, any>;
-    [additionalContext: string]: any;
}

However, technically I think this would end up being a breaking change since users relying on the any would all of a sudden get type errors.

Checklist (if applicable):

@github-actions github-actions bot added docs Improvements or additions to documentation js config labels Feb 27, 2026
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the developer experience in Genkit by introducing robust type safety for application-specific context within flows and tools. By allowing developers to define and infer custom context types, it eliminates the need for manual type casting and reduces potential runtime errors, making Genkit applications more predictable and easier to maintain. The changes also clarify that context is always available, streamlining its usage.

Highlights

  • Typed Context Implementation: Introduced a generic type parameter 'C' across Genkit's core interfaces and classes (e.g., Genkit, ActionFnArg, FlowFn, ToolFn) to enable strong typing for custom application context within flows and tools.
  • Improved Developer Experience: Updated context parameters in flow and tool definitions to automatically infer or accept declared custom types, eliminating the need for manual type casting and enhancing type safety and predictability.
  • Context Always Defined: Refined the 'context' property within 'ActionFnArg' to be non-optional ('context: C & ActionContext'), clarifying that context is always provided during action execution, even if empty.
  • New Test Application: Added a new test application ('js/testapps/typed-context') to provide a practical demonstration and validation of the new typed context functionality.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • js/ai/src/tool.ts
    • Removed direct import of 'ActionContext' as it's now handled via generic types.
    • Updated 'ToolFnOptions' to accept a generic context type 'C' and extend 'ActionFnArg<never, C>'.
    • Modified type signatures for 'ToolFn', 'MultipartToolFn', 'defineTool', 'tool', 'basicTool', 'basicToolV2', 'multipartTool', and 'dynamicTool' to incorporate the generic context type 'C'.
    • Added type assertions for context parameters in tool execution functions.
  • js/core/src/action.ts
    • Updated 'ActionFnArg' interface to accept a generic context type 'C'.
    • Changed the 'context' property within 'ActionFnArg' from optional ('context?: ActionContext') to required ('context: C & ActionContext'), merging custom context with the base 'ActionContext'.
  • js/core/src/context.ts
    • Corrected a typo in the JSDoc comment for 'ActionContext'.
  • js/core/src/flow.ts
    • Imported 'ActionContext' for use in type definitions.
    • Updated 'FlowSideChannel' interface to accept a generic context type 'C' and extend 'ActionFnArg<S, C>'.
    • Modified type signatures for 'FlowFn', 'flow', 'defineFlow', and 'flowAction' to incorporate the generic context type 'C'.
    • Added type assertions for 'FlowSideChannel' context assignments.
  • js/genkit/src/genkit.ts
    • Updated 'GenkitOptions' interface to accept a generic context type 'C'.
    • Made the 'Genkit' class generic over 'C'.
    • Modified the constructor, 'defineFlow', 'defineTool', 'dynamicTool', 'defineModel', 'generate', 'generateStream', and 'currentContext' methods to use and propagate the generic context type 'C'.
    • Added JSDoc comments to explain the new generic context type parameter for better documentation.
  • js/pnpm-lock.yaml
    • Added new dependency entries for the 'testapps/typed-context' project.
  • js/testapps/typed-context/README.md
    • Added a new README file describing the typed context test application, its features, setup, and testing instructions.
  • js/testapps/typed-context/package.json
    • Added a new 'package.json' file for the 'typed-context' test application, including scripts and dependencies.
  • js/testapps/typed-context/src/index.ts
    • Added a new TypeScript source file demonstrating the definition and usage of typed context with 'genkit()', flows, and tools.
  • js/testapps/typed-context/tsconfig.json
    • Added a new TypeScript configuration file for the 'typed-context' test application.
Activity
  • No human activity (comments, reviews, etc.) has been recorded for this pull request yet.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request is a great improvement for Genkit's developer experience, introducing type-safety for context objects in flows and tools. The changes are well-implemented across the core, AI, and Genkit packages, enabling both inferred and declared context typing. The removal of | undefined from the context type is also a welcome change that simplifies usage. I've found a couple of minor issues: one is a redundant type cast that can be removed, and the other is an incorrect README file for the new test application. Overall, this is a solid feature addition.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

config docs Improvements or additions to documentation js

Projects

Status: No status

Development

Successfully merging this pull request may close these issues.

1 participant