Skip to content
4 changes: 2 additions & 2 deletions docs/migrating-from-0.12.md
Original file line number Diff line number Diff line change
Expand Up @@ -383,11 +383,11 @@ ai = Genkit(plugins=[OpenAI(api_key=os.environ['OPENAI_API_KEY'])])
await ai.generate(model=m, prompt=p, context={'secrets': {'api_key': user_key}})
```

Vertex AI Model Garden authenticates with ADC and rejects a per-request key. `ai.embed()` takes no `context`, so embedders always use the plugin's key.
Vertex AI Model Garden authenticates with ADC and rejects a per-request key. `ai.embed(..., context={'secrets': {'api_key': user_key}})` passes the same per-request key to embedder handlers via `EmbedContext`.

## Flow contexts

`ActionRunContext` is replaced by a typed context for each kind of action. The chunk type moves from `@ai.flow(chunk_type=...)` into the context's type parameter.
`ActionRunContext` is replaced by `ActionContext` (in `genkit.plugin_api`) and a typed context for each kind of action (`FlowContext`, `ToolContext`, `ModelContext`, `EmbedContext`, `AgentContext`). The chunk type moves from `@ai.flow(chunk_type=...)` into the context's type parameter.

**Old:**

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,8 @@
from pydantic import BaseModel

import genkit_google_genai._constants as const
from genkit import FlowContext, GenkitError, ModelResponse, Operation
from genkit.embedder import Embedder, EmbedderRef, EmbedRequest, EmbedResponse
from genkit import GenkitError, ModelResponse, Operation
from genkit.embedder import EmbedContext, Embedder, EmbedderRef, EmbedRequest, EmbedResponse
from genkit.model import (
BackgroundModel,
Model,
Expand Down Expand Up @@ -365,7 +365,7 @@ def _create_embedder_action(
is_vertex=(plugin_name == VERTEXAI_PLUGIN_NAME),
)

async def _run(request: EmbedRequest[EmbeddingConfig], ctx: FlowContext[Any]) -> EmbedResponse:
async def _run(request: EmbedRequest[EmbeddingConfig], ctx: EmbedContext) -> EmbedResponse:
embedder_client = GoogleEmbedder(
version=name,
client=client_getter(ctx.context),
Expand Down
9 changes: 6 additions & 3 deletions packages/genkit-ollama/src/genkit_ollama/_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@

from genkit import GenkitError, ModelResponse, get_logger
from genkit.embedder import (
EmbedContext,
Embedder,
EmbedderInfo,
EmbedderSupports,
Expand Down Expand Up @@ -472,10 +473,12 @@ def _create_embedder_action(self, name: str) -> Action:

base_url = self.base_url

async def _run(request: EmbedRequest) -> EmbedResponse:
async def _run(request: EmbedRequest, ctx: EmbedContext | None = None) -> EmbedResponse:
api_key = context_api_key(ctx.context) if ctx is not None else None
# Embedding requests never fetch media, so the whole SDK call is wrapped.
async with wrap_connection_errors(base_url):
return await embedder.embed(request)
async with self._client_for_request(api_key=api_key) as client:
async with wrap_connection_errors(base_url):
return await embedder.embed(request, client=client)

return Embedder(
ollama_name(name),
Expand Down
5 changes: 3 additions & 2 deletions packages/genkit-openai/src/genkit_openai/_openai_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,9 @@
from openai.types import Model as OpenAIModelEntry
from pydantic import BaseModel

from genkit import Embedding, FlowContext, GenkitError, ModelResponse
from genkit import Embedding, GenkitError, ModelResponse
from genkit.embedder import (
EmbedContext,
Embedder,
EmbedderInfo,
EmbedderSupports,
Expand Down Expand Up @@ -566,7 +567,7 @@ def _create_embedder_action(self, name: str) -> Action:
},
)

async def embed_fn(request: EmbedRequest, ctx: FlowContext[Any]) -> EmbedResponse:
async def embed_fn(request: EmbedRequest, ctx: EmbedContext) -> EmbedResponse:
"""Embedder function that calls OpenAI embeddings API."""
# Extract text from document content
texts = []
Expand Down
8 changes: 4 additions & 4 deletions packages/genkit-openai/tests/openai_plugin_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
from openai.types import Model
from openai.types.chat import ChatCompletion

from genkit import Document, FlowContext, Genkit, GenkitError, Message, ModelResponse, Part, Role
from genkit.embedder import EmbedRequest, EmbedResponse
from genkit import Document, Genkit, GenkitError, Message, ModelResponse, Part, Role
from genkit.embedder import EmbedContext, EmbedRequest, EmbedResponse
from genkit.model import ConstrainedSupport, ModelSupports
from genkit.plugin_api import Action, ActionKind, loop_local_client

Expand Down Expand Up @@ -330,7 +330,7 @@ def _embedding_client(embedding: list[float] | None = None) -> MagicMock:
async def _run_embedder(client: MagicMock, options: dict[str, Any] | None = None) -> EmbedResponse:
"""Run the embedder action function against a stub client."""
action = _plugin_with(client)._create_embedder_action('text-embedding-3-small')
return await action._fn(EmbedRequest(input=[Document.from_text('hello')], options=options or {}), FlowContext())
return await action._fn(EmbedRequest(input=[Document.from_text('hello')], options=options or {}), EmbedContext())


@pytest.mark.asyncio
Expand Down Expand Up @@ -625,6 +625,6 @@ def resolve(context: dict[str, Any]) -> MagicMock:
plugin._embed_client = resolve # type: ignore[method-assign]
action = plugin._create_embedder_action('text-embedding-3-small')
tenant = {'secrets': {'api_key': 'sk-tenant'}}
await action._fn(EmbedRequest(input=[Document.from_text('hello')], options={}), FlowContext(context=tenant))
await action._fn(EmbedRequest(input=[Document.from_text('hello')], options={}), EmbedContext(context=tenant))

assert seen == [tenant]
4 changes: 2 additions & 2 deletions packages/genkit/src/genkit/_ai/_agents/_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@
mark_failure_logged,
)
from genkit._ai._json_patch import diff_json
from genkit._core._action import ActionRunContext, get_current_context
from genkit._core._action import ActionContext, get_current_context
from genkit._core._channel import CloseableQueue, QueueShutDown
from genkit._core._compat import await_unchained, cancelling
from genkit._core._error import (
Expand Down Expand Up @@ -277,7 +277,7 @@ async def update_custom(self, fn: Callable[[StateT | None], StateT]) -> None:
await self.session.update_custom(fn)


class AgentContext(ActionRunContext[AgentStreamChunk]):
class AgentContext(ActionContext[AgentStreamChunk]):
"""Execution context passed to a custom agent function.

Provides ``ctx.send_chunk(chunk)`` for streaming :class:`AgentStreamChunk`
Expand Down
18 changes: 14 additions & 4 deletions packages/genkit/src/genkit/_ai/_embedding.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
from pydantic.alias_generators import to_camel
from typing_extensions import Never, TypeVar

from genkit._core._action import Action, ActionKind, FlowContext, get_func_description, with_request_annotation
from genkit._core._action import Action, ActionKind, EmbedContext, get_func_description, with_request_annotation
from genkit._core._model import EmbedRequest, check_ref_config, check_ref_info
from genkit._core._registry import Registry
from genkit._core._schema import custom_options_schema, fixed_json_schema
Expand Down Expand Up @@ -85,7 +85,7 @@ def __post_init__(self) -> None:

EmbedderFn = (
Callable[[EmbedRequest[Any]], Awaitable[EmbedResponse]]
| Callable[[EmbedRequest[Any], FlowContext[Any]], Awaitable[EmbedResponse]]
| Callable[[EmbedRequest[Any], EmbedContext], Awaitable[EmbedResponse]]
)


Expand All @@ -97,7 +97,8 @@ class Embedder(Action[EmbedRequest, EmbedResponse, Never]):

The options class comes from ``config_schema`` or the fn's
``EmbedRequest[Cfg]`` annotation; given both, they must be the same class.
An unannotated fn still gets an ``EmbedRequest``.
An unannotated fn still gets an ``EmbedRequest``, typed by ``config_schema``
when that is a Pydantic class.
"""

def __init__(
Expand Down Expand Up @@ -142,10 +143,19 @@ def __init__(
embedder_meta: dict[str, object] = metadata.copy() if metadata else {}
embedder_meta['embedder'] = embedder_info

# An unannotated request gets EmbedRequest[Cfg] when config_schema is a
# Pydantic class, so options arrive as Cfg on every call path (ai.embed,
# Dev UI, CLI); an explicit ``request: EmbedRequest`` annotation keeps
# dict options. Built at runtime, so checkers can't read
# EmbedRequest[options_class] as a type.
from genkit._ai._model import python_config_schema # noqa: PLC0415

options_class = python_config_schema(config_schema)
request_type = cast(Any, EmbedRequest)[options_class] if options_class is not None else EmbedRequest
Comment thread
huangjeff5 marked this conversation as resolved.
Resolved
super().__init__(
kind=ActionKind.EMBEDDER,
name=name,
fn=with_request_annotation(fn, EmbedRequest, kind=ActionKind.EMBEDDER),
fn=with_request_annotation(fn, request_type, kind=ActionKind.EMBEDDER),
Comment thread
huangjeff5 marked this conversation as resolved.
Resolved
metadata=embedder_meta,
description=get_func_description(fn, description),
config_schema=config_schema,
Expand Down
4 changes: 2 additions & 2 deletions packages/genkit/src/genkit/_ai/_generate.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,8 +62,8 @@
from genkit._core._action import (
GENKIT_DYNAMIC_ACTION_PROVIDER_ATTR,
Action,
ActionContext,
ActionKind,
ActionRunContext,
_action_context, # pyright: ignore[reportPrivateUsage]
create_action_key,
get_current_context,
Expand Down Expand Up @@ -859,7 +859,7 @@ def define_generate_action(ai: _aio.Genkit) -> None:

async def generate_action_fn(
input: GenerateActionOptions,
ctx: ActionRunContext,
ctx: ActionContext,
) -> ModelResponse:
on_chunk = cast(Callable[[ModelResponseChunk], None], ctx.streaming_callback) if ctx.is_streaming else None
response = await run_generate(
Expand Down
Loading
Loading