LLM Integration
Patterns for integrating LLMs into production applications: tool use, streaming, local inference, and fine-tuning. Each category has individual rule files in rules/ loaded on-demand.
Quick Reference
| Category |
Rules |
Impact |
When to Use |
| Function Calling |
3 |
CRITICAL |
Tool definitions, parallel execution, input validation |
| Streaming |
3 |
HIGH |
SSE endpoints, structured streaming, backpressure handling |
| Local Inference |
3 |
HIGH |
Ollama setup, model selection, GPU optimization |
| Fine-Tuning |
3 |
HIGH |
LoRA/QLoRA training, dataset preparation, evaluation |
| Context Optimization |
2 |
HIGH |
Window management, compression, caching, budget scaling |
| Evaluation |
2 |
HIGH |
LLM-as-judge, RAGAS metrics, quality gates, benchmarks |
| Prompt Engineering |
4 |
HIGH |
CoT, few-shot, versioning, DSPy optimization, ReAct, cost optimization |
Total: 20 rules across 7 categories
Quick Start
# Function calling: strict mode tool definition
tools = [{
"type": "function",
"function": {
"name": "search_documents",
"description": "Search knowledge base",
"strict": True,
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"},
"limit": {"type": "integer", "description": "Max results"}
},
"required": ["query", "limit"],
"additionalProperties": False
}
}
}]
# Streaming: SSE endpoint with FastAPI
@app.get("/chat/stream")
async def stream_chat(prompt: str):
async def generate():
async for token in async_stream(prompt):
yield {"event": "token", "data": token}
yield {"event": "done", "data": ""}
return EventSourceResponse(generate())
# Local inference: Ollama with LangChain
llm = ChatOllama(
model="deepseek-r1:70b",
base_url="http://localhost:11434",
temperature=0.0,
num_ctx=32768,
)
# Fine-tuning: QLoRA with Unsloth
model, tokenizer = FastLanguageModel.from_pretrained(
model_name="unsloth/Meta-Llama-3.1-8B",
max_seq_length=2048, load_in_4bit=True,
)
model = FastLanguageModel.get_peft_model(model, r=16, lora_alpha=32)
Function Calling
Enable LLMs to use external tools and return structured data. Use strict mode schemas (2026 best practice) for reliability. Limit to 5-15 tools per request, validate all inputs with Pydantic/Zod, and return errors as tool results.
calling-tool-definition.md -- Strict mode schemas, OpenAI/Anthropic formats, LangChain binding
calling-parallel.md -- Parallel tool execution, asyncio.gather, strict mode constraints
calling-validation.md -- Input validation, error handling, tool execution loops
Streaming
Deliver LLM responses in real-time for better UX. Use SSE for web, WebSocket for bidirectional. Handle backpressure with bounded queues.
streaming-sse.md -- FastAPI SSE endpoints, frontend consumers, async iterators
streaming-structured.md -- Streaming with tool calls, partial JSON parsing, chunk accumulation
streaming-backpressure.md -- Backpressure handling, bounded buffers, cancellation
Local Inference
Run LLMs locally with Ollama for cost savings (93% vs cloud), privacy, and offline development. Pre-warm models, use provider factory for cloud/local switching.
local-ollama-setup.md -- Installation, model pulling, environment configuration
local-model-selection.md -- Model comparison by task, hardware profiles, quantization
local-gpu-optimization.md -- Apple Silicon tuning, keep-alive, CI integration
Fine-Tuning
Customize LLMs with parameter-efficient techniques. Fine-tune ONLY after exhausting prompt engineering and RAG. Requires 1000+ quality examples.
tuning-lora.md -- LoRA/QLoRA configuration, Unsloth training, adapter merging
tuning-dataset-prep.md -- Synthetic data generation, quality validation, deduplication
tuning-evaluation.md -- DPO alignment, evaluation metrics, anti-patterns
Context Optimization
Manage context windows, compression, and attention-aware positioning. Optimize for tokens-per-task.
context-window-management.md -- Five-layer architecture, anchored summarization, compression triggers
context-caching.md -- Just-in-time loading, budget scaling, probe evaluation, CC 2.1.32+
Evaluation
Evaluate LLM outputs with multi-dimension scoring, quality gates, and benchmarks.
evaluation-metrics.md -- LLM-as-judge, RAGAS metrics, hallucination detection
evaluation-benchmarks.md -- Quality gates, batch evaluation, pairwise comparison
Prompt Engineering
Design, version, and optimize prompts for production LLM applications.
prompt-design.md -- Chain-of-Thought, few-shot learning, pattern selection guide
prompt-testing.md -- Langfuse versioning, DSPy optimization, A/B testing, self-consistency
prompt-react-pattern.md -- ReAct loop for tool-using agents, thought-action-observation format
prompt-optimization.md -- Token reduction, cost optimization, model tiering, prompt spec format
Key Decisions
| Decision |
Recommendation |
| Tool schema mode |
strict: true (2026 best practice) |
| Tool count |
5-15 max per request |
| Streaming protocol |
SSE for web, WebSocket for bidirectional |
| Buffer size |
50-200 tokens |
| Local model (reasoning) |
deepseek-r1:70b |
| Local model (coding) |
qwen2.5-coder:32b |
| Fine-tuning approach |
LoRA/QLoRA (try prompting first) |
| LoRA rank |
16-64 typical |
| Training epochs |
1-3 (more risks overfitting) |
| Context compression |
Anchored iterative (60-80%) |
| Compress trigger |
70% utilization, target 50% |
| Judge model |
GPT-5.2-mini or Haiku 4.5 |
| Quality threshold |
0.7 production, 0.6 drafts |
| Few-shot examples |
3-5 diverse, representative |
| Prompt versioning |
Langfuse with labels |
| Auto-optimization |
DSPy MIPROv2 |
Related Skills
ork:rag-retrieval -- Embedding patterns, when RAG is better than fine-tuning
agent-loops -- Multi-step tool use with reasoning
llm-evaluation -- Evaluate fine-tuned and local models
langfuse-observability -- Track training experiments
Capability Details
function-calling
Keywords: tool, function, define tool, tool schema, function schema, strict mode, parallel tools
Solves:
- Define tools with clear descriptions and strict schemas
- Execute tool calls in parallel with asyncio.gather
- Validate inputs and handle errors in tool execution loops
streaming
Keywords: streaming, SSE, Server-Sent Events, real-time, backpressure, token stream
Solves:
- Stream LLM tokens via SSE endpoints
- Handle tool calls within streams
- Manage backpressure with bounded queues
local-inference
Keywords: Ollama, local, self-hosted, model selection, GPU, Apple Silicon
Solves:
- Set up Ollama for local LLM inference
- Select models based on task and hardware
- Optimize GPU usage and CI integration
fine-tuning
Keywords: LoRA, QLoRA, fine-tune, DPO, synthetic data, PEFT, alignment
Solves:
- Configure LoRA/QLoRA for parameter-efficient training
- Generate and validate synthetic training data
- Align models with DPO and evaluate results
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: llm-integration3description: LLM integration patterns for function calling, streaming responses, local inference with Ollama, and fine-tuning customization. Use when implementing tool use, SSE streaming, local model deployment, LoRA/QLoRA fine-tuning, or multi-provider LLM APIs. Use when this capability is needed.4---56# LLM Integration78Patterns for integrating LLMs into production applications: tool use, streaming, local inference, and fine-tuning. Each category has individual rule files in `rules/` loaded on-demand.910## Quick Reference1112| Category | Rules | Impact | When to Use |13|----------|-------|--------|-------------|14| [Function Calling](#function-calling) | 3 | CRITICAL | Tool definitions, parallel execution, input validation |15| [Streaming](#streaming) | 3 | HIGH | SSE endpoints, structured streaming, backpressure handling |16| [Local Inference](#local-inference) | 3 | HIGH | Ollama setup, model selection, GPU optimization |17| [Fine-Tuning](#fine-tuning) | 3 | HIGH | LoRA/QLoRA training, dataset preparation, evaluation |18| [Context Optimization](#context-optimization) | 2 | HIGH | Window management, compression, caching, budget scaling |19| [Evaluation](#evaluation) | 2 | HIGH | LLM-as-judge, RAGAS metrics, quality gates, benchmarks |20| [Prompt Engineering](#prompt-engineering) | 4 | HIGH | CoT, few-shot, versioning, DSPy optimization, ReAct, cost optimization |2122**Total: 20 rules across 7 categories**2324## Quick Start2526```python27# Function calling: strict mode tool definition28tools = [{29 "type": "function",30 "function": {31 "name": "search_documents",32 "description": "Search knowledge base",33 "strict": True,34 "parameters": {35 "type": "object",36 "properties": {37 "query": {"type": "string", "description": "Search query"},38 "limit": {"type": "integer", "description": "Max results"}39 },40 "required": ["query", "limit"],41 "additionalProperties": False42 }43 }44}]45```4647```python48# Streaming: SSE endpoint with FastAPI49@app.get("/chat/stream")50async def stream_chat(prompt: str):51 async def generate():52 async for token in async_stream(prompt):53 yield {"event": "token", "data": token}54 yield {"event": "done", "data": ""}55 return EventSourceResponse(generate())56```5758```python59# Local inference: Ollama with LangChain60llm = ChatOllama(61 model="deepseek-r1:70b",62 base_url="http://localhost:11434",63 temperature=0.0,64 num_ctx=32768,65)66```6768```python69# Fine-tuning: QLoRA with Unsloth70model, tokenizer = FastLanguageModel.from_pretrained(71 model_name="unsloth/Meta-Llama-3.1-8B",72 max_seq_length=2048, load_in_4bit=True,73)74model = FastLanguageModel.get_peft_model(model, r=16, lora_alpha=32)75```7677## Function Calling7879Enable LLMs to use external tools and return structured data. Use strict mode schemas (2026 best practice) for reliability. Limit to 5-15 tools per request, validate all inputs with Pydantic/Zod, and return errors as tool results.8081- `calling-tool-definition.md` -- Strict mode schemas, OpenAI/Anthropic formats, LangChain binding82- `calling-parallel.md` -- Parallel tool execution, asyncio.gather, strict mode constraints83- `calling-validation.md` -- Input validation, error handling, tool execution loops8485## Streaming8687Deliver LLM responses in real-time for better UX. Use SSE for web, WebSocket for bidirectional. Handle backpressure with bounded queues.8889- `streaming-sse.md` -- FastAPI SSE endpoints, frontend consumers, async iterators90- `streaming-structured.md` -- Streaming with tool calls, partial JSON parsing, chunk accumulation91- `streaming-backpressure.md` -- Backpressure handling, bounded buffers, cancellation9293## Local Inference9495Run LLMs locally with Ollama for cost savings (93% vs cloud), privacy, and offline development. Pre-warm models, use provider factory for cloud/local switching.9697- `local-ollama-setup.md` -- Installation, model pulling, environment configuration98- `local-model-selection.md` -- Model comparison by task, hardware profiles, quantization99- `local-gpu-optimization.md` -- Apple Silicon tuning, keep-alive, CI integration100101## Fine-Tuning102103Customize LLMs with parameter-efficient techniques. Fine-tune ONLY after exhausting prompt engineering and RAG. Requires 1000+ quality examples.104105- `tuning-lora.md` -- LoRA/QLoRA configuration, Unsloth training, adapter merging106- `tuning-dataset-prep.md` -- Synthetic data generation, quality validation, deduplication107- `tuning-evaluation.md` -- DPO alignment, evaluation metrics, anti-patterns108109## Context Optimization110111Manage context windows, compression, and attention-aware positioning. Optimize for tokens-per-task.112113- `context-window-management.md` -- Five-layer architecture, anchored summarization, compression triggers114- `context-caching.md` -- Just-in-time loading, budget scaling, probe evaluation, CC 2.1.32+115116## Evaluation117118Evaluate LLM outputs with multi-dimension scoring, quality gates, and benchmarks.119120- `evaluation-metrics.md` -- LLM-as-judge, RAGAS metrics, hallucination detection121- `evaluation-benchmarks.md` -- Quality gates, batch evaluation, pairwise comparison122123## Prompt Engineering124125Design, version, and optimize prompts for production LLM applications.126127- `prompt-design.md` -- Chain-of-Thought, few-shot learning, pattern selection guide128- `prompt-testing.md` -- Langfuse versioning, DSPy optimization, A/B testing, self-consistency129- `prompt-react-pattern.md` -- ReAct loop for tool-using agents, thought-action-observation format130- `prompt-optimization.md` -- Token reduction, cost optimization, model tiering, prompt spec format131132## Key Decisions133134| Decision | Recommendation |135|----------|----------------|136| Tool schema mode | `strict: true` (2026 best practice) |137| Tool count | 5-15 max per request |138| Streaming protocol | SSE for web, WebSocket for bidirectional |139| Buffer size | 50-200 tokens |140| Local model (reasoning) | `deepseek-r1:70b` |141| Local model (coding) | `qwen2.5-coder:32b` |142| Fine-tuning approach | LoRA/QLoRA (try prompting first) |143| LoRA rank | 16-64 typical |144| Training epochs | 1-3 (more risks overfitting) |145| Context compression | Anchored iterative (60-80%) |146| Compress trigger | 70% utilization, target 50% |147| Judge model | GPT-5.2-mini or Haiku 4.5 |148| Quality threshold | 0.7 production, 0.6 drafts |149| Few-shot examples | 3-5 diverse, representative |150| Prompt versioning | Langfuse with labels |151| Auto-optimization | DSPy MIPROv2 |152153## Related Skills154155- `ork:rag-retrieval` -- Embedding patterns, when RAG is better than fine-tuning156- `agent-loops` -- Multi-step tool use with reasoning157- `llm-evaluation` -- Evaluate fine-tuned and local models158- `langfuse-observability` -- Track training experiments159160## Capability Details161162### function-calling163**Keywords:** tool, function, define tool, tool schema, function schema, strict mode, parallel tools164**Solves:**165- Define tools with clear descriptions and strict schemas166- Execute tool calls in parallel with asyncio.gather167- Validate inputs and handle errors in tool execution loops168169### streaming170**Keywords:** streaming, SSE, Server-Sent Events, real-time, backpressure, token stream171**Solves:**172- Stream LLM tokens via SSE endpoints173- Handle tool calls within streams174- Manage backpressure with bounded queues175176### local-inference177**Keywords:** Ollama, local, self-hosted, model selection, GPU, Apple Silicon178**Solves:**179- Set up Ollama for local LLM inference180- Select models based on task and hardware181- Optimize GPU usage and CI integration182183### fine-tuning184**Keywords:** LoRA, QLoRA, fine-tune, DPO, synthetic data, PEFT, alignment185**Solves:**186- Configure LoRA/QLoRA for parameter-efficient training187- Generate and validate synthetic training data188- Align models with DPO and evaluate results189190---191> Converted and distributed by [TomeVault](https://tomevault.io/claim/yonatangross) — claim your Tome and manage your conversions.192<!-- tomevault:4.0:skill_md:2026-04-11 -->