Skip to content

Natural Language Create

NLQueryCreatorExecutor creates new records from natural language descriptions. It handles nested entity resolution, file processing, and transactional persistence.

Basic Usage

from amsdal_ml.ml_models.openai_model import OpenAIModel
from amsdal_ml.ml_retrievers.query_creator import NLQueryCreatorExecutor

llm = OpenAIModel()
llm.setup()

creator = NLQueryCreatorExecutor(llm=llm, queryset=Customer.objects.all())

analysis = await creator.analyze(
    'Create a new customer John Doe, email john@example.com, based in New York'
)
print(analysis.payloads)  # generated field values (list of CreatePayload)

results = await creator.execute(analysis)

How It Works

The create operation follows a 3-phase pipeline:

Phase 1: Resolution Strategy

The LLM analyzes the query and identifies:

  • Which fields to populate
  • Whether nested entities need to be resolved (e.g., "assign to the Sales department" requires finding the Department record)
  • Which fields are missing required values

Phase 2: Context Retrieval

For foreign key fields referencing existing records, the executor:

  • Searches the database for matching entities
  • Resolves references (e.g., "Sales department" → actual Department ID)
  • Reports missing references if no match is found

Phase 3: Payload Synthesis & Persistence

The executor:

  • Generates the complete CreatePayload with resolved field values
  • Validates required fields
  • Saves the record within a transaction
  • Returns the created records (list)

CreatePayload

The result includes a CreatePayload with:

Field Description
fields Dict of field names → values
missing_required List of required fields that couldn't be determined

Authorization

Pass a callback to check permissions before saving:

creator = NLQueryCreatorExecutor(
    llm=llm,
    queryset=Customer.objects.all(),
    on_before_save=my_auth_callback,
)

Document-Oriented Facade

NLQueryCreator returns serialized Document objects:

from amsdal_ml.ml_retrievers.query_creator import NLQueryCreator

creator = NLQueryCreator(llm=llm, queryset=Customer.objects.all())
analysis = await creator.analyze('Create customer Jane Smith, email jane@smith.com')
documents = await creator.invoke(analysis)