code stringlengths 66 870k | docstring stringlengths 19 26.7k | func_name stringlengths 1 138 | language stringclasses 1
value | repo stringlengths 7 68 | path stringlengths 5 324 | url stringlengths 46 389 | license stringclasses 7
values |
|---|---|---|---|---|---|---|---|
def test_defaults_basic_annotations() -> None:
"""Ensure python types resolve to largest polars type."""
# base types
assert DtypeResolver(str).default_polars_dtype() == pl.String
assert DtypeResolver(int).default_polars_dtype() == pl.Int64
assert DtypeResolver(float).default_polars_dtype() == pl.Fl... | Ensure python types resolve to largest polars type. | test_defaults_basic_annotations | python | JakobGM/patito | tests/test_dtypes.py | https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py | MIT |
def test_defaults_nested_annotations() -> None:
"""Ensure python nested types fallback to largest nested polars type."""
assert DtypeResolver(list).default_polars_dtype() is None # needs inner annotation
assert DtypeResolver(list[str]).default_polars_dtype() == pl.List(pl.String)
assert DtypeResolver(... | Ensure python nested types fallback to largest nested polars type. | test_defaults_nested_annotations | python | JakobGM/patito | tests/test_dtypes.py | https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py | MIT |
def test_annotation_validation() -> None:
"""Check that python types are resolveable."""
validate_annotation(int) # no issue
validate_annotation(Optional[int])
with pytest.raises(ValueError, match="Valid dtypes are:"):
validate_annotation(Union[int, float])
# Unions are unsupported as act... | Check that python types are resolveable. | test_annotation_validation | python | JakobGM/patito | tests/test_dtypes.py | https://github.com/JakobGM/patito/blob/master/tests/test_dtypes.py | MIT |
def test_generation_of_unique_data() -> None:
"""Example data generators should be able to generate unique data."""
class UniqueModel(pt.Model):
bool_column: bool
string_column: str = pt.Field(unique=True)
int_column: int = pt.Field(unique=True)
float_column: int = pt.Field(uniq... | Example data generators should be able to generate unique data. | test_generation_of_unique_data | python | JakobGM/patito | tests/test_dummy_data.py | https://github.com/JakobGM/patito/blob/master/tests/test_dummy_data.py | MIT |
def test_enum_field_example_values() -> None:
"""It should produce correct example values for enums."""
class DefaultEnumModel(pt.Model):
row_number: int
# Here the first value will be used as the example value
enum_field: Literal["a", "b", "c"]
# Here the default value will be ... | It should produce correct example values for enums. | test_enum_field_example_values | python | JakobGM/patito | tests/test_dummy_data.py | https://github.com/JakobGM/patito/blob/master/tests/test_dummy_data.py | MIT |
def test_nested_models() -> None:
"""It should be possible to create nested models."""
class NestedModel(pt.Model):
nested_field: int
class ParentModel1(pt.Model):
parent_field: int
nested_model: NestedModel
example_model = ParentModel1.example()
example_df = ParentModel1.... | It should be possible to create nested models. | test_nested_models | python | JakobGM/patito | tests/test_dummy_data.py | https://github.com/JakobGM/patito/blob/master/tests/test_dummy_data.py | MIT |
def test_instantiating_model_from_row() -> None:
"""You should be able to instantiate models from rows."""
class Model(pt.Model):
a: int
polars_dataframe = pl.DataFrame({"a": [1]})
assert Model.from_row(polars_dataframe).a == 1
# Anything besides a dataframe / row should raise TypeError
... | You should be able to instantiate models from rows. | test_instantiating_model_from_row | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_instantiation_from_pandas_row() -> None:
"""You should be able to instantiate models from pandas rows."""
pytest.importorskip("pandas")
class Model(pt.Model):
a: int
polars_dataframe = pl.DataFrame({"a": [1]})
assert Model.from_row(polars_dataframe).a == 1
pandas_dataframe = ... | You should be able to instantiate models from pandas rows. | test_instantiation_from_pandas_row | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_dataframe_class_creation() -> None:
"""Each model should get a custom DataFrame class."""
class CustomModel(pt.Model):
a: int
# The DataFrame class is a sub-class of patito.DataFrame
assert issubclass(CustomModel.DataFrame, pt.DataFrame)
# The LazyFrame class is a sub-class... | Each model should get a custom DataFrame class. | test_model_dataframe_class_creation | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_mapping_to_polars_dtypes() -> None:
"""Model fields should be mappable to polars dtypes."""
assert CompleteModel.dtypes == {
"str_column": pl.String(),
"int_column": pl.Int64(),
"float_column": pl.Float64(),
"bool_column": pl.Boolean(),
"date_column": pl.Date(),
... | Model fields should be mappable to polars dtypes. | test_mapping_to_polars_dtypes | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_joins() -> None:
"""It should produce models compatible with join statements."""
class Left(pt.Model):
left: int = pt.Field(gt=20)
opt_left: Optional[int] = None
class Right(pt.Model):
right: int = pt.Field(gt=20)
opt_right: Optional[int] = None
def test... | It should produce models compatible with join statements. | test_model_joins | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_validator(model: type[pt.Model]) -> None:
"""Test if all field validators have been included correctly."""
with pytest.raises(ValidationError) as e:
model(left=1, opt_left=1, right=1, opt_right=1)
pattern = re.compile(r"Input should be greater than 20")
assert ... | Test if all field validators have been included correctly. | test_model_validator | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_selects() -> None:
"""It should produce models compatible with select statements."""
class MyModel(pt.Model):
a: Optional[int]
b: int = pt.Field(gt=10)
MySubModel = MyModel.select("b")
assert MySubModel.columns == ["b"]
MySubModel(b=11)
with pytest.raises(Validat... | It should produce models compatible with select statements. | test_model_selects | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_prefix_and_suffix() -> None:
"""It should produce models where all fields have been prefixed/suffixed."""
class MyModel(pt.Model):
a: Optional[int]
b: str
NewModel = MyModel.prefix("pre_").suffix("_post")
assert sorted(NewModel.columns) == ["pre_a_post", "pre_b_post"]
... | It should produce models where all fields have been prefixed/suffixed. | test_model_prefix_and_suffix | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_field_renaming() -> None:
"""It should be able to change its field names."""
class MyModel(pt.Model):
a: Optional[int]
b: str
NewModel = MyModel.rename({"b": "B"})
assert sorted(NewModel.columns) == ["B", "a"]
with pytest.raises(
ValueError,
match="T... | It should be able to change its field names. | test_model_field_renaming | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_field_dropping() -> None:
"""Model should be able to drop a subset of its fields."""
class MyModel(pt.Model):
a: int
b: int
c: int
assert sorted(MyModel.drop("c").columns) == ["a", "b"]
assert MyModel.drop(["b", "c"]).columns == ["a"] | Model should be able to drop a subset of its fields. | test_model_field_dropping | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_with_fields() -> None:
"""It should allow whe user to add additional fields."""
class MyModel(pt.Model):
a: int
ExpandedModel = MyModel.with_fields(
b=(int, ...),
c=(int, None),
d=(int, pt.Field(gt=10)),
e=(Optional[int], None),
)
assert sorted(Expa... | It should allow whe user to add additional fields. | test_with_fields | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_enum_annotated_field() -> None:
"""It should use values of enums to infer types."""
class ABCEnum(enum.Enum):
ONE = "a"
TWO = "b"
THREE = "c"
class EnumModel(pt.Model):
column: ABCEnum
assert EnumModel.dtypes["column"] == pl.Enum(["a", "b", "c"])
assert En... | It should use values of enums to infer types. | test_enum_annotated_field | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_model_schema() -> None:
"""Ensure pt.Field properties are correctly applied to model."""
class Model(pt.Model):
a: int = pt.Field(ge=0, unique=True)
schema = Model.model_schema
def validate_model_schema(schema) -> None:
assert set(schema) == {"properties", "required", "type",... | Ensure pt.Field properties are correctly applied to model. | test_model_schema | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_conflicting_type_dtype() -> None:
"""Ensure model annotation is compatible with Field dtype."""
with pytest.raises(ValueError, match="Invalid dtype String"):
class Test1(pt.Model):
foo: int = pt.Field(dtype=pl.String)
Test1.validate_schema()
with pytest.raises(ValueEr... | Ensure model annotation is compatible with Field dtype. | test_conflicting_type_dtype | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_polars_python_type_harmonization() -> None:
"""Ensure datetime types are correctly transformed to polars types."""
class Test(pt.Model):
date: datetime = pt.Field(dtype=pl.Datetime(time_unit="us"))
time: time
assert Test.valid_dtypes["date"] == {pl.Datetime(time_unit="us")}
as... | Ensure datetime types are correctly transformed to polars types. | test_polars_python_type_harmonization | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_column_infos() -> None:
"""Test that pt.Field and ColumnInfo properties match."""
class Model(pt.Model):
a: int
b: int = pt.Field(constraints=[(pl.col("b") < 10)])
c: int = pt.Field(derived_from=pl.col("a") + pl.col("b"))
d: int = pt.Field(dtype=pl.UInt8)
e: int... | Test that pt.Field and ColumnInfo properties match. | test_column_infos | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_validation_alias():
"""Test that validation alias works in pt.Field.
TODO: Not sure if this actually tests anything correctly.
"""
class AliasModel(pt.Model):
my_val_a: int = pt.Field(validation_alias="myValA")
my_val_b: int = pt.Field(validation_alias=AliasChoices("my_val_b",... | Test that validation alias works in pt.Field.
TODO: Not sure if this actually tests anything correctly.
| test_validation_alias | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_json_schema_extra_is_extended_when_it_exists() -> None:
"""Ensure that the json_schema_extra property is extended with column_info when it is set from the model field."""
class Model(pt.Model):
a: int
b: int = pt.Field(
json_schema_extra={"client_column_metadata": {"group1"... | Ensure that the json_schema_extra property is extended with column_info when it is set from the model field. | test_json_schema_extra_is_extended_when_it_exists | python | JakobGM/patito | tests/test_model.py | https://github.com/JakobGM/patito/blob/master/tests/test_model.py | MIT |
def test_dataframe_get_method() -> None:
"""You should be able to retrieve a single row and cast to model."""
class Product(pt.Model):
product_id: int = pt.Field(unique=True)
price: float
df = pt.DataFrame({"product_id": [1, 2], "price": [9.99, 19.99]})
# Validation does nothing, as n... | You should be able to retrieve a single row and cast to model. | test_dataframe_get_method | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_dataframe_set_model_method() -> None:
"""You should be able to set the associated model of a dataframe."""
class MyModel(pt.Model):
pass
modelled_df = pt.DataFrame().set_model(MyModel)
assert modelled_df.model is MyModel
assert MyModel.DataFrame.model is MyModel | You should be able to set the associated model of a dataframe. | test_dataframe_set_model_method | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_fill_nan_with_defaults() -> None:
"""You should be able to fill missing values with declared defaults."""
class DefaultModel(pt.Model):
foo: int = 2
bar: str = "default"
missing_df = pt.DataFrame({"foo": [1, None], "bar": [None, "provided"]})
filled_df = missing_df.set_model(D... | You should be able to fill missing values with declared defaults. | test_fill_nan_with_defaults | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_create_missing_columns_with_defaults() -> None:
"""Columns that have default values should be created if they are missing."""
class NestedModel(pt.Model):
foo: int = 2
small_model: Optional[SmallModel] = None
class DefaultModel(pt.Model):
foo: int = 2
bar: Optional... | Columns that have default values should be created if they are missing. | test_create_missing_columns_with_defaults | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_create_missing_columns_with_dtype() -> None:
"""Ensure optional columns are created by model."""
class DefaultModel(pt.Model):
foo: int
bar: Optional[int] = None
missing_df = pt.DataFrame({"foo": [1, 2]})
filled_df = missing_df.set_model(DefaultModel).fill_null(strategy="defau... | Ensure optional columns are created by model. | test_create_missing_columns_with_dtype | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_preservation_of_model() -> None:
"""The model should be preserved on data frames after method invocations."""
class DummyModel(pt.Model):
a: int
class AnotherDummyModel(pt.Model):
a: int
df_with_model = pt.DataFrame().set_model(DummyModel)
# First many eagerly executed m... | The model should be preserved on data frames after method invocations. | test_preservation_of_model | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_dataframe_model_dtype_casting() -> None:
"""You should be able to cast columns according to model type annotations."""
class DTypeModel(pt.Model):
implicit_int: int
explicit_uint: int = pt.Field(dtype=pl.UInt64)
implicit_date: date
implicit_datetime: datetime
origi... | You should be able to cast columns according to model type annotations. | test_dataframe_model_dtype_casting | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_regular_inferred(tmp_path):
"""The `polars.read_csv` function should infer dtypes."""
csv_path = tmp_path / "foo.csv"
csv_path.write_text("1,2")
regular_df = pl.read_csv(csv_path, has_header=False)
assert regular_df.columns == ["column_1", "column_2"]
... | The `polars.read_csv` function should infer dtypes. | test_correct_columns_and_dtype_on_read_regular_inferred | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_model_dtypes(tmp_path):
"""A model DataFrame should read headerless CSVs with column names and dtypes."""
class Foo(pt.Model):
a: str = pt.Field()
b: int = pt.Field()
csv_path = tmp_path / "foo.csv"
csv_path.write_text("1,2")
model_df = Fo... | A model DataFrame should read headerless CSVs with column names and dtypes. | test_correct_columns_and_dtype_on_read_model_dtypes | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_ordered(tmp_path):
"""A model DataFrame should read headered CSVs with column names and dtypes."""
class Foo(pt.Model):
a: str = pt.Field()
b: int = pt.Field()
csv_path = tmp_path / "foo.csv"
# in model field order
csv_path.write_text("a,... | A model DataFrame should read headered CSVs with column names and dtypes. | test_correct_columns_and_dtype_on_read_ordered | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_ba_float_dtype_override(tmp_path):
"""A model DataFrame should aid CSV reading with column names and dtypes."""
class Foo(pt.Model):
a: str = pt.Field()
b: int = pt.Field()
csv_path = tmp_path / "foo.csv"
# in fkield order
csv_path.write_t... | A model DataFrame should aid CSV reading with column names and dtypes. | test_correct_columns_and_dtype_on_read_ba_float_dtype_override | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_correct_columns_and_dtype_on_read_alias_gen(tmp_path):
"""A model DataFrame should apply aliases to CSV columns."""
csv_path = tmp_path / "foo.csv"
csv_path.write_text("a,b\n1,2")
class AliasedModel(pt.Model):
model_config = ConfigDict(
alias_generator=AliasGenerator(valida... | A model DataFrame should apply aliases to CSV columns. | test_correct_columns_and_dtype_on_read_alias_gen | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_derive_functionality() -> None:
"""Test of Field(derived_from=...) and DataFrame.derive()."""
class DerivedModel(pt.Model):
underived: int
const_derived: int = pt.Field(derived_from=pl.lit(3))
column_derived: int = pt.Field(derived_from="underived")
expr_derived: int = ... | Test of Field(derived_from=...) and DataFrame.derive(). | test_derive_functionality | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_recursive_derive() -> None:
"""Data.Frame.derive() infers proper derivation order and executes it, then returns columns in the order given by the model."""
class DerivedModel(pt.Model):
underived: int
const_derived: int = pt.Field(derived_from=pl.lit(3))
second_order_derived: i... | Data.Frame.derive() infers proper derivation order and executes it, then returns columns in the order given by the model. | test_recursive_derive | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_drop_method() -> None:
"""We should be able to drop columns not specified by the data frame model."""
class Model(pt.Model):
column_1: int
df = Model.DataFrame({"column_1": [1, 2], "column_2": [3, 4]})
# Originally we have all the columns
assert df.columns == ["column_1", "column... | We should be able to drop columns not specified by the data frame model. | test_drop_method | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_polars_conversion():
"""You should be able to convert a DataFrame to a polars DataFrame."""
class Model(pt.Model):
a: int
b: str
df = Model.DataFrame({"a": [1, 2], "b": ["foo", "bar"]})
polars_df = df.as_polars()
assert isinstance(polars_df, pl.DataFrame)
assert not is... | You should be able to convert a DataFrame to a polars DataFrame. | test_polars_conversion | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_validation_alias() -> None:
"""Ensure validation_alias allows multiple column names to be parsed for one field."""
class AliasModel(pt.Model):
my_val_a: int = pt.Field(validation_alias="myValA")
my_val_b: int = pt.Field(
validation_alias=AliasChoices("my_val_b", "myValB", "... | Ensure validation_alias allows multiple column names to be parsed for one field. | test_validation_alias | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_alias_generator_read_csv() -> None:
"""Ensure validation alias is applied to read_csv."""
class AliasGeneratorModel(pt.Model):
model_config = ConfigDict(
alias_generator=AliasGenerator(validation_alias=str.title),
)
My_Val_A: int
My_Val_B: Optional[int] = N... | Ensure validation alias is applied to read_csv. | test_alias_generator_read_csv | python | JakobGM/patito | tests/test_polars.py | https://github.com/JakobGM/patito/blob/master/tests/test_polars.py | MIT |
def test_is_optional() -> None:
"""It should return True for optional types."""
assert is_optional(Optional[int])
assert is_optional(Union[int, None])
assert not is_optional(int) | It should return True for optional types. | test_is_optional | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_dewrap_optional() -> None:
"""It should return the inner type of Optional types."""
assert unwrap_optional(Optional[int]) is int
assert unwrap_optional(Union[int, None]) is int
assert unwrap_optional(int) is int | It should return the inner type of Optional types. | test_dewrap_optional | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validation_returns_df() -> None:
"""It should return a DataFrame with the validation results."""
class SimpleModel(pt.Model):
column_1: int
column_2: str
df = pl.DataFrame({"column_1": [1, 2, 3], "column_2": ["a", "b", "c"]})
result = validate(dataframe=df, schema=SimpleModel)... | It should return a DataFrame with the validation results. | test_validation_returns_df | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_allow_missing_nested_column_validation() -> None:
"""Validation should allow missing nested columns."""
class InnerModel(pt.Model):
column_1: int
column_2: str = pt.Field(allow_missing=True)
class OuterModel(pt.Model):
inner: InnerModel
other: str
df_missing_n... | Validation should allow missing nested columns. | test_allow_missing_nested_column_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_drop_superfluous_columns() -> None:
"""Test whether irrelevant columns get filtered out before validation."""
class SingleColumnModel(pt.Model):
column_1: int
test_df = SingleColumnModel.examples().with_columns(
column_that_should_be_dropped=pl.Series([1])
)
result = valid... | Test whether irrelevant columns get filtered out before validation. | test_drop_superfluous_columns | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validate_non_nullable_columns() -> None:
"""Test for validation logic related to missing values."""
class SmallModel(pt.Model):
column_1: int
column_2: Optional[int] = None
# We insert nulls into a non-optional column, causing an exception
wrong_nulls_df = pl.DataFrame().with_... | Test for validation logic related to missing values. | test_validate_non_nullable_columns | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_uniqueness_validation() -> None:
"""It should be able to validate uniqueness."""
class MyModel(pt.Model):
column: int = pt.Field(unique=True)
non_duplicated_df = pt.DataFrame({"column": [1, 2, 3]})
MyModel.validate(non_duplicated_df)
empty_df = pt.DataFrame([pl.Series("column", [... | It should be able to validate uniqueness. | test_uniqueness_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_datetime_validation() -> None:
"""Test for date(time) validation.
Both strings, dates, and datetimes are assigned type "string" in the OpenAPI JSON
schema spec, so this needs to be specifically tested for since the implementation
needs to check the "format" property on the field schema.
""... | Test for date(time) validation.
Both strings, dates, and datetimes are assigned type "string" in the OpenAPI JSON
schema spec, so this needs to be specifically tested for since the implementation
needs to check the "format" property on the field schema.
| test_datetime_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_enum_validation() -> None:
"""Test validation of enum.Enum-typed fields."""
class ABCEnum(enum.Enum):
ONE = "a"
TWO = "b"
THREE = "c"
class EnumModel(pt.Model):
column: ABCEnum
valid_df = pl.DataFrame({"column": ["a", "b", "b", "c"]})
validate(dataframe=va... | Test validation of enum.Enum-typed fields. | test_enum_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_optional_enum_validation() -> None:
"""Test validation of optional enum.Enum-typed fields."""
class ABCEnum(enum.Enum):
ONE = "a"
TWO = "b"
THREE = "c"
class EnumModel(pt.Model):
column: Optional[ABCEnum]
valid_df = pl.DataFrame({"column": ["a", "b", "b", "c"]... | Test validation of optional enum.Enum-typed fields. | test_optional_enum_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_literal_enum_validation() -> None:
"""Test validation of typing.Literal-typed fields."""
class EnumModel(pt.Model):
column: Literal["a", "b", "c"]
valid_df = pl.DataFrame({"column": ["a", "b", "b", "c"]})
validate(dataframe=valid_df, schema=EnumModel)
invalid_df = pl.DataFrame({"... | Test validation of typing.Literal-typed fields. | test_literal_enum_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_optional_literal_enum_validation() -> None:
"""Test validation of optional typing.Literal-typed fields."""
class EnumModel(pt.Model):
column: Optional[Literal["a", "b", "c"]]
valid_df = pl.DataFrame({"column": ["a", "b", "b", "c"]})
validate(dataframe=valid_df, schema=EnumModel)
... | Test validation of optional typing.Literal-typed fields. | test_optional_literal_enum_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_simple_struct_validation() -> None:
"""Test validation of model with struct column."""
valid_df = pl.DataFrame({"positive_struct": [{"x": 1}, {"x": 2}, {"x": 3}]})
_PositiveStructModel.validate(valid_df)
bad_df = pl.DataFrame({"positive_struct": [{"x": -1}, {"x": 2}, {"x": 3}]})
with pytes... | Test validation of model with struct column. | test_simple_struct_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_nested_struct_validation() -> None:
"""Test validation of model with nested struct column."""
class NestedPositiveStructModel(pt.Model):
positive_struct_model: _PositiveStructModel
valid_df = pl.DataFrame(
{
"positive_struct_model": [
{"positive_struct"... | Test validation of model with nested struct column. | test_nested_struct_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_empty_list_validation() -> None:
"""Test validation of model with empty lists."""
class TestModel(pt.Model):
list_field: list[str]
# validate presence of an empty list
df = pl.DataFrame({"list_field": [["a", "b"], []]})
TestModel.validate(df)
# validate when all lists are emp... | Test validation of model with empty lists. | test_empty_list_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_list_struct_validation() -> None:
"""Test validation of model with list of structs column."""
class ListPositiveStructModel(pt.Model):
list_positive_struct: list[_PositiveStruct]
valid_df = pl.DataFrame(
{"list_positive_struct": [[{"x": 1}, {"x": 2}], [{"x": 3}, {"x": 4}, {"x": 5}... | Test validation of model with list of structs column. | test_list_struct_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_struct_validation_with_polars_constraint() -> None:
"""Test validation of models with constrained struct column."""
class Interval(pt.Model):
x_min: int
x_max: int = pt.Field(constraints=pt.col("x_min") <= pt.col("x_max"))
class IntervalModel(pt.Model):
interval: Interval
... | Test validation of models with constrained struct column. | test_struct_validation_with_polars_constraint | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validation_of_bounds_checks() -> None:
"""Check if value bounds are correctly validated."""
class BoundModel(pt.Model):
le_column: float = pt.Field(le=42.5)
lt_column: float = pt.Field(lt=42.5)
ge_column: float = pt.Field(ge=42.5)
gt_column: float = pt.Field(gt=42.5)
... | Check if value bounds are correctly validated. | test_validation_of_bounds_checks | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validation_of_dtype_specifiers() -> None:
"""Fields with specific dtype annotations should be validated."""
class DTypeModel(pt.Model):
int_column: int
int_explicit_dtype_column: int = pt.Field(dtype=pl.Int64)
smallint_column: int = pt.Field(dtype=pl.Int8)
unsigned_int_... | Fields with specific dtype annotations should be validated. | test_validation_of_dtype_specifiers | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_custom_constraint_validation() -> None:
"""Users should be able to specify custom constraints."""
class CustomConstraintModel(pt.Model):
even_int: int = pt.Field(
constraints=[(pl.col("even_int") % 2 == 0).alias("even_constraint")]
)
odd_int: int = pt.Field(constrai... | Users should be able to specify custom constraints. | test_custom_constraint_validation | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_anonymous_column_constraints() -> None:
"""You should be able to refer to the field column with an anonymous column."""
class Pair(pt.Model):
# pl.col("_") refers to the given field column
odd_number: int = pt.Field(constraints=pl.col("_") % 2 == 1)
# pt.field is simply an alia... | You should be able to refer to the field column with an anonymous column. | test_anonymous_column_constraints | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_optional_enum() -> None:
"""It should handle optional enums correctly."""
class OptionalEnumModel(pt.Model):
# Old type annotation syntax
optional_enum: Optional[Literal["A", "B"]]
df = pl.DataFrame({"optional_enum": ["A", "B", None]})
OptionalEnumModel.validate(df) | It should handle optional enums correctly. | test_optional_enum | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_optional_pipe_operator() -> None:
"""Ensure that pipe operator works as expected."""
class OptionalEnumModel(pt.Model):
# Old type annotation syntax
optional_enum_1: Optional[Literal["A", "B"]]
# New type annotation syntax
optional_enum_2: Optional[Literal["A", "B"]]
... | Ensure that pipe operator works as expected. | test_optional_pipe_operator | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validation_of_list_dtypes() -> None:
"""It should be able to validate dtypes organized in lists."""
class ListModel(pt.Model):
int_list: list[int]
int_or_null_list: list[Optional[int]]
nullable_int_list: Optional[list[int]]
nullable_int_or_null_list: Optional[list[Optio... | It should be able to validate dtypes organized in lists. | test_validation_of_list_dtypes | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_optional_nested_list() -> None:
"""It should be able to validate optional structs organized in lists."""
class Inner(pt.Model):
name: str
reliability: bool
level: int
class Outer(pt.Model):
id: str
code: str
label: str
inner_types: Optional[... | It should be able to validate optional structs organized in lists. | test_optional_nested_list | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_nested_field_attrs() -> None:
"""Ensure that constraints are respected even when embedded inside 'anyOf'."""
class Test(pt.Model):
foo: Optional[int] = pt.Field(
dtype=pl.Int64, ge=0, le=100, constraints=pt.field.sum() == 100
)
test_df = Test.DataFrame(
{"foo":... | Ensure that constraints are respected even when embedded inside 'anyOf'. | test_nested_field_attrs | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validation_column_subset() -> None:
"""Ensure that columns are only validated if they are in the subset."""
class Test(pt.Model):
a: int
b: int = pt.Field(dtype=pl.Int64, ge=0, le=100)
Test.validate(pl.DataFrame({"a": [1, 2, 3], "b": [1, 2, 3]})) # should pass
with pytest.rai... | Ensure that columns are only validated if they are in the subset. | test_validation_column_subset | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_alias_generator() -> None:
"""Allow column name transformations through AliasGenerator."""
df = pl.DataFrame({"my_val_a": [0]})
class NoAliasGeneratorModel(pt.Model):
My_Val_A: int
with pytest.raises(DataFrameValidationError):
NoAliasGeneratorModel.validate(df)
class Alia... | Allow column name transformations through AliasGenerator. | test_alias_generator | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_validate_should_not_mutate_the_original_polars_df_when_aliasing(
df: pd.DataFrame | pl.DataFrame, expected: pd.DataFrame | pl.DataFrame
) -> None:
"""Ensure that the original DataFrame is not mutated by the validation process."""
class AliasGeneratorModel(pt.Model):
model_config = ConfigDi... | Ensure that the original DataFrame is not mutated by the validation process. | test_validate_should_not_mutate_the_original_polars_df_when_aliasing | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_alias_generator_func() -> None:
"""Allow column name transformations through a string function."""
df = pl.DataFrame({"my_val_a": [0]})
class NoAliasGeneratorModel(pt.Model):
My_Val_A: int
with pytest.raises(DataFrameValidationError):
NoAliasGeneratorModel.validate(df)
cl... | Allow column name transformations through a string function. | test_alias_generator_func | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_derived_from_ser_deser():
"""Test whether derived_from can be successfully serialized and deserialized."""
for expr in [None, "foo", pl.col("foo"), pl.col("foo") * 2]:
ci = ColumnInfo(derived_from=expr)
# use str for equality check of expressions
# since expr == expr is an expre... | Test whether derived_from can be successfully serialized and deserialized. | test_derived_from_ser_deser | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_constraint_ser_deser():
"""Test whether constraints can be successfully serialized and deserialized."""
for expr in [pl.col("foo") == 2, pl.col("foo") * 2 == 2]:
ci = ColumnInfo(constraints=expr)
# use str for equality check of expressions
# since expr == expr is an expression i... | Test whether constraints can be successfully serialized and deserialized. | test_constraint_ser_deser | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def test_dtype_ser_deser():
"""Test whether dtypes can be successfully serialized and deserialized."""
for expr in [
pl.Float32,
pl.String,
pl.String(),
pl.Datetime(time_zone="Europe/Oslo"),
pl.Struct({"foo": pl.Int16, "bar": pl.Datetime(time_zone="Europe/Oslo")}),
... | Test whether dtypes can be successfully serialized and deserialized. | test_dtype_ser_deser | python | JakobGM/patito | tests/test_validators.py | https://github.com/JakobGM/patito/blob/master/tests/test_validators.py | MIT |
def query_db(query, args=(), one=False):
"""Queries the database and returns a list of dictionaries."""
cur = sqldb.execute(query, args)
rv = cur.fetchall()
return (rv[0] if rv else None) if one else rv | Queries the database and returns a list of dictionaries. | query_db | python | karpathy/arxiv-sanity-preserver | buildsvm.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/buildsvm.py | MIT |
def encode_feedparser_dict(d):
"""
helper function to get rid of feedparser bs with a deep copy.
I hate when libs wrap simple things in their own classes.
"""
if isinstance(d, feedparser.FeedParserDict) or isinstance(d, dict):
j = {}
for k in d.keys():
j[k] = encode_feedparser_dict(d[k])
r... |
helper function to get rid of feedparser bs with a deep copy.
I hate when libs wrap simple things in their own classes.
| encode_feedparser_dict | python | karpathy/arxiv-sanity-preserver | fetch_papers.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/fetch_papers.py | MIT |
def parse_arxiv_url(url):
"""
examples is http://arxiv.org/abs/1512.08756v2
we want to extract the raw id and the version
"""
ix = url.rfind('/')
idversion = url[ix+1:] # extract just the id (and the version)
parts = idversion.split('v')
assert len(parts) == 2, 'error parsing url ' + url
return parts... |
examples is http://arxiv.org/abs/1512.08756v2
we want to extract the raw id and the version
| parse_arxiv_url | python | karpathy/arxiv-sanity-preserver | fetch_papers.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/fetch_papers.py | MIT |
def get_user_id(username):
"""Convenience method to look up the id for a username."""
rv = query_db('select user_id from user where username = ?',
[username], one=True)
return rv[0] if rv else None | Convenience method to look up the id for a username. | get_user_id | python | karpathy/arxiv-sanity-preserver | serve.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/serve.py | MIT |
def get_username(user_id):
"""Convenience method to look up the username for a user."""
rv = query_db('select username from user where user_id = ?',
[user_id], one=True)
return rv[0] if rv else None | Convenience method to look up the username for a user. | get_username | python | karpathy/arxiv-sanity-preserver | serve.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/serve.py | MIT |
def review():
""" user wants to toggle a paper in his library """
# make sure user is logged in
if not g.user:
return 'NO' # fail... (not logged in). JS should prevent from us getting here.
idvv = request.form['pid'] # includes version
if not isvalidid(idvv):
return 'NO' # fail, malformed id. weir... | user wants to toggle a paper in his library | review | python | karpathy/arxiv-sanity-preserver | serve.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/serve.py | MIT |
def login():
""" logs in the user. if the username doesn't exist creates the account """
if not request.form['username']:
flash('You have to enter a username')
elif not request.form['password']:
flash('You have to enter a password')
elif get_user_id(request.form['username']) is not None:
# userna... | logs in the user. if the username doesn't exist creates the account | login | python | karpathy/arxiv-sanity-preserver | serve.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/serve.py | MIT |
def _tempfile(*args, **kws):
""" Context for temporary file.
Will find a free temporary filename upon entering
and will try to delete the file on leaving
Parameters
----------
suffix : string
optional file suffix
"""
fd, name = tempfile.mkstemp(*args, **kws)
os.close(fd)
... | Context for temporary file.
Will find a free temporary filename upon entering
and will try to delete the file on leaving
Parameters
----------
suffix : string
optional file suffix
| _tempfile | python | karpathy/arxiv-sanity-preserver | utils.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/utils.py | MIT |
def open_atomic(filepath, *args, **kwargs):
""" Open temporary file object that atomically moves to destination upon
exiting.
Allows reading and writing to and from the same filename.
Parameters
----------
filepath : string
the file path to be opened
fsync : bool
whether to... | Open temporary file object that atomically moves to destination upon
exiting.
Allows reading and writing to and from the same filename.
Parameters
----------
filepath : string
the file path to be opened
fsync : bool
whether to force write the file to disk
kwargs : mixed
... | open_atomic | python | karpathy/arxiv-sanity-preserver | utils.py | https://github.com/karpathy/arxiv-sanity-preserver/blob/master/utils.py | MIT |
async def generate_report_plan(state: ReportState, config: RunnableConfig):
"""Generate the initial report plan with sections.
This node:
1. Gets configuration for the report structure and search parameters
2. Generates search queries to gather context for planning
3. Performs web searches usin... | Generate the initial report plan with sections.
This node:
1. Gets configuration for the report structure and search parameters
2. Generates search queries to gather context for planning
3. Performs web searches using those queries
4. Uses an LLM to generate a structured plan with sections
... | generate_report_plan | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
def human_feedback(state: ReportState, config: RunnableConfig) -> Command[Literal["generate_report_plan","build_section_with_web_research"]]:
"""Get human feedback on the report plan and route to next steps.
This node:
1. Formats the current report plan for human review
2. Gets feedback via an inte... | Get human feedback on the report plan and route to next steps.
This node:
1. Formats the current report plan for human review
2. Gets feedback via an interrupt
3. Routes to either:
- Section writing if plan is approved
- Plan regeneration if feedback is provided
Args:
... | human_feedback | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
async def generate_queries(state: SectionState, config: RunnableConfig):
"""Generate search queries for researching a specific section.
This node uses an LLM to generate targeted search queries based on the
section topic and description.
Args:
state: Current state containing section d... | Generate search queries for researching a specific section.
This node uses an LLM to generate targeted search queries based on the
section topic and description.
Args:
state: Current state containing section details
config: Configuration including number of queries to generate
... | generate_queries | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
async def search_web(state: SectionState, config: RunnableConfig):
"""Execute web searches for the section queries.
This node:
1. Takes the generated queries
2. Executes searches using configured search API
3. Formats results into usable context
Args:
state: Current state with ... | Execute web searches for the section queries.
This node:
1. Takes the generated queries
2. Executes searches using configured search API
3. Formats results into usable context
Args:
state: Current state with search queries
config: Search API configuration
Retur... | search_web | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
async def write_section(state: SectionState, config: RunnableConfig) -> Command[Literal[END, "search_web"]]:
"""Write a section of the report and evaluate if more research is needed.
This node:
1. Writes section content using search results
2. Evaluates the quality of the section
3. Either:
... | Write a section of the report and evaluate if more research is needed.
This node:
1. Writes section content using search results
2. Evaluates the quality of the section
3. Either:
- Completes the section if quality passes
- Triggers more research if quality fails
Args:
... | write_section | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
async def write_final_sections(state: SectionState, config: RunnableConfig):
"""Write sections that don't require research using completed sections as context.
This node handles sections like conclusions or summaries that build on
the researched sections rather than requiring direct research.
... | Write sections that don't require research using completed sections as context.
This node handles sections like conclusions or summaries that build on
the researched sections rather than requiring direct research.
Args:
state: Current state with completed sections as context
config... | write_final_sections | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
def gather_completed_sections(state: ReportState):
"""Format completed sections as context for writing final sections.
This node takes all completed research sections and formats them into
a single context string for writing summary sections.
Args:
state: Current state with completed s... | Format completed sections as context for writing final sections.
This node takes all completed research sections and formats them into
a single context string for writing summary sections.
Args:
state: Current state with completed sections
Returns:
Dict with formatted ... | gather_completed_sections | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
def compile_final_report(state: ReportState, config: RunnableConfig):
"""Compile all sections into the final report.
This node:
1. Gets all completed sections
2. Orders them according to original plan
3. Combines them into the final report
Args:
state: Current state with all co... | Compile all sections into the final report.
This node:
1. Gets all completed sections
2. Orders them according to original plan
3. Combines them into the final report
Args:
state: Current state with all completed sections
Returns:
Dict containing the complete r... | compile_final_report | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
def initiate_final_section_writing(state: ReportState):
"""Create parallel tasks for writing non-research sections.
This edge function identifies sections that don't need research and
creates parallel writing tasks for each one.
Args:
state: Current state with all sections and research... | Create parallel tasks for writing non-research sections.
This edge function identifies sections that don't need research and
creates parallel writing tasks for each one.
Args:
state: Current state with all sections and research context
Returns:
List of Send commands fo... | initiate_final_section_writing | python | langchain-ai/open_deep_research | src/open_deep_research/graph.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/graph.py | MIT |
def get_search_tool(config: RunnableConfig):
"""Get the appropriate search tool based on configuration"""
configurable = MultiAgentConfiguration.from_runnable_config(config)
search_api = get_config_value(configurable.search_api)
# Return None if no search tool is requested
if search_api.lower() == ... | Get the appropriate search tool based on configuration | get_search_tool | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def get_supervisor_tools(config: RunnableConfig) -> list[BaseTool]:
"""Get supervisor tools based on configuration"""
configurable = MultiAgentConfiguration.from_runnable_config(config)
search_tool = get_search_tool(config)
tools = [tool(Sections), tool(Introduction), tool(Conclusion), tool(Finish... | Get supervisor tools based on configuration | get_supervisor_tools | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def get_research_tools(config: RunnableConfig) -> list[BaseTool]:
"""Get research tools based on configuration"""
search_tool = get_search_tool(config)
tools = [tool(Section), tool(FinishResearch)]
if search_tool is not None:
tools.append(search_tool) # Add search tool, if available
e... | Get research tools based on configuration | get_research_tools | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def supervisor(state: ReportState, config: RunnableConfig):
"""LLM decides whether to call a tool or not"""
# Messages
messages = state["messages"]
# Get configuration
configurable = MultiAgentConfiguration.from_runnable_config(config)
supervisor_model = get_config_value(configurable.sup... | LLM decides whether to call a tool or not | supervisor | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def supervisor_tools(state: ReportState, config: RunnableConfig) -> Command[Literal["supervisor", "research_team", "__end__"]]:
"""Performs the tool call and sends to the research agent"""
configurable = MultiAgentConfiguration.from_runnable_config(config)
result = []
sections_list = []
intr... | Performs the tool call and sends to the research agent | supervisor_tools | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def supervisor_should_continue(state: ReportState) -> str:
"""Decide if we should continue the loop or stop based upon whether the LLM made a tool call"""
messages = state["messages"]
last_message = messages[-1]
# End because the supervisor asked a question or is finished
if not last_message.... | Decide if we should continue the loop or stop based upon whether the LLM made a tool call | supervisor_should_continue | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
async def research_agent_tools(state: SectionState, config: RunnableConfig):
"""Performs the tool call and route to supervisor or continue the research loop"""
configurable = MultiAgentConfiguration.from_runnable_config(config)
result = []
completed_section = None
source_str = ""
# Get too... | Performs the tool call and route to supervisor or continue the research loop | research_agent_tools | python | langchain-ai/open_deep_research | src/open_deep_research/multi_agent.py | https://github.com/langchain-ai/open_deep_research/blob/master/src/open_deep_research/multi_agent.py | MIT |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.