Skip to content

Instantly share code, notes, and snippets.

View Finndersen's full-sized avatar

Finn Andersen Finndersen

View GitHub Profile
@Finndersen
Finndersen / pydanticai_graph_with_edges.py
Last active January 29, 2025 15:59
Example code for how the PydanticAI graph framework could be adapted to use Edges for flexibility
# NODES
@dataclass
class UserPromptNode(BaseNode[...]):
"""Get the system & user prompt parts for initial message, or user prompt message if there is chat history"""
user_prompt: str
system_prompts: tuple[str, ...]
...
def run(tx: GraphRunContext[...]) -> _messages.ModelRequest:
@Finndersen
Finndersen / sqlalchemy_to_pydantic.py
Created January 24, 2025 18:49
Helper utility to construct a Pydantic Model from a SQLAlchemy model. Based on https://github.com/wezhai/sqlalchemy-to-pydantic/ with some tweaks
from collections.abc import Container
from pydantic import BaseModel, ConfigDict, create_model
orm_config = ConfigDict(from_attributes=True)
def sqlalchemy_to_pydantic(
db_model: type,
*,
@Finndersen
Finndersen / VectorArray.py
Last active January 17, 2023 17:46
Definition of VectorArray for Pandas Extension Types example
class VectorArray(ExtensionScalarOpsMixin, ExtensionArray):
"""
Custom Extension Array type for an array of Vectors
Needs to define:
- Associated Dtype it is used with
- How to construct array from sequence of scalars
- How data is stored and accessed
- Any custom array methods
"""
@Finndersen
Finndersen / VectorDtype.py
Created December 30, 2022 20:52
VectorDtype definition for Pandas Extension Types example
import numpy as np
import pandas as pd
from pandas.core.dtypes.dtypes import PandasExtensionDtype
from pandas.api.extensions import ExtensionArray, ExtensionScalarOpsMixin, register_extension_dtype
@register_extension_dtype
class VectorDtype(PandasExtensionDtype):
"""
Class to describe the custom Vector data type
"""
@Finndersen
Finndersen / vector.py
Last active January 17, 2023 17:38
Example Coordinate class for Pandas Extension Types article
from functools import total_ordering
from math import sqrt
@total_ordering
class Vector(object):
"""
Simple class to represent a 2D vector with X and Y components.
Could extend with more useful methods etc
"""
def __init__(self, x, y):
@Finndersen
Finndersen / polymorphic_related_queryset.py
Last active August 29, 2023 12:53
PolymorphicRelatedQuerySet which allows select_related() to return polymorphic child models instead of base model