A Python library for parallel LLM inference across providers, built on Polars DataFrames.
Polar Llama is a Python library that enables parallel inference calls to multiple Large Language Model providers through Polars dataframes. It streamlines batch processing of AI queries without serial request delays, making it ideal for data-intensive AI applications. 0.5.1 bridges the DSPy-style prompt optimizer onto the on-device MLX backend introduced in 0.5.0 — tuning instructions and few-shot demos against a local Gemma model, with no cloud calls and no Rust path involved.
Send multiple inference requests in parallel without waiting for individual completions
Leverages efficient Polars dataframe operations for request management
Signature / Predict / BootstrapFewShot / InstructionOptimizer — now tunable entirely on-device
Connects with OpenAI, Anthropic, Gemini, Groq, AWS Bedrock — and on-device MLX
Apple Silicon only, Python ≥ 3.10 — installs mlx + mlx-lm for the in-process local backend and the prompt-tuning bridge:
Get started with a simple example
polar_llama.local.make_local_inference_fn(model, ...) — drive the optimizer with on-device gemma-3n, no cloud or Rust path
make_local_inference_fn returns an inference_fn that drives polar_llama.optimize's DSPy-style Predict / BootstrapFewShot / InstructionOptimizer against on-device gemma-3n (mlx-lm). It reuses the same singleton-loaded weights as inference_local(engine="in_process") and applies the mlx-lm #1384 batched fix automatically.
POLAR_LLAMA_LOCAL_COLLAPSE=1 — ~2.8× faster on a full prompt-tuning schedule, at identical output
The collapsed-prefill primitive introduced in 0.5.0 (polar_llama/local/collapsed_prefill.py) is now exposed as an opt-in flag on inference_local(engine="in_process") itself — set POLAR_LLAMA_LOCAL_COLLAPSE=1 to share the common prompt prefix across rows (this is also the prompt-tuning bridge's default). Measured ~2.8× faster on a full prompt-tuning schedule (3.4× on a demo-laden eval) at identical, parity-verified output — the dominant speedup whenever rows share a long prefix, such as a shared system prompt or few-shot demos during tuning. Mutually exclusive with POLAR_LLAMA_LOCAL_KV_BITS — the quantized-KV path takes precedence when both are set.
MlxBatchEngine.get_model_and_tokenizer() reuses already-loaded weights instead of reloading per call
The prompt-tuning bridge and inference_local now share one code path for accessing the loaded model and tokenizer, so repeated Predict calls during an optimization run don't re-trigger a model load.
TypeError: the truth value of a Series is ambiguous
InstructionOptimizer no longer crashes when the proposer model returns the instructions field as a JSON array instead of a newline-delimited string — list/Series values are now flattened to newline-delimited text (polar_llama/optimize.py). This surfaces with small local models that emit {"instructions": [...]}.
Drive the optimizer with a local model via make_local_inference_fn — no API keys, no network
Emit tool calls as structured output, execute them batch-parallel, then synthesize a summary — three explicit turns, each an ordinary column
Batched generation via mlx-lm, no API keys, no network
Process customer feedback at scale
Polar Llama supports multiple LLM providers, plus on-device MLX
Default model: gpt-4o-mini
Default model: claude-opus-4-8
Default model: gemini-2.5-flash. Native system_instruction support and native JSON-schema structured outputs (response_json_schema).
Default model: llama-3.3-70b-versatile
Default model: us.anthropic.claude-haiku-4-5-20251001-v1:0. Requires AWS credentials configured; region resolves from AWS_REGION / AWS_DEFAULT_REGION before falling back to us-east-1.
No provider API, runs entirely on-device via mlx-lm; the prompt-tuning bridge shares its weights
Set up your API keys and overrides in a .env file:
Provider-native prompt caching shares a cached system prefix across rows (Anthropic cache_control, 5m/1h TTL):
Run tests with configured providers:
make_local_inference_fn), collapsed-prefill opt-in for inference_local (POLAR_LLAMA_LOCAL_COLLAPSE=1), singleton weight reuse, and an InstructionOptimizer fix for array-valued instructions.inference_local), collapsed prefix prefill, batched quantized KV cache, and the mlx-lm #1384 batched-RoPE fix for hybrid Gemma models.tools_to_response_model, execute_tool_calls), provider-native prompt caching, a DSPy-style prompt optimization engine (Signature, Predict, BootstrapFewShot, InstructionOptimizer), OPENAI_BASE_URL / ANTHROPIC_BASE_URL proxy support, and POLAR_LLAMA_MAX_CONCURRENCY.gpt-4-turbo and claude-3-opus-20240229 replaced), fixed Gemini and Bedrock structured-output auth, removed disabled TLS verification, and a significant performance pass (shared HTTP client, bounded concurrency, cached Bedrock credentials).embedding_async), similarity functions (cosine_similarity, dot_product, euclidean_distance), and HNSW approximate nearest neighbor search (knn_hnsw).Notable functions and the .llama namespace methods available as of 0.5.1
| Function / Method | Purpose |
|---|---|
| .llama.inference_local(model=..., engine=..., ...) | Local MLX generation (0.5.0) |
| polar_llama.local.make_local_inference_fn(model, ...) | Bridge the optimizer to on-device MLX, new in 0.5.1 |
| mcp_tools(transport) | Fetch tool definitions from an MCP server (tools/list) |
| tools_to_response_model(tools) | Build the structured-output emission schema for tool calls |
| execute_tool_calls(expr, transport=... | executor=...) | Run every emitted call of every row in parallel; failures are data |
| tool_results_to_message(expr) | Render a results column as a message for the synthesis turn |
| Signature / Predict / evaluate | Declare a task and run one batched inference per DataFrame |
| BootstrapFewShot / InstructionOptimizer | Mine few-shot demos / search instructions against labeled data |
| embedding_async(expr, provider=..., model=...) | Parallel embedding generation |
| cosine_similarity / dot_product / euclidean_distance | Rust-powered vector similarity metrics |
| knn_hnsw(query, corpus, k=...) | HNSW approximate nearest neighbor search |
| tag_taxonomy(expr, taxonomy, ...) | Taxonomy-based classification with reasoning and confidence |
Process large datasets with AI insights — sentiment analysis, classification, entity extraction with validated structured outputs
Batch-parallel tool-call emission and execution against an MCP server or Python callable, with every intermediate step an inspectable column
Bootstrap few-shot demos or search for better instructions entirely on-device via make_local_inference_fn — no API keys, no network
Generate embeddings and run HNSW nearest-neighbor search combined with taxonomy filtering for precise, context-aware retrieval
Licensed under MIT.
Questions or issues? Open one on GitHub.