### Install NL2LTL Source: https://github.com/ibm/nl2ltl/blob/main/README.md Installation methods for the NL2LTL package. ```bash pip install nl2ltl ``` ```bash pip install git+https://github.com/IBM/nl2ltl.git ``` ```bash git clone https://github.com/IBM/nl2ltl.git cd nl2ltl pip install -e . ``` -------------------------------- ### Install NL2LTL and Dependencies Source: https://context7.com/ibm/nl2ltl/llms.txt Commands for installing the library from PyPI or source, including optional Rasa support and environment configuration. ```bash # Install from PyPI pip install nl2ltl # Install from source (main branch) pip install git+https://github.com/IBM/nl2ltl.git # Clone and install for development git clone https://github.com/IBM/nl2ltl.git cd nl2ltl pip install -e . # Install with Rasa engine support pip install -e ".[rasa]" # Set OpenAI API key for GPT engine export OPENAI_API_KEY=your_api_key ``` -------------------------------- ### Implement Custom NLU Engine Source: https://context7.com/ibm/nl2ltl/llms.txt Extend the Engine interface to create a custom NLU engine. This example uses a simple keyword-based approach for demonstration. Ensure your custom engine handles utterance translation and optionally applies filtering. ```python from typing import Dict from pylogics.syntax.base import Formula from pylogics.syntax.ltl import Atomic from nl2ltl.engines.base import Engine from nl2ltl.filters.base import Filter from nl2ltl.declare.declare import Existence, Response from nl2ltl import translate class MyCustomEngine(Engine): """Custom engine using a simple keyword-based approach.""" def __init__(self, custom_config: dict = None): """Initialize with optional configuration.""" self.config = custom_config or {} def translate(self, utterance: str, filtering: Filter = None) -> Dict[Formula, float]: """Transform a Natural Language utterance into LTLf formulas. :param utterance: a Natural Language utterance :param filtering: a custom filtering algorithm :return: dictionary mapping formulas to confidence scores """ result: Dict[Formula, float] = {} utterance_lower = utterance.lower() # Simple keyword extraction (replace with your NLU logic) entities = [] keywords = ["slack", "gmail", "salesforce", "trello", "jira"] for keyword in keywords: if keyword in utterance_lower: entities.append(Atomic(keyword)) # Pattern detection based on keywords if "whenever" in utterance_lower or "every time" in utterance_lower: if len(entities) >= 2: formula = Response(entities[0], entities[1]) result[formula] = 0.85 elif "eventually" in utterance_lower or len(entities) == 1: if entities: formula = Existence(entities[0]) result[formula] = 0.90 # Apply filtering if provided if filtering and result: symbols = {str(e): 1.0 for e in entities} return filtering.enforce(result, symbols) return result # Use custom engine with translate function my_engine = MyCustomEngine() utterance = "Whenever I receive a Gmail, send me a Slack" result = translate(utterance, my_engine) for formula, confidence in result.items(): print(f"Formula: {formula}") print(f"Confidence: {confidence}") ``` -------------------------------- ### Implement Custom Filter for Formula Selection Source: https://context7.com/ibm/nl2ltl/llms.txt Extend the Filter interface to create custom filtering logic for selecting LTL formulas. This example demonstrates a 'PriorityFilter' that boosts confidence for preferred patterns and a 'ThresholdFilter' to remove low-confidence formulas. ```python from typing import Dict from pylogics.syntax.base import Formula from nl2ltl.filters.base import Filter from nl2ltl.declare.declare import Response, ChainResponse from nl2ltl import translate from nl2ltl.engines.gpt.core import GPTEngine class PriorityFilter(Filter): """Custom filter that prioritizes certain temporal patterns.""" NAME = "priority" def __init__(self, preferred_patterns: list = None): """Initialize with preferred pattern types.""" self.preferred = preferred_patterns or [Response, ChainResponse] def enforce( self, output: Dict[Formula, float], entities: Dict[str, float], **kwargs ) -> Dict[Formula, float]: """Filter formulas based on priority and confidence threshold. :param output: dictionary of formulas to confidence scores :param entities: dictionary of entities to confidence scores :return: filtered dictionary of formulas """ if not output: return output # Separate preferred and non-preferred formulas preferred_formulas = {} other_formulas = {} for formula, confidence in output.items(): is_preferred = any(isinstance(formula, p) for p in self.preferred) if is_preferred: preferred_formulas[formula] = confidence * 1.1 # Boost confidence else: other_formulas[formula] = confidence # Return preferred formulas if any, otherwise return others if preferred_formulas: return preferred_formulas return other_formulas class ThresholdFilter(Filter): """Filter that removes formulas below a confidence threshold.""" NAME = "threshold" def __init__(self, min_confidence: float = 0.5): self.min_confidence = min_confidence def enforce( self, output: Dict[Formula, float], entities: Dict[str, float], **kwargs ) -> Dict[Formula, float]: """Keep only formulas above the confidence threshold.""" return {f: c for f, c in output.items() if c >= self.min_confidence} ``` -------------------------------- ### Build and Serve Documentation Source: https://github.com/ibm/nl2ltl/blob/main/README.md Commands to generate and preview the project documentation locally. ```bash mkdocs build ``` ```bash mkdocs serve ``` -------------------------------- ### Configure and Use GPTEngine Source: https://context7.com/ibm/nl2ltl/llms.txt Usage of the GPTEngine with custom model parameters and batch processing of utterances. ```python from nl2ltl import translate from nl2ltl.engines.gpt.core import GPTEngine, Models, OperationModes from nl2ltl.filters.simple_filters import BasicFilter # Initialize with default settings (GPT-3.5-turbo, chat mode) engine = GPTEngine() # Or customize the engine parameters engine = GPTEngine( model=Models.GPT4.value, # Use GPT-4 operation_mode=OperationModes.CHAT.value, # Chat completion mode temperature=0.5 # Control randomness ) # Available models: # - Models.GPT35_INSTRUCT = "gpt-3.5-turbo-instruct" # - Models.GPT35_TURBO = "gpt-3.5-turbo" # - Models.GPT4 = "gpt-4" # Translate various utterances utterances = [ "whenever I get a Slack, send a Gmail.", "Invite Sales employees.", "If a new Eventbrite is created, alert me through Slack.", "send me a Slack whenever I get a Gmail.", ] filter = BasicFilter() for utterance in utterances: result = translate(utterance, engine, filter) for formula, confidence in result.items(): print(f"Input: {utterance}") print(f"Formula: {formula}") print(f"English: {formula.to_english()}") print(f"Confidence: {confidence}\n") ``` -------------------------------- ### Set OpenAI API Key Source: https://github.com/ibm/nl2ltl/blob/main/README.md Environment variable configuration for GPT-based engines. ```bash export OPENAI_API_KEY=your_api_key ``` -------------------------------- ### Implement Custom Engine Source: https://github.com/ibm/nl2ltl/blob/main/README.md Create a custom translation engine by extending the Engine base class. ```python from nl2ltl.engines.base import Engine from pylogics.syntax.base import Formula class MyEngine(Engine): def translate(self, utterance: str, filtering: Filter) -> Dict[Formula, float]: """From NL to LTL.""" ``` ```python my_engine = MyEngine() ltl_formulas = translate(utterance, engine=my_engine) ``` -------------------------------- ### DECLARE Template to PPLTL Conversion Source: https://context7.com/ibm/nl2ltl/llms.txt Demonstrates converting DECLARE templates to Past LTL (PPLTL) format. The Existence template converts to PPLTL as Once(X). ```python from pylogics.syntax.ltl import Atomic from nl2ltl.declare.declare import Existence # Convert templates to Past LTL (PPLTL) existence = Existence(Atomic("slack")) print(f"PPLTL: {existence.to_ppltl()}") # Once(slack) ``` -------------------------------- ### Translate Utterance with Custom Filters Source: https://context7.com/ibm/nl2ltl/llms.txt Translate a natural language utterance into LTL using a GPTEngine and custom filters like PriorityFilter and ThresholdFilter. Ensure necessary filters are imported and configured before use. ```python from nl2ltl import translate from nl2ltl.engines.gpt.core import GPTEngine from nl2ltl.filters.simple_filters import PriorityFilter, ThresholdFilter from nl2ltl.declare.declare_templates import Response engine = GPTEngine() priority_filter = PriorityFilter(preferred_patterns=[Response]) threshold_filter = ThresholdFilter(min_confidence=0.7) utterance = "Send a Slack notification every time a Jira issue is created" result = translate(utterance, engine, priority_filter, threshold_filter) for formula, confidence in result.items(): print(f"Prioritized: {formula} (confidence: {confidence})") ``` -------------------------------- ### Configure and Use RasaEngine Source: https://context7.com/ibm/nl2ltl/llms.txt Usage of the RasaEngine for intent classification and entity extraction, including model training. ```python from nl2ltl import translate from nl2ltl.engines.rasa.core import RasaEngine from nl2ltl.filters.simple_filters import BasicFilter from pathlib import Path # Initialize with default pre-trained model engine = RasaEngine() # Or specify a custom trained model path custom_model_path = Path("/path/to/custom/model.tar.gz") engine = RasaEngine(model=custom_model_path) # Train a new Rasa model (static method) trained_model_path = RasaEngine.train( domain=Path("path/to/domain.yml"), config=Path("path/to/config.yml"), training=Path("path/to/nlu_training.yml") ) # Translate utterances using Rasa engine filter = BasicFilter() utterance = "Send a Slack message every time a high priority issue is created in Jira" result = translate(utterance, engine, filter) for formula, confidence in result.items(): print(f"Formula: {formula}") print(f"LTLf: {formula.to_ltlf()}") print(f"Confidence: {confidence}") ``` -------------------------------- ### Implement Custom Filter Source: https://github.com/ibm/nl2ltl/blob/main/README.md Create a custom filtering algorithm by extending the Filter base class. ```python from nl2ltl.filters.base import Filter from pylogics.syntax.base import Formula class MyFilter(Filter): def enforce( self, output: Dict[Formula, float], entities: Dict[str, float], **kwargs ) -> Dict[Formula, float]: """Filtering algorithm.""" ``` ```python my_engine = MyEngine() my_filter = MyFilter() ltl_formulas = translate(utterance, engine=my_engine, filter=my_filter) ``` -------------------------------- ### DECLARE Response Template Source: https://context7.com/ibm/nl2ltl/llms.txt The Response template models 'Whenever X happens, Y happens eventually afterward'. It is converted to LTLf as G(X -> F(Y)). ```python from pylogics.syntax.ltl import Atomic from nl2ltl.declare.declare import Response # Response: "Whenever X happens, Y happens eventually afterward" response = Response(Atomic("gmail"), Atomic("slack")) print(f"Response: {response.to_ltlf()}") # G(gmail -> F(slack)) print(f"English: {response.to_english()}") ``` -------------------------------- ### Format Translation Results with pretty() Source: https://context7.com/ibm/nl2ltl/llms.txt Use the pretty() utility function to format and display translation results, including the LTL formula, its English meaning, and confidence score. This function is useful for visualizing the output of the translate function. ```python from nl2ltl import translate from nl2ltl.engines.gpt.core import GPTEngine from nl2ltl.filters.simple_filters import BasicFilter from nl2ltl.engines.utils import pretty engine = GPTEngine() filter = BasicFilter() # Translate multiple utterances and display results utterances = [ "Eventually send me a Slack after receiving a Gmail", "Create a Trello card whenever a new Salesforce campaign starts", "Invite Sales employees to the event", ] for utterance in utterances: print(f"\nInput: {utterance}") result = translate(utterance, engine, filter) pretty(result) ``` -------------------------------- ### DECLARE Existence Template Source: https://context7.com/ibm/nl2ltl/llms.txt Use the Existence template to represent the pattern 'Eventually, X will happen'. It converts to LTLf as F(X). ```python from pylogics.syntax.ltl import Atomic from nl2ltl.declare.declare import Existence # Existence: "Eventually, X will happen" existence = Existence(Atomic("slack")) print(f"Existence: {existence.to_ltlf()}") # F(slack) print(f"English: {existence.to_english()}") # Eventually, slack will happen. ``` -------------------------------- ### Translate NL to LTL Source: https://github.com/ibm/nl2ltl/blob/main/README.md Basic usage of the translate function with a GPT engine. ```python from nl2ltl import translate from nl2ltl.engines.gpt.core import GPTEngine, Models from nl2ltl.filters.simple_filters import BasicFilter from nl2ltl.engines.utils import pretty engine = GPTEngine() filter = BasicFilter() utterance = "Eventually send me a Slack after receiving a Gmail" ltlf_formulas = translate(utterance, engine, filter) pretty(ltlf_formulas) ``` -------------------------------- ### BasicFilter - Simple Pass-Through Filter Source: https://context7.com/ibm/nl2ltl/llms.txt Use BasicFilter to retain all detected formulas without modification. It's useful when you want to process every possible translation. ```python from nl2ltl import translate from nl2ltl.engines.gpt.core import GPTEngine from nl2ltl.filters.simple_filters import BasicFilter engine = GPTEngine() filter = BasicFilter() # NAME = "basic" # BasicFilter returns all detected formulas without filtering utterance = "Create a Slack notification whenever a Gmail arrives" result = translate(utterance, engine, filter) # All matching formulas are returned for formula, confidence in result.items(): print(f"Pattern: {formula.SYMBOL}") print(f"Formula: {formula}") print(f"English: {formula.to_english()}") ``` -------------------------------- ### DECLARE RespondedExistence Template Source: https://context7.com/ibm/nl2ltl/llms.txt Use the RespondedExistence template to model 'If X happens, Y must happen (before or after)'. Its LTLf form is F(X) -> F(Y). ```python from pylogics.syntax.ltl import Atomic from nl2ltl.declare.declare import RespondedExistence # RespondedExistence: "If X happens, Y must happen (before or after)" responded = RespondedExistence(Atomic("trello"), Atomic("salesforce")) print(f"RespondedExistence: {responded.to_ltlf()}") # F(trello) -> F(salesforce) ``` -------------------------------- ### DECLARE Precedence Template Source: https://context7.com/ibm/nl2ltl/llms.txt Use the Precedence template to ensure 'Y can only happen if X happened before'. Its LTLf form is (!(Y) U X) | G(!(Y)). ```python from pylogics.syntax.ltl import Atomic from nl2ltl.declare.declare import Precedence # Precedence: "Y can only happen if X happened before" precedence = Precedence(Atomic("login"), Atomic("access")) print(f"Precedence: {precedence.to_ltlf()}") # (!(access) U login) | G(!(access)) ``` -------------------------------- ### DECLARE NotCoExistence Template Source: https://context7.com/ibm/nl2ltl/llms.txt The NotCoExistence template ensures that 'X and Y cannot both happen'. This translates to LTLf as F(X) -> !(F(Y)). ```python from pylogics.syntax.ltl import Atomic from nl2ltl.declare.declare import NotCoExistence # NotCoExistence: "X and Y cannot both happen" not_co = NotCoExistence(Atomic("approve"), Atomic("reject")) print(f"NotCoExistence: {not_co.to_ltlf()}") # F(approve) -> !(F(reject)) ``` -------------------------------- ### DECLARE Absence Template Source: https://context7.com/ibm/nl2ltl/llms.txt Use the Absence template to enforce that 'X will never happen'. This translates to LTLf as !(F(X)). ```python from pylogics.syntax.ltl import Atomic from nl2ltl.declare.declare import Absence # Absence: "X will never happen" abscence = Absence(Atomic("error")) print(f"Absence: {abscence.to_ltlf()}") # !(F(error)) ``` -------------------------------- ### DECLARE ExistenceTwo Template Source: https://context7.com/ibm/nl2ltl/llms.txt The ExistenceTwo template signifies that 'X will happen at least twice'. Its LTLf representation is F(X & X(F(X))). ```python from pylogics.syntax.ltl import Atomic from nl2ltl.declare.declare import ExistenceTwo # ExistenceTwo: "X will happen at least twice" existence_two = ExistenceTwo(Atomic("slack")) print(f"ExistenceTwo: {existence_two.to_ltlf()}") # F(slack & X(F(slack))) ``` -------------------------------- ### Translate Natural Language to LTL Source: https://context7.com/ibm/nl2ltl/llms.txt Basic usage of the translate function to convert an utterance into LTL formulas using a specified engine and filter. ```python from nl2ltl import translate from nl2ltl.engines.gpt.core import GPTEngine from nl2ltl.filters.simple_filters import BasicFilter from nl2ltl.engines.utils import pretty # Initialize the GPT engine and filter engine = GPTEngine() filter = BasicFilter() # Translate a natural language utterance utterance = "Eventually send me a Slack after receiving a Gmail" ltlf_formulas = translate(utterance, engine, filter) # Pretty print the results showing formula, English meaning, and confidence pretty(ltlf_formulas) ``` -------------------------------- ### DECLARE ChainResponse Template Source: https://context7.com/ibm/nl2ltl/llms.txt The ChainResponse template enforces that 'X must be directly followed by Y'. This translates to LTLf as G(X -> X(Y)). ```python from pylogics.syntax.ltl import Atomic from nl2ltl.declare.declare import ChainResponse # ChainResponse: "X must be directly followed by Y" chain = ChainResponse(Atomic("eventbrite"), Atomic("slack")) print(f"ChainResponse: {chain.to_ltlf()}") # G(eventbrite -> X(slack)) ``` -------------------------------- ### Academic Citations Source: https://github.com/ibm/nl2ltl/blob/main/README.md BibTeX entries for citing the NL2LTL package in ICAPS and AAAI publications. ```bibtex @inproceedings{icaps2023fc, author = {Francesco Fuggitti and Tathagata Chakraborti}, title = {{NL2LTL} -- A Python Package for Converting Natural Language ({NL}) Instructions to Linear Temporal Logic ({LTL}) Formulas}, booktitle = {{ICAPS}}, year = {2023}, note = {Best System Demonstration Award Runner-Up.}, url_code = {https://github.com/IBM/nl2ltl}, } ``` ```bibtex @inproceedings{aaai2023fc, author = {Francesco Fuggitti and Tathagata Chakraborti}, title = {{NL2LTL} -- A Python Package for Converting Natural Language ({NL}) Instructions to Linear Temporal Logic ({LTL}) Formulas}, booktitle = {{AAAI}}, year = {2023}, note = {System Demonstration.}, url_code = {https://github.com/IBM/nl2ltl}, } ``` -------------------------------- ### GreedyFilter - Conflict-Aware Greedy Filter Source: https://context7.com/ibm/nl2ltl/llms.txt Employ GreedyFilter to select the highest-scoring formula and discard conflicting or subsumed ones. This filter is ideal for scenarios requiring a single, best-fit translation. ```python from nl2ltl import translate from nl2ltl.engines.gpt.core import GPTEngine from nl2ltl.filters.simple_filters import GreedyFilter engine = GPTEngine() filter = GreedyFilter() # NAME = "greedy" # GreedyFilter algorithm: # 1. Add the highest scoring formula to the result set # 2. For each remaining formula: # - If it conflicts with the highest scoring formula, discard it # - If it subsumes the highest scoring formula, discard it # - Otherwise, add it to the result set utterance = "Every time there is a new Salesforce campaign, immediately create a Trello card" result = translate(utterance, engine, filter) # Only non-conflicting, non-subsumed formulas are returned for formula, confidence in result.items(): print(f"Best Match: {formula}") print(f"Confidence: {confidence}") ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.