Skip to content

Commit

Permalink
fix(py): Applied pre-commit formatting according to settings (#1892)
Browse files Browse the repository at this point in the history
  • Loading branch information
kirgrim authored Feb 12, 2025
1 parent d3e9408 commit a881e74
Show file tree
Hide file tree
Showing 16 changed files with 170 additions and 123 deletions.
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ go/
pnpm-lock.yaml
public/
py/*
README.md
2 changes: 1 addition & 1 deletion py/bin/sanitize_schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ def visit_ClassDef(self, node: ast.ClassDef) -> ast.ClassDef:

def process_file(filename: str) -> None:
"""Process a Python file to remove model_config from RootModel classes."""
with open(filename, 'r') as f:
with open(filename) as f:
source = f.read()

tree = ast.parse(source)
Expand Down
22 changes: 0 additions & 22 deletions py/captainhook.json
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,6 @@
},
{
"run": "go test go/..."
},
{
"run": "govulncheck -C go ./...",
"conditions": [
{
"run": "CaptainHook::FileChanged.Any",
"options": {
"files": ["go/go.mod", "go.sum", "*.go"]
}
}
]
}
]
},
Expand Down Expand Up @@ -105,17 +94,6 @@
{
"run": "go test go/..."
},
{
"run": "govulncheck -C go ./...",
"conditions": [
{
"run": "CaptainHook::FileChanged.Any",
"options": {
"files": ["go/go.mod", "go.sum", "*.go"]
}
}
]
},
{
"run": "py/.hooks/commit-message-format-pre-push"
}
Expand Down
3 changes: 2 additions & 1 deletion py/packages/genkit/src/genkit/ai/model.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
# Copyright 2025 Google LLC
# SPDX-License-Identifier: Apache-2.0

from typing import Callable
from collections.abc import Callable

from genkit.core.schemas import GenerateRequest, GenerateResponse

ModelFn = Callable[[GenerateRequest], GenerateResponse]
7 changes: 4 additions & 3 deletions py/packages/genkit/src/genkit/ai/prompt.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@
# SPDX-License-Identifier: Apache-2.0


from typing import Callable, Optional, Any
from genkit.core.schemas import GenerateRequest
from collections.abc import Callable
from typing import Any

from genkit.core.schemas import GenerateRequest

PromptFn = Callable[[Optional[Any]], GenerateRequest]
PromptFn = Callable[[Any | None], GenerateRequest]
16 changes: 8 additions & 8 deletions py/packages/genkit/src/genkit/core/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,18 @@
# SPDX-License-Identifier: Apache-2.
import inspect
import json

from typing import Dict, Optional, Callable, Any
from pydantic import ConfigDict, BaseModel, TypeAdapter
from collections.abc import Callable
from typing import Any

from genkit.core.tracing import tracer
from pydantic import BaseModel, ConfigDict, TypeAdapter


class ActionResponse(BaseModel):
model_config = ConfigDict(extra='forbid')

response: Any
traceId: str
trace_id: str


class Action:
Expand All @@ -26,9 +26,9 @@ def __init__(
action_type: str,
name: str,
fn: Callable,
description: Optional[str] = None,
metadata: Optional[Dict[str, Any]] = None,
span_metadata: Optional[Dict[str, str]] = None,
description: str | None = None,
metadata: dict[str, Any] | None = None,
span_metadata: dict[str, str] | None = None,
):
# TODO(Tatsiana Havina): separate a long constructor into methods.
self.type = action_type
Expand Down Expand Up @@ -63,7 +63,7 @@ def fn_to_call(*args, **kwargs):
else:
span.set_attribute('genkit:output', json.dumps(output))

return ActionResponse(response=output, traceId=trace_id)
return ActionResponse(response=output, trace_id=trace_id)

self.fn = fn_to_call
self.description = description
Expand Down
21 changes: 10 additions & 11 deletions py/packages/genkit/src/genkit/core/reflection.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
"""Exposes an API for inspecting and interacting with Genkit in development."""

import json

from http.server import BaseHTTPRequestHandler
from pydantic import BaseModel

from genkit.core.registry import Registry
from pydantic import BaseModel


def make_reflection_server(registry: Registry):
Expand All @@ -20,7 +19,7 @@ class ReflectionServer(BaseHTTPRequestHandler):

ENCODING = 'utf-8'

def do_GET(self):
def do_GET(self) -> None: # noqa: N802
"""Handles GET requests."""
if self.path == '/api/__health':
self.send_response(200)
Expand All @@ -38,8 +37,8 @@ def do_GET(self):
actions[key] = {
'key': key,
'name': action.name,
'inputSchema': action.inputSchema,
'outputSchema': action.outputSchema,
'inputSchema': action.input_schema,
'outputSchema': action.output_schema,
'metadata': action.metadata,
}

Expand All @@ -49,24 +48,24 @@ def do_GET(self):
self.send_response(404)
self.end_headers()

def do_POST(self):
def do_POST(self) -> None: # noqa: N802
"""Handles POST requests."""
if self.path == '/api/notify':
self.send_response(200)
self.end_headers()

elif self.path == '/api/runAction':
content_len = int(self.headers.get('Content-Length'))
content_len = int(self.headers.get('Content-Length') or 0)
post_body = self.rfile.read(content_len)
payload = json.loads(post_body.decode(encoding=self.ENCODING))
print(payload)
action = registry.lookup_by_absolute_name(payload['key'])
if '/flow/' in payload['key']:
input_action = action.inputType.validate_python(
input_action = action.input_type.validate_python(
payload['input']['start']['input']
)
else:
input_action = action.inputType.validate_python(
input_action = action.input_type.validate_python(
payload['input']
)

Expand All @@ -83,7 +82,7 @@ def do_POST(self):
'{"result": '
+ output.response.model_dump_json()
+ ', "traceId": "'
+ output.traceId
+ output.trace_id
+ '"}',
self.ENCODING,
)
Expand All @@ -94,7 +93,7 @@ def do_POST(self):
json.dumps(
{
'result': output.response,
'telemetry': {'traceId': output.traceId},
'telemetry': {'traceId': output.trace_id},
}
),
self.ENCODING,
Expand Down
3 changes: 1 addition & 2 deletions py/packages/genkit/src/genkit/core/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,13 @@

"""The registry is used to store and lookup resources."""

from typing import Dict
from genkit.core.action import Action


class Registry:
"""Stores actions, trace stores, flow state stores, plugins, and schemas."""

actions: Dict[str, Dict[str, Action]] = {}
actions: dict[str, dict[str, Action]] = {}

def register_action(self, action_type: str, name: str, action: Action):
if action_type not in self.actions:
Expand Down
2 changes: 2 additions & 0 deletions py/packages/genkit/src/genkit/core/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@

# DO NOT EDIT: Generated by `generate_schema_types` from `genkit-schemas.json`.
from __future__ import annotations

from enum import Enum
from typing import Any

from pydantic import BaseModel, ConfigDict, Field, RootModel


Expand Down
29 changes: 16 additions & 13 deletions py/packages/genkit/src/genkit/core/tracing.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,17 @@
import json
import os
import sys
from typing import Any, Dict, Sequence
from collections.abc import Sequence
from typing import Any, cast

import requests
from opentelemetry.sdk.trace import TracerProvider
import requests # type: ignore[import-untyped]
from opentelemetry import trace as trace_api
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export import (
SimpleSpanProcessor,
SpanExporter,
SpanExportResult,
SimpleSpanProcessor,
)
from opentelemetry import trace as trace_api
from opentelemetry.sdk.trace import ReadableSpan


class TelemetryServerSpanExporter(SpanExporter):
Expand All @@ -31,12 +31,14 @@ class TelemetryServerSpanExporter(SpanExporter):
def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
for span in spans:
span_data = {'traceId': f'{span.context.trace_id}', 'spans': {}}
span_data['spans'][span.context.span_id] = {
span_data['spans'][span.context.span_id] = { # type: ignore
'spanId': f'{span.context.span_id}',
'traceId': f'{span.context.trace_id}',
'startTime': span.start_time / 1000000,
'endTime': span.end_time / 1000000,
'attributes': convert_attributes(span.attributes),
'attributes': convert_attributes(
attributes=cast(span.attributes, dict), # type: ignore
),
'displayName': span.name,
# "links": span.links,
'spanKind': trace_api.SpanKind(span.kind).name,
Expand All @@ -63,15 +65,16 @@ def export(self, spans: Sequence[ReadableSpan]) -> SpanExportResult:
# })),
# },
}
if not span_data['spans'][span.context.span_id]['parentSpanId']:
del span_data['spans'][span.context.span_id]['parentSpanId']
if not span_data['spans'][span.context.span_id]['parentSpanId']: # type: ignore
del span_data['spans'][span.context.span_id]['parentSpanId'] # type: ignore

if not span.parent:
span_data['displayName'] = span.name
span_data['startTime'] = span.start_time
span_data['endTime'] = span.end_time

# TODO: telemetry server URL must be dynamic, whatever tools notification says
# TODO: telemetry server URL must be dynamic,
# whatever tools notification says
requests.post(
'http://localhost:4033/api/traces',
data=json.dumps(span_data),
Expand All @@ -88,8 +91,8 @@ def force_flush(self, timeout_millis: int = 30000) -> bool:
return True


def convert_attributes(attributes: Dict[str, Any]) -> Dict[str, Any]:
attrs: Dict[str, Any] = {}
def convert_attributes(attributes: dict[str, Any]) -> dict[str, Any]:
attrs: dict[str, Any] = {}
for key in attributes:
attrs[key] = attributes[key]
return attrs
Expand Down
2 changes: 2 additions & 0 deletions py/packages/genkit/src/genkit/veneer/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
# Copyright 2025 Google LLC
# SPDX-License-Identifier: Apache-2.0

from genkit.veneer.veneer import Genkit, Plugin

__all__ = [
'Genkit',
'Plugin',
Expand Down
Loading

0 comments on commit a881e74

Please sign in to comment.