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 valuemath.sqrt(x)Square rootmath.pow(x, y)Raise x to the power ymath.ceil(x)Round up to nearest integermath.floor(x)Round down to nearest integermath.round(x)Round to nearest integermath.sin(x)Sinemath.cos(x)Cosinemath.tan(x)Tangentmath.log(x)Natural logarithmmath.log2(x)Base-2 logarithmmath.log10(x)Base-10 logarithmmath.exp(x)e raised to the power xmath.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 stringio.write(path, content)Write string to fileio.append(path, content)Append string to fileio.readlines(path)Read file as list of linesio.exists(path)Check if file existsio.remove(path)Delete a fileio.mkdir(path)Create directory (recursive)io.listdir(path)List directory entriesjson
JSON parsing and serialization.
json.parse(str)Parse JSON string into JsonValuejson.stringify(value)Convert JsonValue to compact JSON stringjson.pretty(value)Convert JsonValue to pretty-printed JSONtime
Time, dates, and scheduling.
time.now()Current time in milliseconds since epochtime.millis()Alias for now()time.seconds()Current time in secondstime.format(ms, fmt)Format timestamp with strftime patterntime.today()Today's date as YYYY-MM-DDtime.timestamp()Current datetime as YYYY-MM-DD HH:MM:SStime.year()Current yeartime.month()Current month (1-12)time.day()Current day of monthtime.hour()Current hour (0-23)time.minute()Current minutetime.second()Current secondtime.sleep(ms)Sleep for ms millisecondstime.wait(ms)Alias for sleep()time.date()Current datetime stringtime.timer()Create a Timer with elapsed() and reset()time.every(interval_ms, func, count)Run func repeatedly at intervaltime.after(delay_ms, func)Run func after delayos
Operating system utilities.
os.env(name)Get environment variableos.setenv(name, val)Set environment variableos.platform()Returns "linux", "macos", or "windows"os.pid()Current process IDos.cwd()Current working directoryos.cpus()Number of CPU coresenv
Environment variables and .env file loading.
env.get(name, default)Get env var with optional defaultenv.set(name, val)Set environment variableenv.unset(name)Remove environment variableenv.has(name)Check if env var existsenv.load(path)Load variables from .env filere
Regular expressions.
re.match(pattern, str)Test if entire string matches patternre.has_match(pattern, str)Test if pattern found anywhere in stringre.search(pattern, str)Return first match or empty stringre.replace(pattern, replacement, text)Replace all matchesre.findall(pattern, str)Return all matches as listre.find_all(pattern, text)Alias for findall()re.split(pattern, str)Split string by regex patternfs
Filesystem operations.
fs.read(path)Read file contentsfs.write(path, data)Write data to filefs.append(path, data)Append data to filefs.copy(src, dst)Copy file or directoryfs.move(src, dst)Move/rename file or directoryfs.remove(path)Delete file or directory recursivelyfs.mkdir(path)Create directories recursivelyfs.list(path)List directory entriesfs.size(path)Get file size in bytesfs.exists(path)Check if path existsfs.is_file(path)Check if path is a regular filefs.is_dir(path)Check if path is a directoryweb
Web server framework with routing, middleware, and SSE.
web.app()Create a new web applicationapp.get(path, handler)Register GET routeapp.post(path, handler)Register POST routeapp.put(path, handler)Register PUT routeapp.del(path, handler)Register DELETE routeapp.use(middleware)Add middleware functionapp.serve_static(prefix, dir)Serve static files from directoryapp.listen(port)Start server on portapp.sse(path, generator, interval)Server-Sent Events endpointapp.live(path, handler)Long-polling endpointweb.html(body)Create HTML responseweb.json(body)Create JSON responseweb.text(body)Create text responseweb.redirect(url)Create redirect responseweb.bus()Create in-memory message bushttp
HTTP client (powered by libcurl).
http.get(url)HTTP GET requesthttp.post(url, body)HTTP POST requesthttp.put(url, body)HTTP PUT requesthttp.del(url)HTTP DELETE requesthttp.patch(url, body)HTTP PATCH requesthttp.request(method, url, body, headers)Custom HTTP requesthttp.download(url, path)Download file from URLdb
SQLite database (real SQLite via sqlite3).
db.connect(path)Open SQLite database connectionconn.exec(sql)Execute SQL statementconn.query(sql)Query and return list of Row objectsconn.close()Close database connectionrow.get(key)Get column value from Row by nameai
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 callai.chat(prompt, model)Send prompt to AI, get responseai.chat(prompt, system, model)Chat with system promptai.ask(question)Simple alias for chat()ai.summarize(text, max_words)Summarize textai.translate(text, to)Translate text to target languageai.classify(text, labels)Classify text into one of the labelsai.extract(text, fields)Extract structured fields from text as JSONai.generate_code(description)Generate Pyro code from descriptionai.conversation(system)Create multi-turn conversationai.set_key(key)Set API keyai.set_model(model)Set default modelai.set_url(url)Set API endpoint URLml
Machine learning: regression, classification, clustering.
ml.load_csv(path, target)Load CSV into Datasetml.split(dataset, ratio)Split dataset into train/testml.normalize(dataset)Min-max normalize featuresml.linear_regression(ds, lr, epochs)Train linear regression modelml.logistic(ds, lr, epochs)Train logistic regression modelml.knn_predict(train, test, k)K-nearest neighbors predictionml.kmeans(ds, k, max_iter)K-means clusteringml.mse(pred, actual)Mean squared errorml.mae(pred, actual)Mean absolute errorml.r2_score(pred, actual)R-squared scoreml.accuracy(pred, actual)Classification accuracynn
Neural networks with backpropagation.
nn.sequential()Create sequential modelnn.dense(in, out, activation)Dense layer (relu, sigmoid, tanh, softmax)nn.dropout(rate)Dropout regularization layernn.randn(rows, cols)Random tensor (He initialization)model.add(layer)Add layer to modelmodel.compile(loss, lr)Set loss function and learning ratemodel.fit(x, y, in_size, out_size, epochs, batch)Train the modelmodel.predict(input)Run inferencemodel.evaluate(x, y, out_size)Evaluate accuracymodel.summary()Print model architecturemodel.save(path)Save model weights to filenn.mse_loss(pred, target)Mean squared error lossnn.cross_entropy_loss(pred, target)Cross-entropy losstensor
N-dimensional tensor operations.
tensor.zeros(r, c)Tensor of zerostensor.ones(r, c)Tensor of onestensor.eye(n)Identity matrixtensor.random(r, c)Random tensor in [0, 1)tensor.range(start, end, step)Tensor from rangetensor.sum(t)Sum of all elementstensor.mean(t)Mean of all elementstensor.min_val(t)Minimum elementtensor.max_val(t)Maximum elementtensor.std_dev(t)Standard deviationtensor.sqrt(t)Element-wise square roottensor.abs(t)Element-wise absolute valuetensor.exp(t)Element-wise exponentialtensor.log(t)Element-wise natural logtensor.pow(t, p)Element-wise powertensor.dot(a, b)Dot producttensor.matmul(a, b)Matrix multiplicationtensor.transpose(t)Transpose matrixtensor.det(t)Determinant (2x2 and 3x3)tensor.inverse(t)Matrix inverse (2x2)nlp
Natural language processing.
nlp.tokenize(text)Tokenize into words and punctuationnlp.word_tokenize(text)Tokenize into alphabetic words onlynlp.sent_tokenize(text)Split text into sentencesnlp.lowercase(str)Convert to lowercasenlp.remove_stopwords(text)Remove common stopwordsnlp.remove_punctuation(text)Strip punctuation charactersnlp.stem(word)Porter-like suffix stemmernlp.ngrams(text, n)Generate n-gramsnlp.word_count(text)Word frequency mapnlp.keywords(text, top)Extract top keywords by TF scorenlp.similarity(a, b)Cosine similarity between two textsnlp.sentiment(text)Lexicon-based sentiment analysisnlp.ner(text)Rule-based named entity recognitioncv
Computer vision and image processing.
cv.create(w, h, r, g, b)Create blank imagecv.load(path)Load PPM/PGM imagecv.save(img, path)Save image as PPM or BMPcv.grayscale(img)Convert to grayscalecv.resize(img, w, h)Resize image (nearest neighbor)cv.flip(img, dir)Flip horizontal or verticalcv.blur(img, radius)Box blurcv.edges(img)Sobel edge detectioncv.threshold(img, thresh)Binary thresholdcv.brightness(img, delta)Adjust brightnesscv.invert(img)Invert colorscv.crop(img, x, y, w, h)Crop regioncv.draw_rect(img, x, y, w, h, r, g, b)Draw rectangle outlinecv.fill_rect(img, x, y, w, h, r, g, b)Draw filled rectanglecv.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 chartviz.line_chart(x, y, title, w, h)Line chart with gradient fillviz.scatter(x, y, title, w, h)Animated scatter plotviz.pie_chart(labels, values, title, w, h)Donut-style pie chartviz.save(path, svg)Save SVG string to fileplot
Simple SVG chart generation.
plot.set_size(w, h)Set chart dimensionsplot.line(y, title, file)Line chart from y valuesplot.bar(labels, values, title, file)Bar chartplot.scatter(x, y, title, file)Scatter plotplot.histogram(data, bins, title, file)Histogramplot.heatmap(matrix, title, file)Heatmap from 2D matrixplot.training_curve(loss, title, file)Training loss curveplot.save(file)Save last chart to fileplot.show()Open last chart in browsertest
Unit testing and benchmarking.
test.run(name, fn)Run a named testtest.eq(got, expected)Assert equaltest.neq(got, expected)Assert not equaltest.ok(condition)Assert truetest.fail(msg)Force test failuretest.gt(a, b)Assert a > btest.lt(a, b)Assert a < btest.gte(a, b)Assert a >= btest.lte(a, b)Assert a <= btest.summary()Print test results summarytest.bench(name, iterations, fn)Benchmark a functionvalidate
Input validation and sanitization.
validate.email(str)Validate email addressvalidate.url(str)Validate URL (http/https)validate.ip(str)Validate IPv4 addressvalidate.phone(str)Validate phone numbervalidate.number(str)Check if string is numericvalidate.alpha(str)Check if string is alphabeticvalidate.alphanumeric(str)Check if string is alphanumericvalidate.empty(str)Check if string is emptyvalidate.not_empty(str)Check if string is not emptyvalidate.length(str, min, max)Check string length in rangevalidate.sanitize(str)HTML-escape special charactersvalidate.sql_safe(str)Escape SQL injection charactersvalidate.password_strength(str)Score password strength (0-6)crypto
Cryptography via OpenSSL.
crypto.sha256(input)SHA-256 hashcrypto.sha512(input)SHA-512 hashcrypto.hmac_sha256(key, data)HMAC-SHA256crypto.encrypt(plaintext, key)AES-256-GCM encryptioncrypto.decrypt(ciphertext, key)AES-256-GCM decryptioncrypto.random_token(length)Secure random alphanumeric tokencrypto.random_bytes(length)Secure random bytes (hex)crypto.uuid()Generate UUID v4crypto.hash_password(password, iterations)PBKDF2 password hashcrypto.verify_password(password, hash)Verify password against hashcrypto.to_hex(data)Bytes to hex stringcrypto.from_hex(hex)Hex string to bytescsv
CSV reading and writing.
csv.read(path)Read CSV file into 2D string arraycsv.parse(str)Parse CSV stringcsv.stringify(data)Convert 2D array to CSV stringcsv.write(path, data)Write 2D array to CSV filedata
DataFrame for tabular data analysis.
data.read(path)Load CSV into DataFramedata.write(df, path)Save DataFrame to CSVdf.rows()Number of rowsdf.cols()Number of columnsdf.col(name)Get column as Seriesdf.head(n)Print first n rowsdf.describe()Print column statisticsdf.where(col, predicate)Filter rowsdf.sort_by(col, ascending)Sort by columndf.select(cols)Select columnsdf.groupby(key, agg_col, func)Group by column and aggregatedf.merge(other, on)Join two DataFramesdf.apply(col, func)Apply function to columndf.drop_duplicates()Remove duplicate rowsdf.fillna(val)Fill empty cellsdf.sample(n)Random sample of n rowsdf.to_json()Convert to JSON stringdf.rename(old, new)Rename columndf.drop(col)Drop columnrandom
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 generatorrandom.choice(list)Pick random element from listrandom.sample(list, n)Pick n random elementsrandom.shuffle(list)Shuffle list in placebase64
Base64 encoding and decoding.
base64.encode(str)Encode string to Base64base64.decode(str)Decode Base64 to stringuuid
UUID generation.
uuid.v4()Generate random UUID v4uuid.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 textcolor.green(str)Green textcolor.yellow(str)Yellow textcolor.blue(str)Blue textcolor.magenta(str)Magenta textcolor.cyan(str)Cyan textcolor.bold(str)Bold textcolor.dim(str)Dim textcolor.underline(str)Underlined textcolor.bg_red(str)Red backgroundcolor.bg_green(str)Green backgroundlog
Leveled logging with timestamps.
log.set_level(level)Set minimum log level (trace/debug/info/warn/error/fatal)log.trace(...)Log at TRACE levellog.debug(...)Log at DEBUG levellog.info(...)Log at INFO levellog.warn(...)Log at WARN levellog.error(...)Log at ERROR levellog.fatal(...)Log at FATAL levelpath
Filesystem path manipulation.
path.join(a, b)Join two path segmentspath.dirname(p)Parent directorypath.basename(p)File name componentpath.extension(p)File extensionpath.exists(p)Check if path existspath.is_file(p)Check if path is a filepath.is_dir(p)Check if path is a directorypath.absolute(p)Get absolute path