API Reference

Every function in Pyro's 76 built-in modules.

math

Mathematical functions and constants.

math.PIPi constant (3.14159...)
math.EEuler's number (2.71828...)
math.TAUTau constant (6.28318...)
math.abs(x)Absolute value
math.sqrt(x)Square root
math.pow(x, y)Raise x to the power y
math.ceil(x)Round up to nearest integer
math.floor(x)Round down to nearest integer
math.round(x)Round to nearest integer
math.sin(x)Sine
math.cos(x)Cosine
math.tan(x)Tangent
math.log(x)Natural logarithm
math.log2(x)Base-2 logarithm
math.log10(x)Base-10 logarithm
math.exp(x)e raised to the power x
math.random()Random double in [0, 1)
math.randint(a, b)Random integer in [a, b]

io

File I/O operations.

io.read(path)Read entire file as string
io.write(path, content)Write string to file
io.append(path, content)Append string to file
io.readlines(path)Read file as list of lines
io.exists(path)Check if file exists
io.remove(path)Delete a file
io.mkdir(path)Create directory (recursive)
io.listdir(path)List directory entries

json

JSON parsing and serialization.

json.parse(str)Parse JSON string into JsonValue
json.stringify(value)Convert JsonValue to compact JSON string
json.pretty(value)Convert JsonValue to pretty-printed JSON

time

Time, dates, and scheduling.

time.now()Current time in milliseconds since epoch
time.millis()Alias for now()
time.seconds()Current time in seconds
time.format(ms, fmt)Format timestamp with strftime pattern
time.today()Today's date as YYYY-MM-DD
time.timestamp()Current datetime as YYYY-MM-DD HH:MM:SS
time.year()Current year
time.month()Current month (1-12)
time.day()Current day of month
time.hour()Current hour (0-23)
time.minute()Current minute
time.second()Current second
time.sleep(ms)Sleep for ms milliseconds
time.wait(ms)Alias for sleep()
time.date()Current datetime string
time.timer()Create a Timer with elapsed() and reset()
time.every(interval_ms, func, count)Run func repeatedly at interval
time.after(delay_ms, func)Run func after delay

os

Operating system utilities.

os.env(name)Get environment variable
os.setenv(name, val)Set environment variable
os.platform()Returns "linux", "macos", or "windows"
os.pid()Current process ID
os.cwd()Current working directory
os.cpus()Number of CPU cores

env

Environment variables and .env file loading.

env.get(name, default)Get env var with optional default
env.set(name, val)Set environment variable
env.unset(name)Remove environment variable
env.has(name)Check if env var exists
env.load(path)Load variables from .env file

re

Regular expressions.

re.match(pattern, str)Test if entire string matches pattern
re.has_match(pattern, str)Test if pattern found anywhere in string
re.search(pattern, str)Return first match or empty string
re.replace(pattern, replacement, text)Replace all matches
re.findall(pattern, str)Return all matches as list
re.find_all(pattern, text)Alias for findall()
re.split(pattern, str)Split string by regex pattern

fs

Filesystem operations.

fs.read(path)Read file contents
fs.write(path, data)Write data to file
fs.append(path, data)Append data to file
fs.copy(src, dst)Copy file or directory
fs.move(src, dst)Move/rename file or directory
fs.remove(path)Delete file or directory recursively
fs.mkdir(path)Create directories recursively
fs.list(path)List directory entries
fs.size(path)Get file size in bytes
fs.exists(path)Check if path exists
fs.is_file(path)Check if path is a regular file
fs.is_dir(path)Check if path is a directory

web

Web server framework with routing, middleware, and SSE.

web.app()Create a new web application
app.get(path, handler)Register GET route
app.post(path, handler)Register POST route
app.put(path, handler)Register PUT route
app.del(path, handler)Register DELETE route
app.use(middleware)Add middleware function
app.serve_static(prefix, dir)Serve static files from directory
app.listen(port)Start server on port
app.sse(path, generator, interval)Server-Sent Events endpoint
app.live(path, handler)Long-polling endpoint
web.html(body)Create HTML response
web.json(body)Create JSON response
web.text(body)Create text response
web.redirect(url)Create redirect response
web.bus()Create in-memory message bus

http

HTTP client (powered by libcurl).

http.get(url)HTTP GET request
http.post(url, body)HTTP POST request
http.put(url, body)HTTP PUT request
http.del(url)HTTP DELETE request
http.patch(url, body)HTTP PATCH request
http.request(method, url, body, headers)Custom HTTP request
http.download(url, path)Download file from URL

db

SQLite database (real SQLite via sqlite3).

db.connect(path)Open SQLite database connection
conn.exec(sql)Execute SQL statement
conn.query(sql)Query and return list of Row objects
conn.close()Close database connection
row.get(key)Get column value from Row by name

ai

AI/LLM integration (multi-provider, OpenAI-compatible). You must configure a provider before use.

ai.provider(name, key, model)Configure provider (nvidia, openai, gemini, groq, ollama, etc.) — required before any AI call
ai.chat(prompt, model)Send prompt to AI, get response
ai.chat(prompt, system, model)Chat with system prompt
ai.ask(question)Simple alias for chat()
ai.summarize(text, max_words)Summarize text
ai.translate(text, to)Translate text to target language
ai.classify(text, labels)Classify text into one of the labels
ai.extract(text, fields)Extract structured fields from text as JSON
ai.generate_code(description)Generate Pyro code from description
ai.conversation(system)Create multi-turn conversation
ai.set_key(key)Set API key
ai.set_model(model)Set default model
ai.set_url(url)Set API endpoint URL

ml

Machine learning: regression, classification, clustering.

ml.load_csv(path, target)Load CSV into Dataset
ml.split(dataset, ratio)Split dataset into train/test
ml.normalize(dataset)Min-max normalize features
ml.linear_regression(ds, lr, epochs)Train linear regression model
ml.logistic(ds, lr, epochs)Train logistic regression model
ml.knn_predict(train, test, k)K-nearest neighbors prediction
ml.kmeans(ds, k, max_iter)K-means clustering
ml.mse(pred, actual)Mean squared error
ml.mae(pred, actual)Mean absolute error
ml.r2_score(pred, actual)R-squared score
ml.accuracy(pred, actual)Classification accuracy

nn

Neural networks with backpropagation.

nn.sequential()Create sequential model
nn.dense(in, out, activation)Dense layer (relu, sigmoid, tanh, softmax)
nn.dropout(rate)Dropout regularization layer
nn.randn(rows, cols)Random tensor (He initialization)
model.add(layer)Add layer to model
model.compile(loss, lr)Set loss function and learning rate
model.fit(x, y, in_size, out_size, epochs, batch)Train the model
model.predict(input)Run inference
model.evaluate(x, y, out_size)Evaluate accuracy
model.summary()Print model architecture
model.save(path)Save model weights to file
nn.mse_loss(pred, target)Mean squared error loss
nn.cross_entropy_loss(pred, target)Cross-entropy loss

tensor

N-dimensional tensor operations.

tensor.zeros(r, c)Tensor of zeros
tensor.ones(r, c)Tensor of ones
tensor.eye(n)Identity matrix
tensor.random(r, c)Random tensor in [0, 1)
tensor.range(start, end, step)Tensor from range
tensor.sum(t)Sum of all elements
tensor.mean(t)Mean of all elements
tensor.min_val(t)Minimum element
tensor.max_val(t)Maximum element
tensor.std_dev(t)Standard deviation
tensor.sqrt(t)Element-wise square root
tensor.abs(t)Element-wise absolute value
tensor.exp(t)Element-wise exponential
tensor.log(t)Element-wise natural log
tensor.pow(t, p)Element-wise power
tensor.dot(a, b)Dot product
tensor.matmul(a, b)Matrix multiplication
tensor.transpose(t)Transpose matrix
tensor.det(t)Determinant (2x2 and 3x3)
tensor.inverse(t)Matrix inverse (2x2)

nlp

Natural language processing.

nlp.tokenize(text)Tokenize into words and punctuation
nlp.word_tokenize(text)Tokenize into alphabetic words only
nlp.sent_tokenize(text)Split text into sentences
nlp.lowercase(str)Convert to lowercase
nlp.remove_stopwords(text)Remove common stopwords
nlp.remove_punctuation(text)Strip punctuation characters
nlp.stem(word)Porter-like suffix stemmer
nlp.ngrams(text, n)Generate n-grams
nlp.word_count(text)Word frequency map
nlp.keywords(text, top)Extract top keywords by TF score
nlp.similarity(a, b)Cosine similarity between two texts
nlp.sentiment(text)Lexicon-based sentiment analysis
nlp.ner(text)Rule-based named entity recognition

cv

Computer vision and image processing.

cv.create(w, h, r, g, b)Create blank image
cv.load(path)Load PPM/PGM image
cv.save(img, path)Save image as PPM or BMP
cv.grayscale(img)Convert to grayscale
cv.resize(img, w, h)Resize image (nearest neighbor)
cv.flip(img, dir)Flip horizontal or vertical
cv.blur(img, radius)Box blur
cv.edges(img)Sobel edge detection
cv.threshold(img, thresh)Binary threshold
cv.brightness(img, delta)Adjust brightness
cv.invert(img)Invert colors
cv.crop(img, x, y, w, h)Crop region
cv.draw_rect(img, x, y, w, h, r, g, b)Draw rectangle outline
cv.fill_rect(img, x, y, w, h, r, g, b)Draw filled rectangle
cv.histogram(img)Pixel value distribution (256 bins)

viz

Rich SVG visualizations with dark theme and animation.

viz.bar_chart(labels, values, title, w, h)Animated bar chart
viz.line_chart(x, y, title, w, h)Line chart with gradient fill
viz.scatter(x, y, title, w, h)Animated scatter plot
viz.pie_chart(labels, values, title, w, h)Donut-style pie chart
viz.save(path, svg)Save SVG string to file

plot

Simple SVG chart generation.

plot.set_size(w, h)Set chart dimensions
plot.line(y, title, file)Line chart from y values
plot.bar(labels, values, title, file)Bar chart
plot.scatter(x, y, title, file)Scatter plot
plot.histogram(data, bins, title, file)Histogram
plot.heatmap(matrix, title, file)Heatmap from 2D matrix
plot.training_curve(loss, title, file)Training loss curve
plot.save(file)Save last chart to file
plot.show()Open last chart in browser

test

Unit testing and benchmarking.

test.run(name, fn)Run a named test
test.eq(got, expected)Assert equal
test.neq(got, expected)Assert not equal
test.ok(condition)Assert true
test.fail(msg)Force test failure
test.gt(a, b)Assert a > b
test.lt(a, b)Assert a < b
test.gte(a, b)Assert a >= b
test.lte(a, b)Assert a <= b
test.summary()Print test results summary
test.bench(name, iterations, fn)Benchmark a function

validate

Input validation and sanitization.

validate.email(str)Validate email address
validate.url(str)Validate URL (http/https)
validate.ip(str)Validate IPv4 address
validate.phone(str)Validate phone number
validate.number(str)Check if string is numeric
validate.alpha(str)Check if string is alphabetic
validate.alphanumeric(str)Check if string is alphanumeric
validate.empty(str)Check if string is empty
validate.not_empty(str)Check if string is not empty
validate.length(str, min, max)Check string length in range
validate.sanitize(str)HTML-escape special characters
validate.sql_safe(str)Escape SQL injection characters
validate.password_strength(str)Score password strength (0-6)

crypto

Cryptography via OpenSSL.

crypto.sha256(input)SHA-256 hash
crypto.sha512(input)SHA-512 hash
crypto.hmac_sha256(key, data)HMAC-SHA256
crypto.encrypt(plaintext, key)AES-256-GCM encryption
crypto.decrypt(ciphertext, key)AES-256-GCM decryption
crypto.random_token(length)Secure random alphanumeric token
crypto.random_bytes(length)Secure random bytes (hex)
crypto.uuid()Generate UUID v4
crypto.hash_password(password, iterations)PBKDF2 password hash
crypto.verify_password(password, hash)Verify password against hash
crypto.to_hex(data)Bytes to hex string
crypto.from_hex(hex)Hex string to bytes

csv

CSV reading and writing.

csv.read(path)Read CSV file into 2D string array
csv.parse(str)Parse CSV string
csv.stringify(data)Convert 2D array to CSV string
csv.write(path, data)Write 2D array to CSV file

data

DataFrame for tabular data analysis.

data.read(path)Load CSV into DataFrame
data.write(df, path)Save DataFrame to CSV
df.rows()Number of rows
df.cols()Number of columns
df.col(name)Get column as Series
df.head(n)Print first n rows
df.describe()Print column statistics
df.where(col, predicate)Filter rows
df.sort_by(col, ascending)Sort by column
df.select(cols)Select columns
df.groupby(key, agg_col, func)Group by column and aggregate
df.merge(other, on)Join two DataFrames
df.apply(col, func)Apply function to column
df.drop_duplicates()Remove duplicate rows
df.fillna(val)Fill empty cells
df.sample(n)Random sample of n rows
df.to_json()Convert to JSON string
df.rename(old, new)Rename column
df.drop(col)Drop column

random

Random number generation.

random.random()Random double in [0, 1)
random.randint(a, b)Random integer in [a, b]
random.uniform(a, b)Random double in [a, b)
random.seed(s)Seed the random generator
random.choice(list)Pick random element from list
random.sample(list, n)Pick n random elements
random.shuffle(list)Shuffle list in place

base64

Base64 encoding and decoding.

base64.encode(str)Encode string to Base64
base64.decode(str)Decode Base64 to string

uuid

UUID generation.

uuid.v4()Generate random UUID v4
uuid.nil_uuid()Return nil UUID (all zeros)
uuid.from_string(str)UUID from string (passthrough)

color

Terminal color formatting (ANSI escape codes).

color.red(str)Red text
color.green(str)Green text
color.yellow(str)Yellow text
color.blue(str)Blue text
color.magenta(str)Magenta text
color.cyan(str)Cyan text
color.bold(str)Bold text
color.dim(str)Dim text
color.underline(str)Underlined text
color.bg_red(str)Red background
color.bg_green(str)Green background

log

Leveled logging with timestamps.

log.set_level(level)Set minimum log level (trace/debug/info/warn/error/fatal)
log.trace(...)Log at TRACE level
log.debug(...)Log at DEBUG level
log.info(...)Log at INFO level
log.warn(...)Log at WARN level
log.error(...)Log at ERROR level
log.fatal(...)Log at FATAL level

path

Filesystem path manipulation.

path.join(a, b)Join two path segments
path.dirname(p)Parent directory
path.basename(p)File name component
path.extension(p)File extension
path.exists(p)Check if path exists
path.is_file(p)Check if path is a file
path.is_dir(p)Check if path is a directory
path.absolute(p)Get absolute path