API¶
The asplain project.
log = logging.getLogger(__name__)
module-attribute
¶
Foil
¶
Class to represent a foil, including the atoms in the foil model, the added and removed rules, and the reference atoms. Intended to save the result of obtaining foils
from_explanation_graph(foil_pg: str) -> Foil
classmethod
¶
Inspect the foil program graph to extract the foil model, added and removed rules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
foil_pg
|
str
|
The program graph of the foil model as a string of facts. |
required |
Returns:
| Type | Description |
|---|---|
Foil
|
A tuple containing three lists: |
Foil
|
|
Foil
|
|
Foil
|
|
print() -> None
¶
Print the foil model, added and removed rules.
Graph
¶
Representation of the explanation graph for the LLM
json: Dict[str, List[JsonNodeTagged] | List[JsonEdge] | List[JsonQuery]]
property
¶
A JSON representation of the explanation graph Returns: A JSON representation of the explanation graph as a python dictionary
assert_no_errors(symbols: List[Symbol], function_name: str = 'error') -> None
¶
Check for error symbols in the given list of symbols. If any error symbols are found, raise a RuntimeError with the error messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
List[Symbol]
|
A list of clingo.Symbol objects to check for errors. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If any error symbols are found. |
assumptions_as_ic(assumptions: Sequence[Tuple[str, bool]]) -> str
¶
colored(color: str, s: str) -> str
¶
Returns the string colored by the given color.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
color
|
str
|
A color name: GREY, BLUE, GREEN, YELLOW, RED |
required |
constants_to_args(constants: dict[str, str]) -> list[str]
¶
construct_contrastive(pg: str, query_prg: Optional[str]) -> str
¶
Constructs a contrastive explanation. Args: pg: The set of facts defining the reference program graph, foil program graph, foil model graph and optionally the reference model graph. query_prg: The query program string defined via query/2 facts. Returns: The contrastive explanation program graph as a string, which includes the facts for the input graphs in pg.
construct_program_graph(file_paths: List[str], prg: str = '', constants: Optional[dict[str, str]] = None, assumptions: Optional[List[Tuple[str, bool]]] = None, dynamic_tags_prg: Optional[str] = None, dynamic_tags_files: Optional[List[str]] = None) -> str
¶
Constructs a program graph Args: file_paths: List of file paths to load. prg: Additional program string to include. constants: Constants to pass to clingo. assumptions: Assumptions to include as integrity constraints. dynamic_tags_prg: Dynamic tags program string to generate tags. dynamic_tags_files: List of files to load for dynamic tags. Returns: The program graph as a string.
load_encoding(ctl: Control, encoding_name: str) -> None
¶
Load an encoding into the given clingo Control object.
reify_program(file_paths: List[str], prg: str = '', constants: Optional[dict[str, str]] = None) -> str
¶
Reifies a program. Args: file_paths: List of file paths to load. prg: Additional program string to include. constants: Constants to pass to clingo. Returns: The reified program as a string.
save_out(file_name: str, content: str) -> None
¶
Save content to a file if the logging level is low enough.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
file_path
|
The path to the file. |
required | |
content
|
str
|
The content to save. |
required |
set_foil_ctl(pg: str, query_prg: Optional[str] = None, cost_prg: Optional[str] = None, number_of_foils: int = 1) -> Control
¶
Constructs a foil to explain a query. Args: pg: The reference program graph string which might include facts for the reference model graph. query_prg: The query program string. cost_prg: The distance program string. number_of_foils: The number of foils to construct.
set_model_subgraphs_ctl(pg: str, ctl: Optional[Control] = None, model_symbols: Optional[List[str]] = None) -> Control
¶
Sets the control object for computing model subgraphs. Args: pg: The program graph string. ctl: Optional existing Control object. model_symbols: Optional list of model symbols. Returns: The Control object with the model subgraph encoding loaded and grounded
symbols_to_prg(symbols: List[Symbol]) -> str
¶
Converts a list of symbols to a program string.
app
¶
Module for Asplain application logic.
AsplainApp
¶
Bases: Application
Application for reification with extensions.
__init__(name: str, constants: Optional[dict[str, str]] = None, on_foil: Optional[Callable[[Foil], None]] = None) -> None
¶
Initialize AsplainApp.
main(control: Control, files: Sequence[str]) -> None
¶
Main entry point.
on_statistics(_: Any, accu: dict[str, Any]) -> None
¶
Callback to collect statistics after solving
parse_assumptions(value: str) -> bool
¶
Parse assumptions string
parse_file(attr_name: str, multi: bool = False) -> Callable[[str], bool]
¶
Parse file attributes
parse_llm_tag(value: str) -> bool
¶
Save the LLM tag for prompting in the object
parse_log_level(log_level: str) -> bool
¶
Parse log
parse_model(value: str) -> bool
¶
Save the model command line in the object
parse_number_explanations(value: str) -> bool
¶
Parse number of explanations
parse_pruning(value: str) -> bool
¶
Save the pruning method in the object
parse_query(value: str) -> bool
¶
Parse query string
print_model(model: Model, _) -> None
¶
Print the model's symbols.
register_options(options: ApplicationOptions) -> None
¶
Register command line options.
size_for_statistics(name: str, pg: str) -> dict[str, Any]
¶
Compute size statistics for a program graph.
llm
¶
models
¶
Backends to call different LLM APIs
AbstractModel
¶
Bases: ABC
Abstract base class for all language model wrappers
model_tag_key: str
abstractmethod
property
¶
Key to access the model tag from a ModelTag object
__init__(model_tag: ModelTag) -> None
¶
Abstract constructor
prompt(instructions_string: str, input_string: str) -> str
abstractmethod
async
¶
Prompts the language model with the given input string
prompt_template(template: Template) -> str
abstractmethod
async
¶
Explains an explanation graph
transform_output(unfiltered_output: str) -> str
abstractmethod
staticmethod
¶
Transforms the direct model output string
OpenAIModel
¶
Bases: AbstractModel
Wrapper class for the OpenAI model
Tag
dataclass
¶
Representation of a LLM model tag for different libraries
base
¶
Abstract base language model wrapper
AbstractModel
¶
Bases: ABC
Abstract base class for all language model wrappers
model_tag_key: str
abstractmethod
property
¶
Key to access the model tag from a ModelTag object
__init__(model_tag: ModelTag) -> None
¶
Abstract constructor
prompt(instructions_string: str, input_string: str) -> str
abstractmethod
async
¶
Prompts the language model with the given input string
prompt_template(template: Template) -> str
abstractmethod
async
¶
Explains an explanation graph
transform_output(unfiltered_output: str) -> str
abstractmethod
staticmethod
¶
Transforms the direct model output string
openai
¶
Wrapper for the OpenAI ChatGPT model
OpenAIModel
¶
Bases: AbstractModel
Wrapper class for the OpenAI model
utils
¶
Utility functions for asplain's LLM functionality
Graph
¶
Representation of the explanation graph for the LLM
json: Dict[str, List[JsonNodeTagged] | List[JsonEdge] | List[JsonQuery]]
property
¶
A JSON representation of the explanation graph Returns: A JSON representation of the explanation graph as a python dictionary
parse_llm_json_response(response: str) -> str
¶
Parses an LLM response in JSON format Args: response: A string containing the LLM response in JSON format. Returns: A string containing the natural language explanation.
graph
¶
Graph utilities for generating the explanation graph representation for the LLM
Graph
¶
Representation of the explanation graph for the LLM
json: Dict[str, List[JsonNodeTagged] | List[JsonEdge] | List[JsonQuery]]
property
¶
A JSON representation of the explanation graph Returns: A JSON representation of the explanation graph as a python dictionary
GraphEdge
dataclass
¶
Edge of the explanation graph
GraphNode
dataclass
¶
Node of the explanation graph
parsing
¶
Utility functions for parsing an LLM response
parse_llm_json_response(response: str) -> str
¶
Parses an LLM response in JSON format Args: response: A string containing the LLM response in JSON format. Returns: A string containing the natural language explanation.
predicates
¶
Clorm Predicates representing the explanation graph
Edge
¶
Bases: Predicate
Edge in the explanation graph
EdgeNodes
¶
Bases: Predicate
Nodes connected by an edge
Fired
¶
Bases: Predicate
Node that fired
Model
¶
Bases: Predicate
Association of a model node with a world
Node
¶
Bases: Predicate
Node in the explanation graph
Program
¶
Bases: Predicate
Association of a program node with a world
Query
¶
Bases: Predicate
Query node for the explanation
Rule
¶
Bases: Predicate
Representation of a program rule
Tag
¶
Bases: Predicate
Tag for a node
TagLabel
¶
Bases: Predicate
Node tag with a label
TagRuleFirstOrder
¶
Bases: Predicate
Node tag with the first order rule
TagRuleLocation
¶
Bases: Predicate
Node tag with the file location of a rule
pruning
¶
pruners
¶
Pruning methods for the explanation graph.
PruningException
¶
Bases: Exception
Exception that is thrown when the pruning of the explanation graph malfunctions
prune_changes(symbols: Iterable[clingo.Symbol]) -> List[clingo.Symbol]
¶
Prune methods to keep only changes between reference and foil models
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
Iterable[Symbol]
|
The symbols of the explanation graph to prune |
required |
prune_explanation_graph(symbols: Iterable[clingo.Symbol], method: PruningMethod, path_depth: int = 0) -> List[clingo.Symbol]
¶
Prune the explanation graph using the specified method.
prune_orphans(symbols: Iterable[clingo.Symbol]) -> List[clingo.Symbol]
¶
Prune method to remove orphan nodes, i.e., nodes that are not connected to any query. Args: symbols: The symbols of the explanation graph to prune
prune_path(symbols: Iterable[clingo.Symbol], depth: int = 0) -> List[clingo.Symbol]
¶
Pruning method finding a connecting path between changed rules and query in the graph with a maximum depth. Args: symbols: The symbols of the explanation graph to prune depth: The maximum depth of the path to keep
prune_path_undirected(symbols: Iterable[clingo.Symbol]) -> List[clingo.Symbol]
¶
Pruning method finding a connecting path between changed rules and query in the graph disregarding edge directions Args: symbols: The symbols of the explanation graph to prune
solve_program(symbols: Iterable[clingo.Symbol], files: Iterable[str]) -> List[clingo.Symbol]
¶
Solve the ASP program with the given symbols and files.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
Iterable[Symbol]
|
The symbols of the explanation graph to include in the program |
required |
files
|
Iterable[str]
|
The ASP files to load and include in the program |
required |
Returns:
| Type | Description |
|---|---|
List[Symbol]
|
The symbols of the solved model |
utils
¶
Utilities.
clingo
¶
Utilities for working with Clingo.
assert_no_errors(symbols: List[Symbol], function_name: str = 'error') -> None
¶
Check for error symbols in the given list of symbols. If any error symbols are found, raise a RuntimeError with the error messages.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
symbols
|
List[Symbol]
|
A list of clingo.Symbol objects to check for errors. |
required |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If any error symbols are found. |
assumptions_as_ic(assumptions: Sequence[Tuple[str, bool]]) -> str
¶
constants_to_args(constants: dict[str, str]) -> list[str]
¶
divide_space_string(space_string: str) -> tuple[list[str], list[str]]
¶
Divide the string into atoms to include and exclude
get_query_prg(query_include: List[Symbol], query_exclude: List[Symbol]) -> str
¶
Get the query program string for the given included and excluded query atoms.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query_include
|
List[Symbol]
|
A list of symbols to include in the query. |
required |
query_exclude
|
List[Symbol]
|
A list of symbols to exclude from the query. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A string representing the query as an ASP program. |
load_encoding(ctl: Control, encoding_name: str) -> None
¶
Load an encoding into the given clingo Control object.
model_symbols(model_pg_symbols: Sequence[Symbol], graph_name: str = 'ref') -> List[Symbol]
¶
Extract model symbols from the program graph string. Placeholder implementation.
parse_constants(arguments: list[str]) -> dict[str, str]
¶
Parse constants from the command line arguments. We need these constrants in both steps and since we can't fork the control object, we parse them here.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arguments
|
list
|
The command line arguments. |
required |
Returns:
list: A list of constants in the form
print_foil(foil_atoms: list[str], added_rules: list[str], removed_rules: list[str]) -> None
¶
symbols_to_prg(symbols: List[Symbol]) -> str
¶
Converts a list of symbols to a program string.
logging
¶
Setup project wide loggers.
This is a thin wrapper around Python's logging module. It supports colored logging.
colored(color: str, s: str) -> str
¶
Returns the string colored by the given color.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
color
|
str
|
A color name: GREY, BLUE, GREEN, YELLOW, RED |
required |
configure_logging(stream: TextIO, level: int, use_color: bool) -> None
¶
Configure application logging.
get_configured_logging_level() -> int | None
¶
Returns the logging level that was last set by configure_logging.
get_logger(name: str) -> logging.Logger
¶
Get a logger with the given name.
parser
¶
The command line parser for the project.
get_parser() -> ArgumentParser
¶
Return the parser for command line options.
viz
¶
Visualization utilities for Asplain.
viz_graph(pg: str, title: str, show: bool = False, name: str = 'graph', format: str = 'svg') -> dict[str, Any]
¶
Visualize the explanation graph using cligraph Args: pg: The program graph as a string of facts. This might define multiple graphs. title: Title of the graph. open: Whether to open the generated graph image. name: Name format for the output file.