middleware.dataset_middleware
=============================
.. py:module:: middleware.dataset_middleware
.. autoapi-nested-parse::
LangChain middleware and tools for mutating and serializing an RDF dataset session.
Attributes
----------
.. autoapisummary::
middleware.dataset_middleware.logger
middleware.dataset_middleware.DATASET_SYSTEM_PROMPT
middleware.dataset_middleware.RESET_DATASET_TOOL_DESCRIPTION
middleware.dataset_middleware.LIST_TRIPLES_TOOL_DESCRIPTION
middleware.dataset_middleware.ADD_TRIPLES_TOOL_DESCRIPTION
middleware.dataset_middleware.REMOVE_TRIPLES_TOOL_DESCRIPTION
middleware.dataset_middleware.SERIALIZE_DATASET_TOOL_DESCRIPTION
middleware.dataset_middleware.CREATE_BLANK_NODE_TOOL_DESCRIPTION
middleware.dataset_middleware.RESET_DATASET_MISUSE_MESSAGE
middleware.dataset_middleware.NEW_BLANK_NODE_MISUSE_MESSAGE
middleware.dataset_middleware.REPEATED_ADD_TRIPLES_NOOP_MESSAGE
middleware.dataset_middleware.REPEATED_REMOVE_TRIPLES_NOOP_MESSAGE
Exceptions
----------
.. autoapisummary::
middleware.dataset_middleware.WhitelistViolation
Classes
-------
.. autoapisummary::
middleware.dataset_middleware.DatasetMiddlewareConfig
middleware.dataset_middleware.DatasetMiddleware
Module Contents
---------------
.. py:data:: logger
.. py:data:: DATASET_SYSTEM_PROMPT
:type: Final[str]
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""## Knowledge Base
- You have a knowledge base implemented as RDF.
- In the current middleware phase, the knowledge base is the default RDF graph only.
- Use the knowledge base when facts should persist across multiple reasoning steps.
- Use the knowledge base when semantics should be unambiguously represented.
- Use the knowledge base if you are expected to output RDF
- Prefer adding or correcting exact triples over resetting the entire knowledge base.
- Model facts in an atemporal, stable way when possible rather than storing transient phrasing as timeless truth.
- When asserting facts into the knowledge base, you SHOULD keep them grounded in the provided content unless the user explicitly asks for inference, extrapolation, or hypothesis generation.
- You SHOULD NOT assert uncertain facts as settled triples.
- You SHOULD prefer representing explicit source claims over designing additional ontology structure that the source does not require.
- When transforming unstructured content into RDF, you SHOULD prefer controlled vocabularies when they fit the source material and task.
- You SHOULD reuse established terms when they fit your intended meaning, and mint new local terms only when they are genuinely needed for a faithful representation.
- You SHOULD prefer the least ontology invention that still captures the grounded content.
- If you mint IRIs and the user does not specify a base IRI, you SHOULD use as the default base for minted IRIs.
- When presenting RDF to the user or serializing the knowledge base for inspection, you SHOULD prefer Turtle unless the user requests a different RDF serialization.
- SHOULD NOT mint IRIs if convention dictates that they be blank nodes (e.g., OWL 2 Class Restrictions).
- You SHOULD prefer a minted IRI over a blank node when there is an authoritative IRI base for that resource.
- When minting an IRI to represent a Class, Datatype, or Property, you MUST assign it a `rdfs:label` and define it using `rdfs:comment`.
- When minting a new local IRI for a Class or Datatype, the local name SHOULD be singular and use `PascalCase`, for example `ProjectReport`, `FieldObservation`, or `QualityRating`.
- When minting a new local IRI for a Property, the local name SHOULD use `camelCase`, for example `hasInventoryCode`, `recordedAtFacility`, or `reviewStatus`.
### Knowledge Base Tools
- `list_triples`: inspect the current triples in the knowledge base
- `add_triples`: Add triples to the knowledge base (idempotent)
- `remove_triples`: remove exact triples from the knowledge base
- `serialize_dataset`: render the current knowledge base as RDF text
- `reset_dataset`: clear the entire knowledge base
- `new_blank_node`: create an anonymous resource without an IRI
#### Knowledge Base Tool Guidance
- Prefer `add_triples` and `remove_triples` to correct triples/facts rather than using `reset_dataset`.
- When providing IRIs to dataset tools, you MAY use either canonical N3 form like `` or a bare RFC 3987 IRI like `urn:example:ProjectReport`.
- The middleware serializes IRIs back in canonical N3 form.
- When a predicate expects text such as `rdfs:label` or `rdfs:comment`, the object MUST be an RDF literal such as `"Project report"` or `"A short human-readable description."`.
- You SHOULD NOT include the same triple in multiple `add_triples` calls; `add_triples` is idempotent.
- If an `add_triples` call fails validation, you SHOULD correct the invalid triple or triples before retrying.
- You MAY retry with a smaller `add_triples` call if that helps isolate which triple is invalid.
- If an `add_triples` response sets `no_action_needed=true`, you MUST NOT submit any of those same triples again in this run,
whether in the same batch, a reordered batch, or a smaller subset.
- After such a response, you SHOULD continue with different triples that are still missing, inspect the dataset once if you are unsure what remains missing, or return your final answer if the dataset already reflects the RDF you intend to present.
- If a `remove_triples` response sets `no_action_needed=true`, you MUST NOT submit any of those same triples again in this run,
whether in the same batch, a reordered batch, or a smaller subset.
- After such a response, you SHOULD continue with a different specific dataset change, inspect the dataset once if you are unsure whether the correction is already reflected, or return your final answer if the dataset already reflects the RDF you intend to present.
- If an `add_triples` call is rejected as misuse or because a term violates vocabulary/policy constraints, you SHOULD follow the remediation advice in the tool response rather than retrying automatically.
- If you have already added the triples needed for a modeling step, you SHOULD NOT restate the same intention and repeat overlapping `add_triples` calls.
- Move to the next missing concept, inspect the dataset once if needed, or return your final answer.
- `serialize_dataset` is mainly a checkpoint or inspection tool, not a drafting loop.
- You SHOULD usually call `serialize_dataset` only when the graph is substantially complete or when one explicit inspection pass is needed to resolve uncertainty.
- After calling `serialize_dataset`, you SHOULD usually either return your final answer immediately or make a specific dataset change that the serialization revealed.
- You SHOULD NOT call `serialize_dataset` repeatedly without first changing the dataset or deciding to return your final answer.
- `serialize_dataset` does NOT add data, infer data, or improve data; changing serialization formats cannot improve an unchanged dataset.
- If a `serialize_dataset` response sets `is_empty=true`, the default graph is empty; changing formats will not add data, so your next step SHOULD be to add triples or return an explicitly empty-graph answer.
- If `serialize_dataset` reports that the dataset is unchanged since the previous serialization in that format, you MUST NOT call `serialize_dataset` again until you have changed the dataset.
- After such a response, you MUST either return your final answer immediately or make one or more specific dataset changes before using `serialize_dataset` again.
- Errors like `Value error, Could not parse RDF term` indicate that your RDF term syntax is incorrect.
- If the value is meant to be an IRI, first check whether it should be wrapped as `<...>` or corrected to a valid bare RFC 3987 IRI.
- If the value is meant to be plain text, encode it as an RDF literal such as `"Project report"` or `"A short human-readable description."`.
- Mutating knowledge base tool effects are persistent, cumulative, and idempotent.
- You MUST keep each `add_triples` call small enough to recover from a single validation error.
- You SHOULD prefer one subject per `add_triples` call.
- You SHOULD NOT mix many unrelated subjects in one `add_triples` call.
### Guidance for Modeling Facts
- You MAY incrementally build your dataset using multiple `add_triples` calls.
- You SHOULD prefer that each `add_triples` call completely describes one single concept or entity.
The following is an example of something that completely describes one single concept or entity.
The subject of this example is a minted class called `ProjectReport`, while the
supporting superclass reuses a standard vocabulary term.
```text/turtle
@prefix schema: .
a rdfs:Class ;
rdfs:label "Project report" ;
rdfs:comment "A written report that summarizes project work." ;
rdfs:subClassOf schema:CreativeWork .
```
- ` a rdfs:Class` is syntactic sugar for ` rdf:type rdfs:Class`.
- For `rdfs:label`, the object SHOULD usually be a short string literal such as `"Project report"`.
- For `rdfs:comment`, the object SHOULD usually be a descriptive string literal such as `"A written report that summarizes project work."`.
- Model facts in an atemporal, stable way when possible rather than storing transient phrasing as timeless truth.
- When asserting facts into the knowledge base, you SHOULD keep them grounded in the provided content unless the user explicitly asks for inference, extrapolation, or hypothesis generation.
- You SHOULD NOT assert uncertain facts as settled triples.
- You SHOULD avoid introducing helper abstractions, organizing concepts, or auxiliary relations unless they are genuinely needed to represent explicit grounded claims.
### Usage of IRIs and Blank Nodes
- When transforming unstructured content into RDF, you SHOULD prefer controlled vocabularies when they fit the source material and task.
- If you mint IRIs and the user does not specify a base IRI, you SHOULD use as the default base for minted IRIs.
- The fact that a local base IRI is available does NOT by itself justify minting a new local term.
- You SHOULD NOT mint IRIs if convention dictates that they be blank nodes (e.g., OWL 2 Class Restrictions).
- You SHOULD prefer a minted IRI over a blank node when there is an authoritative IRI base for that resource.
- When minting an IRI to represent a Class, Datatype, or Property, you MUST assign it a `rdfs:label` and define it using `rdfs:comment`.
- When minting a new local IRI for a Class or Datatype, the local name SHOULD be singular and use `PascalCase`, for example `ProjectReport`, `FieldObservation`, or `QualityRating`.
- When minting a new local IRI for a Property, the local name SHOULD use `camelCase`, for example `hasInventoryCode`, `recordedAtFacility`, or `reviewStatus`.
- If the current dataset already reflects the RDF you intend to present, you SHOULD serialize it at most once and then return your final answer rather than repeatedly re-serializing it.
"""
.. raw:: html
.. py:data:: RESET_DATASET_TOOL_DESCRIPTION
:type: Final[str]
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""Reset the RDF dataset to an empty state.
This permanently discards the current knowledge base state for the current session.
You MUST NOT use this tool as part of normal iterative drafting, exploration, or correction.
You MUST NOT call this tool repeatedly while deciding what triples to add.
You SHOULD prefer `remove_triples` or adding corrected triples when only part of the dataset is wrong.
Use this tool only when ALL of the following are true:
- the current dataset is broadly unusable or fundamentally mis-modeled
- targeted correction would be less clear or less reliable than starting over
- you are prepared to rebuild the dataset immediately after resetting it
After calling this tool, you SHOULD proceed directly to rebuilding the dataset rather than continuing to deliberate.
"""
.. raw:: html
.. py:data:: LIST_TRIPLES_TOOL_DESCRIPTION
:type: Final[str]
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""List all exact triples currently stored in the default RDF graph knowledge base.
Call this tool with no arguments when you need to inspect the current graph state before
adding, removing, or describing facts.
"""
.. raw:: html
.. py:data:: ADD_TRIPLES_TOOL_DESCRIPTION
:type: Final[str]
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""Add one or more exact RDF triples to the default RDF graph knowledge base.
Pass `triples` as a top-level argument containing one or more RDF triples.
IRI inputs MAY be given either in canonical N3 form like `` or
as bare RFC 3987 IRIs like `urn:example:ProjectReport`.
Literal text MUST be encoded as RDF literals like `"Project report"` or
`"A short human-readable description."`.
You SHOULD keep each call small and recoverable.
You SHOULD prefer one subject per call.
If the response sets `no_action_needed=true`, the requested triples are already
present and you MUST NOT submit any of those same triples again in this run,
whether in the same batch, a reordered batch, or a smaller subset.
After such a response, you SHOULD continue with different triples that are
still missing, inspect the dataset once if you are unsure what remains
missing, or return your final answer if the dataset already reflects the RDF
you intend to present.
Example arguments:
- `{"triples": [{"subject": "", "predicate": "", "object": ""Project report""}]}`
- `{"triples": [{"subject": "", "predicate": "", "object": ""A written report that summarizes project work.""}]}`
- `{"triples": [{"subject": "urn:example:ProjectReport", "predicate": "http://www.w3.org/2000/01/rdf-schema#subClassOf", "object": "https://schema.org/CreativeWork"}]}`
"""
.. raw:: html
.. py:data:: REMOVE_TRIPLES_TOOL_DESCRIPTION
:type: Final[str]
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""Remove one or more exact RDF triples from the default RDF graph knowledge base.
Pass `triples` as a top-level argument containing the exact triples to remove.
IRI inputs MAY be given either in canonical N3 form like `` or
as bare RFC 3987 IRIs like `urn:example:ProjectReport`.
Literal text MUST be encoded as RDF literals like `"Project report"` or
`"A short human-readable description."`.
If the response sets `no_action_needed=true`, the requested triples are already
absent and you MUST NOT submit any of those same triples again in this run,
whether in the same batch, a reordered batch, or a smaller subset.
After such a response, you SHOULD continue with a different specific dataset
change, inspect the dataset once if you are unsure whether the correction is
already reflected, or return your final answer if the dataset already reflects
the RDF you intend to present.
Example arguments:
- `{"triples": [{"subject": "", "predicate": "", "object": ""Project report""}]}`
- `{"triples": [{"subject": "urn:example:ProjectReport", "predicate": "http://www.w3.org/2000/01/rdf-schema#comment", "object": ""A written report that summarizes project work.""}]}`
"""
.. raw:: html
.. py:data:: SERIALIZE_DATASET_TOOL_DESCRIPTION
:type: Final[str]
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""Serialize the current default-graph knowledge base as RDF text.
Pass `format` as a top-level argument when you need a specific RDF serialization.
Use this mainly as a checkpoint when the graph is substantially complete or when
one inspection pass is needed to decide on a specific correction.
This tool does NOT modify, normalize, or improve the dataset; it only renders
the current graph state as RDF text.
Changing serialization formats cannot improve an unchanged dataset or add
missing triples.
If the response sets `is_empty=true`, the default graph is empty and another
serialization format will still be empty until you change the dataset.
If the serialization already reflects the graph you intend to present, the next
step SHOULD usually be to return your final answer.
If the serialization reveals a problem, the next step SHOULD usually be a
dataset change rather than another identical serialization request.
If `serialize_dataset` reports that the dataset is unchanged since the previous
serialization in that format, you MUST NOT call `serialize_dataset` again until
you have changed the dataset.
After such a response, you MUST either return your final answer immediately or
make one or more specific dataset changes before using `serialize_dataset`
again.
You SHOULD NOT repeatedly call `serialize_dataset` without first changing the
dataset or deciding to return your final answer.
Example arguments:
- `{"format": "turtle"}`
- `{"format": "trig"}`
"""
.. raw:: html
.. py:data:: CREATE_BLANK_NODE_TOOL_DESCRIPTION
:type: Final[str]
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""Create a new RDF Blank Node Identifier for use as the subject of object of a triple in your knowledge base.
The **NEED** for a RDF Blank Node as defined in RDF 1.1 Turtle ยง 2.6 RDF Blank Nodes (https://www.w3.org/TR/turtle/#BNodes) **MUST** precede its creation by this tool.
The entity MUST be necessary as the subject or object of a triple in your knowledge base.
You MUST use a Blank Node when conventions dictate. E.g.,:
- OWL 2 Class Restrictions
- RDF Collections
- SHACL Constraints
- Other structural conventions dictated by a specific standard, specification, or application.
Blank Nodes used outside of those conventions MUST also satisfy the following requirements:
- There MUST NOT be a meaningful IRI that can be associated with the entity.
- It MUST be outside your authority to mint a new IRI for this entity, or adding a new IRI reduces clarity.
- A Blank Node MUST be assigned one or more `rdf:type`s, one `rdfs:label`, and one definitional `rdfs:comment`.
- A Blank Node MUST NOT be used to represent vocabulary terms that you introduce.
"""
.. raw:: html
.. py:data:: RESET_DATASET_MISUSE_MESSAGE
:type: Final[str]
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""Misuse: `reset_dataset` was rejected.
Your dataset is empty. You have not yet used `add_triples` to add content.
Use `reset_dataset` only when the current dataset is broadly unusable and you are ready
to rebuild it immediately. Do not use it for iterative drafting, exploration, or
repeated correction while deciding what triples to add.
"""
.. raw:: html
.. py:data:: NEW_BLANK_NODE_MISUSE_MESSAGE
:type: Final[str]
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""Misuse: `new_blank_node` was rejected.
You have already requested 2 blank nodes, but have yet to use either in an `add_triples` call.
Use `new_blank_node` only when an anonymous RDF resource is genuinely required. Do not
use it as a placeholder while exploring, and do not use blank nodes for vocabulary
terms that you introduce. You must use your existing blank nodes before creating
new ones: {existing}
"""
.. raw:: html
.. py:data:: REPEATED_ADD_TRIPLES_NOOP_MESSAGE
:type: Final[str]
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""Misuse: repeated `add_triples` no-op was rejected.
Your previous `add_triples` call with these same triples was already satisfied.
You MUST NOT retry the same `add_triples` call unchanged. Either add different triples,
inspect the current dataset state, or return your final answer.
"""
.. raw:: html
.. py:data:: REPEATED_REMOVE_TRIPLES_NOOP_MESSAGE
:type: Final[str]
:value: Multiline-String
.. raw:: html
Show Value
.. code-block:: python
"""Misuse: repeated `remove_triples` no-op was rejected.
Your previous `remove_triples` call with these same triples was already satisfied.
You MUST NOT retry the same `remove_triples` call unchanged. Either make a
different specific dataset change, inspect the current dataset state, or return
your final answer.
"""
.. raw:: html
.. py:class:: DatasetMiddlewareConfig
Configuration for the dataset middleware surface.
.. py:attribute:: vocabulary_context
:type: middleware.vocabulary_configuration.VocabularyContext
.. py:attribute:: runtime
:type: middleware.shared_services.DatasetRuntime | None
:value: None
.. py:attribute:: run_term_telemetry
:type: middleware.shared_services.RunTermTelemetry | None
:value: None
.. py:class:: DatasetMiddleware(config: DatasetMiddlewareConfig)
Bases: :py:obj:`langchain.agents.middleware.AgentMiddleware`\ [\ :py:obj:`middleware.dataset_state.DatasetState`\ , :py:obj:`langchain.agents.middleware.types.ContextT`\ , :py:obj:`langchain.agents.middleware.types.ResponseT`\ ]
Dataset middleware for dataset-backed agent experiments.
Exposes default-graph operations (``add_triples``, ``serialize_dataset``,
``reset_dataset``) to the Research Agent and appends RDF-modeling guidance
to the system prompt.
When configured with a ``VocabularyContext``, the middleware also:
- **Enforces** namespace constraints by rejecting URIs from non-whitelisted
namespaces in ``add_triples``.
- **Enumerates** allowed vocabularies in the system prompt.
- **Suggests remediation** via Levenshtein-distance nearest matches for
closed-vocabulary near-misses.
.. py:attribute:: state_schema
The schema for state passed to the middleware nodes.
.. py:attribute:: vocabulary_context
:type: middleware.vocabulary_configuration.VocabularyContext
.. py:attribute:: runtime
:type: middleware.shared_services.DatasetRuntime
.. py:attribute:: tools
:type: collections.abc.Sequence[langchain.tools.BaseTool]
Additional tools registered by the middleware.
.. py:attribute:: whitelist
:type: middleware.namespaces.spec_whitelist.RestrictedNamespaceWhitelist
.. py:attribute:: run_term_telemetry
:type: middleware.shared_services.RunTermTelemetry
.. py:attribute:: config
.. py:method:: before_agent(state: middleware.dataset_state.DatasetState, runtime: Any) -> None
Dataset session state is owned by the middleware itself.
.. py:method:: after_model(state: middleware.dataset_state.DatasetState, runtime: Any) -> dict[str, Any] | langgraph.types.Command[Any] | None
Logic to run after the model is called.
:param state: The current agent state.
:param runtime: The runtime context.
:returns: Agent state updates to apply after model call.
.. py:method:: wrap_model_call(request: langchain.agents.middleware.types.ModelRequest[langchain.agents.middleware.types.ContextT], handler: collections.abc.Callable[[langchain.agents.middleware.types.ModelRequest[langchain.agents.middleware.types.ContextT]], langchain.agents.middleware.types.ModelResponse[langchain.agents.middleware.types.ResponseT]]) -> langchain.agents.middleware.types.ModelResponse[langchain.agents.middleware.types.ResponseT]
Append dataset guidance to the system prompt before model execution.
.. py:method:: awrap_model_call(request: langchain.agents.middleware.types.ModelRequest[langchain.agents.middleware.types.ContextT], handler: collections.abc.Callable[[langchain.agents.middleware.types.ModelRequest[langchain.agents.middleware.types.ContextT]], collections.abc.Awaitable[langchain.agents.middleware.types.ModelResponse[langchain.agents.middleware.types.ResponseT]]]) -> Any
:async:
Append dataset guidance to the system prompt before async model execution.
.. py:method:: wrap_tool_call(request: langchain.agents.middleware.types.ToolCallRequest, handler: collections.abc.Callable[[langchain.agents.middleware.types.ToolCallRequest], langchain_core.messages.ToolMessage | langgraph.types.Command[Any] | Any]) -> langchain_core.messages.ToolMessage | langgraph.types.Command[Any] | Any
Reject invalid dataset tool usage before calling the wrapped tool.
.. py:method:: list_triples() -> tuple[rdflib_reasoning.axiom.common.Triple, Ellipsis]
Return all exact triples currently present in the default graph.
.. py:method:: add_triples(triples: collections.abc.Iterable[rdflib_reasoning.axiom.common.Triple], context: rdflib_reasoning.axiom.common.ContextIdentifier | None = None) -> middleware.dataset_model.MutationResponse
Add exact triples to the default graph.
.. py:method:: remove_triples(triples: collections.abc.Iterable[rdflib_reasoning.axiom.common.Triple], context: rdflib_reasoning.axiom.common.ContextIdentifier | None = None) -> middleware.dataset_model.MutationResponse
Remove exact triples from the default graph.
.. py:method:: reset_dataset() -> middleware.dataset_model.MutationResponse
Reset the middleware-owned dataset session.
.. py:method:: serialize(format: Literal['trig', 'turtle', 'nt', 'n3'] = 'trig', context: rdflib_reasoning.axiom.common.ContextIdentifier | None = None) -> str
Serialize the default graph as RDF text.
.. py:exception:: WhitelistViolation(bad_term: rdflib.URIRef, result: middleware.namespaces.spec_whitelist.WhitelistResult)
Bases: :py:obj:`Exception`
Exception raised when a term is rejected by the whitelist.
.. py:attribute:: bad_term
.. py:attribute:: result