# Examples

Module for handling example data in document processing.

This module provides classes for defining examples that can be used to guide LLM extraction tasks.
Examples serve as reference points for the model to understand the expected format and content
of extracted information. The module supports different types of examples including string-based
examples and structured JSON object examples.

Examples can be attached to concepts to provide concrete illustrations of the kind of information
to be extracted, improving the accuracy and consistency of LLM-based extraction processes.

### *class* contextgem.public.examples.StringExample(\*\*data)

Bases: `_StringExample`

Represents a string example that can be provided by users for certain extraction tasks.

* **Variables:**
  **content** ([*str*](https://docs.python.org/3/builtins/stdtypes.html#str)) – A non-empty string that holds the text content of the example.
* **Parameters:**
  * **custom_data** ([*Annotated*](https://docs.python.org/3/library/typing.html#typing.Annotated) *[*[*dict*](https://docs.python.org/3/builtins/stdtypes.html#dict) *[*[*str*](https://docs.python.org/3/builtins/stdtypes.html#str) *,* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any) *]* *,* [*BeforeValidator*](https://pydantic.dev/docs/validation/latest/api/pydantic/functional_validators/#pydantic.functional_validators.BeforeValidator) *(**func=~contextgem.internal.typings.validators._validate_is_json_dict* *,* *json_schema_input_type=PydanticUndefined* *)* *]*)
  * **content** ([*Annotated*](https://docs.python.org/3/library/typing.html#typing.Annotated) *[*[*str*](https://docs.python.org/3/builtins/stdtypes.html#str) *,* [*Strict*](https://pydantic.dev/docs/validation/latest/api/pydantic/types/#pydantic.types.Strict) *(**strict=True* *)* *,* [*StringConstraints*](https://pydantic.dev/docs/validation/latest/api/pydantic/types/#pydantic.types.StringConstraints) *(**strip_whitespace=True* *,* *to_upper=None* *,* *to_lower=None* *,* *strict=None* *,* *min_length=1* *,* *max_length=None* *,* *pattern=None* *,* *ascii_only=None* *)* *]*)

Note:
: Examples are optional and can be used to guide LLM extraction tasks. They serve as reference
  points for the model to understand the expected format and content of extracted information.
  StringExample can be attached to a [`StringConcept`](https://contextgem.shcherbak.ai/api/concepts/index.html.md#contextgem.public.concepts.StringConcept).

Example:
: ```python
  from contextgem import StringConcept, StringExample
  <br/>
  <br/>
  # Create string examples
  string_examples = [
      StringExample(content="X (Client)"),
      StringExample(content="Y (Supplier)"),
  ]
  <br/>
  # Attach string examples to a StringConcept
  string_concept = StringConcept(
      name="Contract party name and role",
      description="The name and role of the contract party",
      examples=string_examples,  # Attach the example to the concept (optional)
  )
  ```

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be
validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

#### clone()

Creates and returns a deep copy of the current instance.

* **Return type:**
  [`typing.Self`](https://docs.python.org/3/library/typing.html#typing.Self)
* **Returns:**
  A deep copy of the current instance.

#### *classmethod* from_dict(obj_dict)

Reconstructs an instance of the class from a dictionary representation.

This method deserializes a dictionary containing the object’s attributes and values
into a new instance of the class. It handles complex nested structures like aspects,
concepts, and extracted items, properly reconstructing each component.

A deserialized model or model group has no API credentials, as they are not
included in the serialized data, i.e. they are to be set again.

* **Parameters:**
  **obj_dict** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`typing.Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Dictionary containing the serialized object data.
* **Returns:**
  A new instance of the class with restored attributes.
* **Return type:**
  [`typing.Self`](https://docs.python.org/3/library/typing.html#typing.Self)

#### *classmethod* from_disk(file_path)

Loads an instance of the class from a JSON file stored on disk.

This method reads the JSON content from the specified file path and
deserializes it into an instance of the class using the from_json
method.

* **Parameters:**
  **file_path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Path to the JSON file to load (must end with ‘.json’).
  Can be a string or a Path object.
* **Returns:**
  An instance of the class populated with the data from the file.
* **Return type:**
  [`typing.Self`](https://docs.python.org/3/library/typing.html#typing.Self)
* **Raises:**
  * [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If the file path doesn’t end with ‘.json’, or if the file
    does not hold valid serialized data, e.g. it is not a valid UTF-8 text
    (`UnicodeDecodeError`) or JSON (`json.JSONDecodeError`), or the data
    fails validation (pydantic’s `ValidationError`). These errors are
    subclasses of `ValueError`.
  * [**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError) – If the serialized data is of another class.
  * [**OSError**](https://docs.python.org/3/builtins/exceptions.html#OSError) – If the file cannot be read, e.g. it does not exist.
    The error is the one raised by the file operation, e.g.
    `FileNotFoundError` or `PermissionError`.

#### *classmethod* from_json(json_string)

Creates an instance of the class from a JSON string representation.

This method deserializes the provided JSON string into a dictionary and uses
the from_dict method to construct the class instance. It validates that the
class name in the serialized data matches the current class.

* **Parameters:**
  **json_string** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – JSON string containing the serialized object data.
* **Returns:**
  A new instance of the class with restored state.
* **Return type:**
  [`typing.Self`](https://docs.python.org/3/library/typing.html#typing.Self)
* **Raises:**
  * [**json.JSONDecodeError**](https://docs.python.org/3/library/json.html#json.JSONDecodeError) – If the string is not a valid JSON. The error
    gives the position of what is invalid, and does not hold the string.
  * [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If the JSON value is not an object with a class name,
    i.e. not serialized data.
  * [**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError) – If the class name in the serialized data doesn’t match.

#### to_dict()

Transforms the current object into a dictionary representation.

Converts the object to a dictionary that includes:
- All public attributes
- Special handling for specific public and private attributes

When a model or model group is serialized, its API credentials and usage/cost stats are removed.

* **Returns:**
  A dictionary representation of the current object with all necessary data for serialization
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`typing.Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### to_disk(file_path)

Saves the serialized instance to a JSON file at the specified path.

This method converts the instance to a dictionary representation using to_dict(),
then writes it to disk as a formatted JSON file with UTF-8 encoding.

* **Parameters:**
  **file_path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Path where the JSON file should be saved (must end with ‘.json’).
  Can be a string or a Path object.
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)
* **Returns:**
  None
* **Raises:**
  * [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If the file path doesn’t end with ‘.json’.
  * [**OSError**](https://docs.python.org/3/builtins/exceptions.html#OSError) – If the file cannot be written, e.g. its directory does not
    exist. The error is the one raised by the file operation, e.g.
    `FileNotFoundError` or `PermissionError`.

#### to_json()

Converts the object to its JSON string representation.

Serializes the object into a JSON-formatted string using the dictionary
representation provided by the to_dict() method.

* **Returns:**
  A JSON string representation of the object.
* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### *property* unique_id *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

Returns the ULID of the instance.

#### content *: [Annotated](https://docs.python.org/3/library/typing.html#typing.Annotated)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Strict](https://pydantic.dev/docs/validation/latest/api/pydantic/types/#pydantic.types.Strict)(strict=True), [StringConstraints](https://pydantic.dev/docs/validation/latest/api/pydantic/types/#pydantic.types.StringConstraints)(strip_whitespace=True, to_upper=[None](https://docs.python.org/3/builtins/constants.html#None), to_lower=[None](https://docs.python.org/3/builtins/constants.html#None), strict=[None](https://docs.python.org/3/builtins/constants.html#None), min_length=1, max_length=[None](https://docs.python.org/3/builtins/constants.html#None), pattern=[None](https://docs.python.org/3/builtins/constants.html#None), ascii_only=[None](https://docs.python.org/3/builtins/constants.html#None))]*

#### custom_data *: [Annotated](https://docs.python.org/3/library/typing.html#typing.Annotated)[[dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Any](https://docs.python.org/3/library/typing.html#typing.Any)], [BeforeValidator](https://pydantic.dev/docs/validation/latest/api/pydantic/functional_validators/#pydantic.functional_validators.BeforeValidator)(func=\_validate_is_json_dict, json_schema_input_type=PydanticUndefined)]*

### *class* contextgem.public.examples.JsonObjectExample(\*\*data)

Bases: `_JsonObjectExample`

Represents a JSON object example that can be provided by users for certain extraction tasks.

* **Variables:**
  **content** ([*dict*](https://docs.python.org/3/builtins/stdtypes.html#dict) *[*[*str*](https://docs.python.org/3/builtins/stdtypes.html#str) *,* *Any* *]*) – A JSON-serializable dict with the minimum length of 1 that holds
  the content of the example.
* **Parameters:**
  * **custom_data** ([*Annotated*](https://docs.python.org/3/library/typing.html#typing.Annotated) *[*[*dict*](https://docs.python.org/3/builtins/stdtypes.html#dict) *[*[*str*](https://docs.python.org/3/builtins/stdtypes.html#str) *,* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any) *]* *,* [*BeforeValidator*](https://pydantic.dev/docs/validation/latest/api/pydantic/functional_validators/#pydantic.functional_validators.BeforeValidator) *(**func=~contextgem.internal.typings.validators._validate_is_json_dict* *,* *json_schema_input_type=PydanticUndefined* *)* *]*)
  * **content** ([*Annotated*](https://docs.python.org/3/library/typing.html#typing.Annotated) *[*[*dict*](https://docs.python.org/3/builtins/stdtypes.html#dict) *[*[*str*](https://docs.python.org/3/builtins/stdtypes.html#str) *,* [*Any*](https://docs.python.org/3/library/typing.html#typing.Any) *]* *,* [*BeforeValidator*](https://pydantic.dev/docs/validation/latest/api/pydantic/functional_validators/#pydantic.functional_validators.BeforeValidator) *(**func=~contextgem.internal.typings.validators._validate_is_json_dict* *,* *json_schema_input_type=PydanticUndefined* *)* *]*)

Note:
: Examples are optional and can be used to guide LLM extraction tasks. They serve as reference
  points for the model to understand the expected format and content of extracted information.
  JsonObjectExample can be attached to a [`JsonObjectConcept`](https://contextgem.shcherbak.ai/api/concepts/index.html.md#contextgem.public.concepts.JsonObjectConcept).

Example:
: ```python
  from contextgem import JsonObjectConcept, JsonObjectExample
  <br/>
  <br/>
  # Create a JSON object example
  json_example = JsonObjectExample(
      content={
          "name": "John Doe",
          "education": "Bachelor's degree in Computer Science",
          "skills": ["Python", "Machine Learning", "Data Analysis"],
          "hobbies": ["Reading", "Traveling", "Gaming"],
      }
  )
  <br/>
  <br/>
  # Define a structure for JSON object concept
  class PersonInfo:
      name: str
      education: str
      skills: list[str]
      hobbies: list[str]
  <br/>
  <br/>
  # Also works as a dict with type hints, e.g.
  # PersonInfo = {
  #     "name": str,
  #     "education": str,
  #     "skills": list[str],
  #     "hobbies": list[str],
  # }
  <br/>
  # Attach JSON example to a JsonObjectConcept
  json_concept = JsonObjectConcept(
      name="Candidate info",
      description="Structured information about a job candidate",
      structure=PersonInfo,  # Define the expected structure
      examples=[json_example],  # Attach the example to the concept (optional)
  )
  ```

Create a new model by parsing and validating input data from keyword arguments.

Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be
validated to form a valid model.

self is explicitly positional-only to allow self as a field name.

#### clone()

Creates and returns a deep copy of the current instance.

* **Return type:**
  [`typing.Self`](https://docs.python.org/3/library/typing.html#typing.Self)
* **Returns:**
  A deep copy of the current instance.

#### *classmethod* from_dict(obj_dict)

Reconstructs an instance of the class from a dictionary representation.

This method deserializes a dictionary containing the object’s attributes and values
into a new instance of the class. It handles complex nested structures like aspects,
concepts, and extracted items, properly reconstructing each component.

A deserialized model or model group has no API credentials, as they are not
included in the serialized data, i.e. they are to be set again.

* **Parameters:**
  **obj_dict** ([`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`typing.Any`](https://docs.python.org/3/library/typing.html#typing.Any)]) – Dictionary containing the serialized object data.
* **Returns:**
  A new instance of the class with restored attributes.
* **Return type:**
  [`typing.Self`](https://docs.python.org/3/library/typing.html#typing.Self)

#### *classmethod* from_disk(file_path)

Loads an instance of the class from a JSON file stored on disk.

This method reads the JSON content from the specified file path and
deserializes it into an instance of the class using the from_json
method.

* **Parameters:**
  **file_path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Path to the JSON file to load (must end with ‘.json’).
  Can be a string or a Path object.
* **Returns:**
  An instance of the class populated with the data from the file.
* **Return type:**
  [`typing.Self`](https://docs.python.org/3/library/typing.html#typing.Self)
* **Raises:**
  * [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If the file path doesn’t end with ‘.json’, or if the file
    does not hold valid serialized data, e.g. it is not a valid UTF-8 text
    (`UnicodeDecodeError`) or JSON (`json.JSONDecodeError`), or the data
    fails validation (pydantic’s `ValidationError`). These errors are
    subclasses of `ValueError`.
  * [**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError) – If the serialized data is of another class.
  * [**OSError**](https://docs.python.org/3/builtins/exceptions.html#OSError) – If the file cannot be read, e.g. it does not exist.
    The error is the one raised by the file operation, e.g.
    `FileNotFoundError` or `PermissionError`.

#### *classmethod* from_json(json_string)

Creates an instance of the class from a JSON string representation.

This method deserializes the provided JSON string into a dictionary and uses
the from_dict method to construct the class instance. It validates that the
class name in the serialized data matches the current class.

* **Parameters:**
  **json_string** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str)) – JSON string containing the serialized object data.
* **Returns:**
  A new instance of the class with restored state.
* **Return type:**
  [`typing.Self`](https://docs.python.org/3/library/typing.html#typing.Self)
* **Raises:**
  * [**json.JSONDecodeError**](https://docs.python.org/3/library/json.html#json.JSONDecodeError) – If the string is not a valid JSON. The error
    gives the position of what is invalid, and does not hold the string.
  * [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If the JSON value is not an object with a class name,
    i.e. not serialized data.
  * [**TypeError**](https://docs.python.org/3/builtins/exceptions.html#TypeError) – If the class name in the serialized data doesn’t match.

#### to_dict()

Transforms the current object into a dictionary representation.

Converts the object to a dictionary that includes:
- All public attributes
- Special handling for specific public and private attributes

When a model or model group is serialized, its API credentials and usage/cost stats are removed.

* **Returns:**
  A dictionary representation of the current object with all necessary data for serialization
* **Return type:**
  [`dict`](https://docs.python.org/3/builtins/stdtypes.html#dict)[[`str`](https://docs.python.org/3/builtins/stdtypes.html#str), [`typing.Any`](https://docs.python.org/3/library/typing.html#typing.Any)]

#### to_disk(file_path)

Saves the serialized instance to a JSON file at the specified path.

This method converts the instance to a dictionary representation using to_dict(),
then writes it to disk as a formatted JSON file with UTF-8 encoding.

* **Parameters:**
  **file_path** ([`str`](https://docs.python.org/3/builtins/stdtypes.html#str) | [`pathlib.Path`](https://docs.python.org/3/library/pathlib.html#pathlib.Path)) – Path where the JSON file should be saved (must end with ‘.json’).
  Can be a string or a Path object.
* **Return type:**
  [`None`](https://docs.python.org/3/builtins/constants.html#None)
* **Returns:**
  None
* **Raises:**
  * [**ValueError**](https://docs.python.org/3/builtins/exceptions.html#ValueError) – If the file path doesn’t end with ‘.json’.
  * [**OSError**](https://docs.python.org/3/builtins/exceptions.html#OSError) – If the file cannot be written, e.g. its directory does not
    exist. The error is the one raised by the file operation, e.g.
    `FileNotFoundError` or `PermissionError`.

#### to_json()

Converts the object to its JSON string representation.

Serializes the object into a JSON-formatted string using the dictionary
representation provided by the to_dict() method.

* **Returns:**
  A JSON string representation of the object.
* **Return type:**
  [`str`](https://docs.python.org/3/builtins/stdtypes.html#str)

#### *property* unique_id *: [str](https://docs.python.org/3/builtins/stdtypes.html#str)*

Returns the ULID of the instance.

#### content *: [Annotated](https://docs.python.org/3/library/typing.html#typing.Annotated)[[dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Any](https://docs.python.org/3/library/typing.html#typing.Any)], [BeforeValidator](https://pydantic.dev/docs/validation/latest/api/pydantic/functional_validators/#pydantic.functional_validators.BeforeValidator)(func=\_validate_is_json_dict, json_schema_input_type=PydanticUndefined)]*

#### custom_data *: [Annotated](https://docs.python.org/3/library/typing.html#typing.Annotated)[[dict](https://docs.python.org/3/builtins/stdtypes.html#dict)[[str](https://docs.python.org/3/builtins/stdtypes.html#str), [Any](https://docs.python.org/3/library/typing.html#typing.Any)], [BeforeValidator](https://pydantic.dev/docs/validation/latest/api/pydantic/functional_validators/#pydantic.functional_validators.BeforeValidator)(func=\_validate_is_json_dict, json_schema_input_type=PydanticUndefined)]*
