Skip to content
31 changes: 27 additions & 4 deletions packages/genkit/src/genkit/_ai/_aio.py
Original file line number Diff line number Diff line change
Expand Up @@ -715,16 +715,18 @@ def lookup_value(self, *, kind: str, name: str) -> object | None:
def define_value(self, *, kind: str, name: str, value: object) -> None:
"""Store ``value`` under ``kind`` and ``name`` for later ``lookup_value``.

Defining the same kind and name again replaces the value, so a
re-run notebook cell does not fail.

Raises:
ValueError: ``kind`` is one Genkit owns (use ``define_middleware``,
``define_format``, or ``Genkit(model=...)``), ``value`` is None,
or a value is already defined under this kind and name.
``define_format``, or ``Genkit(model=...)``), or ``value`` is None.
"""
if kind in _CORE_VALUE_KINDS:
raise ValueError(f'define_value kind {kind!r} is reserved; use {_CORE_VALUE_KINDS[kind]} instead.')
if value is None:
raise ValueError('define_value value must not be None; lookup_value returns None for "not defined".')
self._registry.register_value(kind, name, value)
self._registry.register_value(kind, name, value, allow_overwrite=True)

# Overload 1: Both input_schema and output_schema typed -> Prompt[InputT, OutputT]
@overload
Expand Down Expand Up @@ -1108,7 +1110,15 @@ def _bind_reflection_socket(host: str, port: int, *, pinned: bool) -> socket.soc
continue
sock.listen(2048)
return sock
raise last or OSError(f'no available port in range {port}-{port + 99}')
if pinned:
raise last or OSError(f'port {port} is not available')
# Each Genkit() with reflection on holds one port; a notebook that
# re-runs `ai = Genkit(...)` exhausts the range.
raise OSError(
f'No free reflection port in {port}-{port + 99}. Each Genkit() instance with the Dev UI '
'reflection server on (GENKIT_ENV=dev) holds one port; reuse one instance instead of '
'creating a new one per cell or request.'
) from last

def _start_reflection_background(self) -> None:
"""Start the Dev UI reflection server in a background daemon thread.
Expand Down Expand Up @@ -1288,6 +1298,19 @@ async def main() -> None:
# stays up for the Dev UI until you press Ctrl+C.
```
"""
try:
asyncio.get_running_loop()
except RuntimeError:
pass
else:
# Jupyter, IPython, and async frameworks already run a loop, and
# asyncio.run would fail with a raw RuntimeError plus an
# unawaited-coroutine warning.
coro.close()
raise RuntimeError(
'ai.run_main() cannot be called from a running event loop (Jupyter, IPython, or an async '
'framework). Use `await main()` instead.'
)
if not self._reflection_config.enabled:
return run_loop(coro)

Expand Down
85 changes: 75 additions & 10 deletions packages/genkit/src/genkit/_ai/_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import signal
import sys
import threading
from collections.abc import Callable
from collections.abc import Callable, Sequence
from datetime import datetime
from pathlib import Path
from types import FrameType, TracebackType
Expand All @@ -36,6 +36,37 @@
logger = get_logger(__name__)

DEFAULT_RUNTIME_DIR_NAME = '.genkit/runtimes'

# Same list as the CLI's ``findProjectRoot`` (genkit-tools/common/src/utils/utils.ts).
# The CLI reads ``.genkit/runtimes`` under that root, so the runtime file has to
# land there too.
PROJECT_ROOT_MARKERS: tuple[str, ...] = (
'package.json',
'go.mod',
'pyproject.toml',
'requirements.txt',
'pom.xml',
'build.gradle',
'build.gradle.kts',
'pubspec.yaml',
)


def find_project_root(start: Path | None = None) -> Path:
"""Nearest ancestor of ``start`` (default cwd) holding a project marker.

Mirrors the CLI: walk up from cwd, stop before the filesystem root, and
fall back to cwd when no marker is found.
"""
cwd = Path(start) if start is not None else Path.cwd()
current = cwd
while current != Path(current.anchor):
if any((current / marker).exists() for marker in PROJECT_ROOT_MARKERS):
return current
current = current.parent
return cwd


ACTIVE_CLEANUPS: list[Callable[[], None]] = []
# RLock so a SIGINT/SIGTERM mid-update can re-enter: signal handlers run on the
# main thread, and a plain Lock would deadlock if that thread already holds it.
Expand Down Expand Up @@ -82,9 +113,14 @@ def handle_signal(signum: int, frame: FrameType | None) -> None:
pass


def _remove_file(file_path: Path | None) -> bool:
def _remove_file(file_path: Path | None, created_dirs: Sequence[Path] = ()) -> bool:
"""Synchronously attempts to delete the file.

Args:
file_path: The runtime file to delete.
created_dirs: Directories this process created for the file, innermost
first; each is removed if it is left empty.

Returns:
True if cleanup was successful or file didn't exist, False on error.
"""
Expand All @@ -94,25 +130,43 @@ def _remove_file(file_path: Path | None) -> bool:
try:
if file_path.exists():
file_path.unlink()
_remove_empty_dirs(created_dirs)
return True
except Exception as e:
print(f'Error deleting {file_path}: {e}') # noqa: T201 - atexit handler, logger unavailable
return False


def _register_atexit_cleanup_handler(path_to_remove: Path | None) -> None:
def _remove_empty_dirs(created_dirs: Sequence[Path]) -> None:
"""Drop the runtime directories this process created, if left empty.

Only directories that did not exist on entry are removed. ``genkit start``
creates and watches ``.genkit/runtimes`` before it spawns the app; removing
and recreating that directory leaves the CLI's watcher blind to the next
runtime file. ``rmdir`` only removes an empty directory, so another
runtime's file or the CLI's traces keep them in place.
"""
for directory in created_dirs:
try:
directory.rmdir()
except OSError:
return


def _register_atexit_cleanup_handler(path_to_remove: Path | None, created_dirs: Sequence[Path] = ()) -> None:
"""Defines and registers the synchronous atexit cleanup handler for a path.

Args:
path_to_remove: The path to the file that needs cleanup.
created_dirs: Directories this process created, removed if left empty.
"""
if not path_to_remove:
logger.warning('Cannot register atexit cleanup: runtime file path not set.')
return

def sync_cleanup() -> None:
# TODO(#4335): Neither print nor logger appears to work during atexit.
_ = _remove_file(path_to_remove)
_ = _remove_file(path_to_remove, created_dirs)

logger.debug(f'Registering synchronous atexit cleanup for {path_to_remove}')
_ = atexit.register(sync_cleanup)
Expand Down Expand Up @@ -204,7 +258,8 @@ def __init__(
Args:
spec: The server specification for the reflection server.
runtime_dir: The directory to store the runtime file in.
Defaults to .genkit/runtimes in the current directory.
Defaults to .genkit/runtimes under the project root,
found the same way the CLI finds it.
lazy_write: If True, the runtime file will not be written immediately
on context entry. It must be written manually by calling
write_runtime_file().
Expand All @@ -213,18 +268,25 @@ def __init__(
self.spec: ServerSpec = spec
self._secret: str | None = secret
if runtime_dir is None:
self._runtime_dir: Path = Path(Path.cwd()) / DEFAULT_RUNTIME_DIR_NAME
self._runtime_dir: Path = find_project_root() / DEFAULT_RUNTIME_DIR_NAME
else:
self._runtime_dir = Path(runtime_dir)

self.lazy_write: bool = lazy_write
self._runtime_file_path: Path | None = None
# Runtime directories this manager created, innermost first.
self._created_dirs: list[Path] = []

def _ensure_runtime_dir(self) -> None:
"""Create the runtime directory, remembering which levels were new."""
self._created_dirs = [d for d in (self._runtime_dir, self._runtime_dir.parent) if not d.exists()]
_ = self._runtime_dir.mkdir(parents=True, exist_ok=True)

async def __aenter__(self) -> RuntimeManager:
"""Create the runtime directory and file."""
try:
logger.debug(f'Ensuring runtime directory exists: {self._runtime_dir}')
_ = self._runtime_dir.mkdir(parents=True, exist_ok=True)
self._ensure_runtime_dir()
if not self.lazy_write:
_ = self.write_runtime_file()

Expand Down Expand Up @@ -257,7 +319,7 @@ def __enter__(self) -> RuntimeManager:
"""Synchronous entry point: Create the runtime directory and file."""
try:
logger.debug(f'[sync] Ensuring runtime directory exists: {self._runtime_dir}')
_ = self._runtime_dir.mkdir(parents=True, exist_ok=True)
self._ensure_runtime_dir()
if not self.lazy_write:
_ = self.write_runtime_file()

Expand Down Expand Up @@ -297,7 +359,7 @@ def write_runtime_file(self) -> Path:
return self._runtime_file_path

self._runtime_file_path = _create_and_write_runtime_file(self._runtime_dir, self.spec, self._secret)
_register_atexit_cleanup_handler(self._runtime_file_path)
_register_atexit_cleanup_handler(self._runtime_file_path, self._created_dirs)
with ACTIVE_CLEANUPS_LOCK:
ACTIVE_CLEANUPS.append(self.cleanup)
return self._runtime_file_path
Expand All @@ -310,5 +372,8 @@ def cleanup(self) -> None:

if self._runtime_file_path:
logger.debug(f'Cleaning up runtime file: {self._runtime_file_path}')
_ = _remove_file(self._runtime_file_path)
_ = _remove_file(self._runtime_file_path, self._created_dirs)
self._runtime_file_path = None
else:
# lazy_write: the directory exists but no file was ever written.
_remove_empty_dirs(self._created_dirs)
76 changes: 68 additions & 8 deletions packages/genkit/src/genkit/_core/_logger.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

import logging
import os
import sys
import threading
from collections.abc import Awaitable, Callable
from typing import Protocol, cast
Expand Down Expand Up @@ -81,6 +82,34 @@ def unrecognized_level() -> str | None:
return raw


_DEFAULT_STRUCTLOG_FACTORY: object = (
structlog.get_config().get('logger_factory')
if not structlog.is_configured()
else getattr(getattr(structlog, '_config', None), '_BUILTIN_DEFAULT_LOGGER_FACTORY', None)
)

_stderr_lock = threading.Lock()


class _StderrPrintLogger:
"""structlog ``PrintLogger`` equivalent that resolves ``sys.stderr`` at emit time.

Passing ``file=sys.stderr`` to ``structlog.PrintLoggerFactory`` binds the
stream object once at factory creation, missing later ``sys.stderr`` swaps
from ``pytest`` capture, ``contextlib.redirect_stderr``, or notebooks.
"""

def msg(self, message: object) -> None:
with _stderr_lock:
stream = sys.stderr
if stream is not None:
stream.write(f'{message}\n')
stream.flush()

log = debug = info = warn = warning = msg
fatal = failure = err = error = critical = exception = msg


def _app_chose_level() -> bool:
"""Report whether the application configured structlog with a level of its own."""
if not structlog.is_configured():
Expand All @@ -89,6 +118,13 @@ def _app_chose_level() -> bool:
return structlog.get_config().get('wrapper_class') is not unfiltered


def _app_chose_logger_factory() -> bool:
"""Report whether the application configured structlog with its own logger factory."""
if not structlog.is_configured():
return False
return structlog.get_config().get('logger_factory') is not _DEFAULT_STRUCTLOG_FACTORY


def configure_structlog_level() -> bool:
"""Apply ``GENKIT_LOG`` to structlog unless the application chose a level.

Expand Down Expand Up @@ -228,31 +264,53 @@ class ExportTee:
above, so a quiet terminal can still fill the trace viewer's log panel.
"""

def __init__(self, bound: BindableLogger, attrs: dict[str, object] | None = None) -> None:
def __init__(
self,
bound: BindableLogger,
attrs: dict[str, object] | None = None,
*,
stderr_bound: BindableLogger | None = None,
) -> None:
self._bound = bound
self._stderr_bound = stderr_bound
self._attrs = attrs or {}

def _active_bound(self) -> BindableLogger:
if self._stderr_bound is not None and not _app_chose_logger_factory():
return self._stderr_bound
return self._bound

def bind(self, **new_values: object) -> ExportTee:
return ExportTee(self._bound.bind(**new_values), attrs={**self._attrs, **new_values})
stderr = self._stderr_bound.bind(**new_values) if self._stderr_bound is not None else None
return ExportTee(self._bound.bind(**new_values), attrs={**self._attrs, **new_values}, stderr_bound=stderr)

def unbind(self, *keys: str) -> ExportTee:
kept = {k: v for k, v in self._attrs.items() if k not in keys}
return ExportTee(self._bound.unbind(*keys), attrs=kept)
stderr = self._stderr_bound.unbind(*keys) if self._stderr_bound is not None else None
return ExportTee(self._bound.unbind(*keys), attrs=kept, stderr_bound=stderr)

def try_unbind(self, *keys: str) -> ExportTee:
kept = {k: v for k, v in self._attrs.items() if k not in keys}
return ExportTee(self._bound.try_unbind(*keys), attrs=kept)
stderr = self._stderr_bound.try_unbind(*keys) if self._stderr_bound is not None else None
return ExportTee(self._bound.try_unbind(*keys), attrs=kept, stderr_bound=stderr)

def new(self, **new_values: object) -> ExportTee:
return ExportTee(self._bound.new(**new_values), attrs=dict(new_values))
bound_new = self._bound.new(**new_values)
stderr = (
cast(BindableLogger, structlog.wrap_logger(_StderrPrintLogger())).bind(**new_values)
if self._stderr_bound is not None
else None
)
return ExportTee(bound_new, attrs=dict(new_values), stderr_bound=stderr)

def is_enabled_for(self, level: int) -> bool:
from genkit._core._telemetry._log_exporter import log_export_is_enabled

if level >= logging.DEBUG and log_export_is_enabled():
return True
active = self._active_bound()
for attr in ('is_enabled_for', 'isEnabledFor'):
check = getattr(self._bound, attr, None)
check = getattr(active, attr, None)
if not callable(check):
continue
try:
Expand All @@ -267,7 +325,7 @@ def _emit(self, level: int, event: str, args: tuple[object, ...], kw: dict[str,
emit_log(level=level, event=_interpolate_event(event, args), attrs={**self._attrs, **kw})

def __getattr__(self, name: str) -> object:
target = getattr(self._bound, name)
target = getattr(self._active_bound(), name)
if name == 'log' and callable(target):

def emit_log(level: int, event: str, *args: object, **kw: object) -> object:
Expand Down Expand Up @@ -371,7 +429,9 @@ async def lookup_menu(restaurant_id: str) -> int:
return 12
```
"""
return cast(GenkitLogger, ExportTee(structlog.get_logger(name)))
app_bound = structlog.get_logger(name) if name is not None else structlog.get_logger()
stderr_bound = cast(BindableLogger, structlog.wrap_logger(_StderrPrintLogger()))
return cast(GenkitLogger, ExportTee(app_bound, stderr_bound=stderr_bound))


def is_debug_enabled(logger: GenkitLogger) -> bool:
Expand Down
Loading
Loading