Primitives

Primitives are the atoms of the SymbolicAI API – small, orthogonal operations that can be freely combined to express very rich behaviour. Every Symbol automatically inherits them, so there is no import-gymnastics required: just create a symbol and start hacking.

This page gives you a hands-on overview of the most useful primitives that ship with symai. All examples are copy-pastable – open a Python REPL and play with them! The table of contents below mirrors the internal organisation of symai/ops/primitives.py, so if you ever need more detail you know where to look.

❗️NOTE❗️We will focus mostly on the semantic behaviour of the primitives, but you can also use them in syntactic mode, which is the default. Syntactic mode behaves like a normal Python value, unless otherwise specified. Be sure to check the examples below to see how the primitives behave.

Supported Primitives - SymbolicAI

This table summarizes all supported primitives, grouped by category. Use Python operators in either syntactic (Symbol(...).syn or Symbol(...)) or semantic (Symbol(...).sem or Symbol(..., semantic=True)) mode. Semantic mode invokes neuro-symbolic reasoning. Checkmark columns show which mode is supported; description explains the behavior.

Primitive/Operator
Category
Syntactic
Semantic
Description

.sem / .syn

Casting

Switches a symbol between syntactic (literal) and semantic (neuro-symbolic) behavior.

==

Comparison

Tests for equality. Syntactic: literal match. Semantic: fuzzy/conceptual equivalence (e.g. 'Hi' == 'Hello').

!=

Comparison

Tests for inequality. Syntactic: literal not equal. Semantic: non-equivalence or opposite concepts.

>

Comparison

Greater-than. Syntactic: numeric/string compare. Semantic: abstract comparison (e.g. 'hot' > 'warm').

<

Comparison

Less-than. Syntactic: numeric/string compare. Semantic: abstract ordering (e.g. 'cat' < 'dog').

>=

Comparison

Greater or equal. Syntactic or conceptual.

<=

Comparison

Less or equal. Syntactic or conceptual.

in

Membership

Syntactic: element in list/string. Semantic: membership by meaning (e.g. 'fruit' in ['apple', ...]).

~

Invert

Negation: Syntactic: logical NOT/bitwise invert. Semantic: conceptual inversion (e.g. 'True' ➔ 'False', 'I am happy.' ➔ 'Happiness is me.').

+

Arithmetic

Syntactic: numeric/string/list addition. Semantic: meaningful composition, blending, or conceptual merge.

-

Arithmetic

Syntactic: subtraction/negate. Semantic: replacement or conceptual opposition.

*

Arithmetic

Syntactic: multiplication/repeat. Semantic: expand or strengthen meaning.

@

Arithmetic

Sytactic: string concatenation.

/

Arithmetic

Syntactic: division. On strings, it splits the string based on delimiter (e.g. Symbol('a b') / ' ' -> ['a', 'b']))).

//

Arithmetic

Floor division.

%

Arithmetic

Modulo. Semantic: find remainder or part, can be used creatively over concepts.

**

Arithmetic

Power operation. Semantic: (hypernym or intensifier, depending on domain).

&

Logical/Bitwise

Syntactic: bitwise/logical AND. Semantic: logical conjunction, inference, e.g., context merge.

|

Logical/Bitwise

Syntactic: bitwise/logical OR. Semantic: conceptual alternative/option.

^

Logical/Bitwise

Syntactic: bitwise XOR. Semantic: exclusive option/concept distinction.

<<

Shift

Syntactic: left-shift (integers). Semantic: prepend or rearrange meaning/order.

>>

Shift

Syntactic: right-shift (integers). Semantic: append or rearrange meaning/order.

+=, -=, *=, /=, //=, %=, **=

In-place Arithmetic

In-place enhanced assignment, some syntactic and some semantic (see above).

&=, |=, ^=

In-place Logical

In-place enhanced bitwise/logical assignment, both syntactic and semantic.

.cast(type), .to(type)

Casting

Cast to a specified type (e.g., int, float, str).

.str(), .int(), .float(), .bool()

Casting

Cast to basic types.

.ast()

Casting

Parse a Python literal string into a native object.

symbol[index], symbol[start:stop]

Iteration

Get item or slice (list, tuple, dict, numpy array).

symbol[index] = value

Iteration

Set item or slice.

del symbol[index]

Iteration

Delete item or key.

.split(delimiter)

String Helper

Split a string or sequence into a list.

.join(delimiter)

String Helper

Join a list of strings into a string.

.startswith(prefix)

String Helper

Check if a string starts with given prefix (in both modes).

.endswith(suffix)

String Helper

Check if a string ends with given suffix (in both modes).

.equals(string, context?)

Comparison

Semantic/contextual equality beyond ==.

.contains(element)

Comparison

Semantic contains beyond in.

.isinstanceof(query)

Comparison

Semantic type checking.

.interpret(prompt, accumulate?)

Expression Handling

Interpret prompts/expressions

.get_results()

Expression Handling

Retrieve accumulated interpretation results.

.clear_results()

Expression Handling

Clear accumulated interpretation results.

.clean()

Data Handling

Clean text (remove extra whitespace, newlines, tabs).

.summarize(context?)

Data Handling

Summarize text (optionally with context).

.outline()

Data Handling

Generate outline from structured text.

.filter(criteria, include?)

Data Handling

Filter text by criteria (exclude/include).

.map(instruction, prompt?)

Data Handling

Semantic mapping over iterables.

.modify(changes)

Data Handling

Apply modifications according to prompt.

.replace(old, new)

Data Handling

Replace substrings in data.

.remove(information)

Data Handling

Remove specified text.

.include(information)

Data Handling

Include additional information.

.combine(information)

Data Handling

Combine with another text fragment.

.unique(keys?)

Uniqueness

Extract unique elements or entries.

.compose()

Uniqueness

Compose a coherent narrative.

.rank(measure?, order?)

Pattern Matching

Rank items by a given measure/order.

.extract(pattern)

Pattern Matching

Extract info matching a pattern.

.correct(context, exception)

Pattern Matching

Correct code/text based on prompt/exception.

.translate(language)

Pattern Matching

Translate text into another language.

.choice(cases, default)

Pattern Matching

Select best match from provided cases.

.query(context, prompt?, examples?)

Query Handling

Query structured data with a question or prompt.

.convert(format)

Query Handling

Convert data to specified format (YAML, XML, etc.).

.transcribe(modify)

Query Handling

Transcribe/reword text per instructions.

.analyze(exception, query?)

Execution Control

Analyze code execution and exceptions.

.execute(), .fexecute()

Execution Control

Execute code (with fallback).

.simulate()

Execution Control

Simulate code or process semantically.

.sufficient(query)

Execution Control

Check if information is sufficient.

.list(condition)

Execution Control

List items matching criteria.

.foreach(condition, apply)

Execution Control

Apply action to each element.

.stream(expr, token_ratio)

Execution Control

Stream-process large inputs.

.ftry(expr, retries)

Execution Control

Fault-tolerant execution with retries.

.dict(context, **kwargs)

Dict Handling

Convert text/list into a dict semantically.

.template(template, placeholder?)

Template Styling

Fill in placeholders in a template string.

.style(description, libraries?)

Template Styling

Style text/code (e.g., syntax highlighting).

.cluster(**clustering_kwargs?)

Data Clustering

Cluster data into groups semantically. (uses sklearn's DBSCAN)

.embed()

Embedding

Generate embeddings for text/data.

.embedding

Embedding

Retrieve embeddings as a numpy array.

.similarity(other, metric?, normalize?)

Embedding

Compute similarity between embeddings.

.distance(other, kernel?)

Embedding

Compute distance between embeddings.

.zip()

Embedding

Package id, embedding, query into tuples.

.open(path?)

IO Handling

Open a file and read its contents.

.input(message?)

IO Handling

Read user input interactively.

.save(path, serialize?, replace?)

Persistence

Save a symbol to file (pickle/text).

.load(path)

Persistence

Load a symbol from file.

.expand()

Persistence

Generate and attach code based on prompt.

.output()

Output Handling

Handle/capture output with handler.


1. Syntactic vs. Semantic Symbols

Symbol comes in two flavours:

  1. Syntactic – behaves like a normal Python value (string, list, int ‐ whatever you passed in).

  2. Semantic – is wired to the neuro-symbolic engine and therefore understands meaning and context.

Why is syntactic the default? Because Python operators (==, ~, &, …) are overloaded in symai. If we would immediately fire the engine for every bitshift or comparison, code would be slow and could produce surprising side-effects. Starting syntactic keeps things safe and fast; you opt-in to semantics only where you need them.

How to switch to the semantic view

  1. At creation time

  2. On demand with the .sem projection – the twin .syn flips you back:

Because the projections return the same underlying object with just a different behavioural coat, you can weave complex chains of syntactic and semantic operations on a single symbol.

2. Inversion and Negation

Inversion (~)

Negation (-)

3. Comparison Operations

Equality (==) and Inequality (!=)

The equality and inequality operators showcase one of the most powerful aspects of semantic symbols: conceptual equivalence rather than just literal matching.

Semantic Equality - Conceptual Equivalence

Semantic Inequality (!=)

The inequality operator works as the logical inverse of equality with conceptual understanding:

Advanced Contextual Equality - Custom Context Comparison

Beyond basic semantic equality, symbols support contextual comparison where you can specify the context for evaluation:

4. Membership Operations

The in Operator - Semantic Containment

The in operator demonstrates how semantic symbols can understand conceptual membership beyond literal substring or element matching.

Semantic Membership - Conceptual Containment

Enhanced Semantic Containment - Multi-Type Support

The contains() method provides advanced semantic containment that works across different data types:

5. Ordering and Comparison Operations

Greater Than (>) and Less Than (<) and Greater or Equal (>=) and Less or Equal (<=)

Semantic symbols can understand abstract ordering and magnitude relationships beyond numeric comparisons.

6. Shift Operations - Semantic Inclusion

Left Shift (<<) and Right Shift (>>)

Shift operations perform semantic inclusion by incorporating one symbol's content into another. The direction of the operator indicates where the inclusion occurs - left shift (<<) prepends content, while right shift (>>) appends content.

Semantic Inclusion Operations

Practical Use Cases

The shift operators provide a consistent way to indicate inclusion direction in high-level design:

  • Left Shift (<<): Use when you want to prepend, prioritize, or add context before

  • Right Shift (>>): Use when you want to append, extend, or add context after

This semantic approach allows for intuitive text manipulation and content combination while maintaining clear directional intent in your code design.

7. Bitwise and Logical Operations

Bitwise operators (&, |, ^) work with both numeric values and logical statements, providing mathematical bitwise operations for integers and logical inference for semantic symbols.

Bitwise AND (&) - Intersection and Logical Conjunction

Bitwise OR (|) - Union and Logical Disjunction

Bitwise XOR (^) - Exclusive OR

8. Arithmetic Operations

Basic arithmetic operations (+, -) provide both syntactic combination and semantic mathematical interpretation.

Addition (+) and Subtraction (-)

String Manipulation (@, /)

The following are syntactic sugar for string concatenation and splitting:

9. Indexing and Slicing Operations

The indexing and slicing operations (__getitem__, __setitem__, __delitem__) provide both syntactic data access and semantic key matching for dictionaries and lists.

Getting Items (symbol[key])

Setting Items (symbol[key] = value)

Deleting Items (del symbol[key])

10. Type Checking Operations

Semantic Type Validation (isinstanceof)

The isinstanceof() method provides semantic type checking that goes beyond traditional Python type checking to understand conceptual types:

11. Basic Symbolic Manipulations

The interpret() method provides a way to interpret and process symbolic expressions. Each step is atomic, meaning you can build complex interpretations by chaining them together.

Conditional Logic Processing

System Solving and Constraints

The interpret() method supports can accumulate steps into one symbol:

12. Data Processing and Manipulation Operations

Text Cleaning and Normalization (clean)

The clean() method normalizes whitespace, removes extra spaces, and standardizes text formatting:

Content Summarization (summarize)

The summarize() method creates concise summaries of longer content, with optional context for focused summarization:

Content Outlining (outline)

The outline() method extracts structure and key points from hierarchical content:

Content Filtering (filter)

The filter() method selectively includes or excludes content based on criteria:

Content Modification (modify)

The modify() method applies specified changes to content:

Text Replacement (replace)

The replace() method substitutes specific text with new content:

Content Removal (remove)

The remove() method eliminates specified content:

Content Addition (include, combine)

Both methods add content, with subtle differences in behavior:

Semantic Mapping (map)

The map operation applies semantic transformations to each element in an iterable based on natural language instructions. It preserves the container type and leaves non-matching elements unchanged.

Supported Types:

  • Strings: "abc""xyz" (character-by-character transformation)

  • Lists: [...][...]

  • Tuples: (...)(...)

  • Sets: {...}{...}

  • Dictionaries: {key: value}{key: transformed_value}

Note: For strings, transformations apply to individual characters and the result is joined back into a string. For dictionaries, transformations apply to values while preserving keys.

13. Pattern Matching and Intelligence Operations

Content Ranking (rank)

The rank() method orders content based on specified measures and criteria:

Pattern Extraction (extract)

The extract() method identifies and extracts specific patterns or information types:

Code Correction (correct)

The correct() method automatically fixes code errors based on exceptions:

Language Translation (translate)

The translate() method converts content between languages:

Multi-Choice Classification (choice)

The choice() method classifies content into predefined categories:

14. Query Handling

Querying

The query() method provides an easy interaction with an LLM based on the symbol value and a specified context.

Format Conversion (convert)

The convert() method transforms data between different formats:

Content Transcription (transcribe)

The transcribe() method modifies content style, tone, and formality:

15. Execution Control and Code Operations

Code Analysis (analyze)

The analyze() method provides insights into code issues and exceptions:

Code Execution (execute, fexecute)

Execute Python code and return comprehensive results:

Code Simulation (simulate)

The simulate() method provides step-by-step execution traces:

Information Sufficiency (sufficient)

Check if provided information is adequate for specific purposes:

List Processing (list, foreach)

Extract and process lists based on criteria:

Fault-Tolerant Execution (ftry)

Execute operations with retry logic and error handling:

16. Dictionary Handling Operations

Dictionary Creation (dict)

Convert various data types into structured dictionaries:

17. Template and Styling Operations

Template Substitution (template)

Replace placeholders in templates with Symbol values:

Content Styling (style)

Apply formatting and styling to content:

18. Data Clustering Operations

Semantic Clustering (cluster)

Group similar items based on semantic similarity:

Under the hood, the cluster method uses sklearn's HDBSCAN algorithm. You can pass as kwargs any parameter that is accepted by the HDBSCAN class, such as min_samples, min_cluster_size, metric, etc.

19. Embedding and Similarity Operations

Embedding Generation (embed, embedding)

Create vector embeddings for semantic operations:

Similarity and Distance Calculations

Calculate semantic similarity and distance between symbols:

Embedding Packaging (zip)

Format embeddings for storage and retrieval:

20. Input/Output Handling Operations

File Operations (open)

Read file contents into Symbol values:

User Input (input)

Handle interactive user input (requires user interaction):

21. Persistence Operations

Saving Symbols (save)

Persist Symbol data to files with various options:

Loading Symbols (load)

Load previously saved Symbol data:

Dynamic Function Expansion (expand)

Generate and attach new functions based on descriptions:

22. Output Processing Operations

Output Handling (output)

Process and format Symbol output with custom handlers:

Last updated