You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Some useful snippets for notebooks, Python/R/HTML/CSS code in Quarto/Jupyter notebooks
dotenv: Load environment variables from a .env file in a notebook cell:
importosfromopenaiimportOpenAIfrompprintimportpprintfromIPython.displayimportdisplay, Markdown#import tiktokenfromdotenvimportload_dotenv, find_dotenv_=load_dotenv(find_dotenv()) # read local .env fileassertos.environ.get('OPENAI_API_KEY'), "API key not found. Make sure to set OPENAI_API_KEY in your .env file."openai=OpenAI(api_key=os.environ['OPENAI_API_KEY'])
GUI: Highlight a note or tip in a notebook cell:
# Highlight a note or tip in a notebook cell:
<pstyle="padding:12px; border:1px solid #ffc107; border-radius:6px">>β‘ Note: ...
</p>
Tool Calling: Disk-Based Memoization (Essential for Notebooks)
Prevents re-running expensive calls when iterating. Use diskcacheβit's pure-Python, zero-config, and persists across notebook restarts.
Tool Calling with Kimi-K2-Thinking-Turbo: A Minimalist Guide for Solo Devs
For your solo-dev, notebook-to-cron workflow, you don't need heavy orchestration. The classic max_turns loop is still your skeletonβjust add a few lightweight guardrails to make it robust and idempotent. Here are the patterns that actually matter for small scripts:
1. Disk-Based Memoization (Essential for Notebooks)
Prevents re-running expensive calls when iterating. Use diskcacheβit's pure-Python, zero-config, and persists across notebook restarts.
qwen3.6-27b tool calling best practices for cron jobs and notebooks
Given your workflow (notebook β tiny projects β cron), you don't need complex multi-agent or streaming architectures. You need deterministic termination, minimal boilerplate, and clean batch execution. The best fit is a Guardrailed Tool Loop with explicit exit conditions, not just n turns.
Hereβs a practical, production-ready approach tailored to your context:
π Core Pattern: Guardrailed Tool Loop
Instead of a naive for _ in range(max_turns):, use a loop that exits on any of these conditions:
Condition
Why it matters for cron/notebooks
max_turns reached
Hard cap prevents infinite loops
max_runtime exceeded
Cron jobs shouldn't hang forever
LLM returns no tool calls
Normal completion
tool fails N times consecutively
Prevents cascading API/network failures
idempotency check passes
Skip if job already ran successfully today
dry_run=True
Test logic without executing tools
π οΈ Key Techniques for Your Workflow
1. Stateless, Export-Ready Tool Functions
Avoid notebook globals or mutable state. Tools should be pure functions that take explicit args and return structured dicts:
Keep a simple list of messages. Easy to dump for debugging or convert to script later:
history= [
{"role": "system", "content": "You are a helpful assistant with access to tools."},
{"role": "user", "content": "What's the weather in Berlin and how much is 3x coffee at $2.50?"}
]
3. Graceful Tool Failure Handling
Never let a tool crash the loop. Wrap execution, return clear error strings to the LLM:
Set explicit timeouts: Cron doesn't kill long jobs automatically. Use timeout 300 python script.py in crontab.
Idempotency: Check a marker file or DB flag before running:
ifos.path.exists("last_run_success.json"):
logging.info("Already ran today. Skipping.")
exit(0)
Network resilience: Add retry logic for external APIs (tools, LLM calls). Use tenacity or simple try/except with backoff.
π« Common Pitfalls & Fixes
Pitfall
Fix
LLM loops calling same tool with same args
Add max_consecutive_same_tool check or require arg mutation
Tool output too long β context overflow
Truncate tool results, return only essential fields
Cron fails silently
Always redirect stdout/stderr to log files, check exit codes
Notebook state leaks into script
Run python script.py early in dev; don't wait until cron
LLM ignores tool results
Add system prompt: "You must acknowledge tool output before proceeding."
β Recommendation Summary
Start with a guardrailed tool loop (max turns + timeout + error backoff).
Keep tools stateless & pure functions.
Use logging + exit codes, not print().
Design for cron from day 1: env vars, idempotency, flock, timeouts.
Convert notebooks early using nbconvert, fix magic cells, test as scripts.
Add dry_run=True flag for safe iteration.
This pattern scales from interactive notebook exploration to unattended cron jobs with minimal refactoring. If you want, I can provide a complete, runnable template with proper OpenAI tool schemas, logging, and cron-safe structure. Just say the word.