在脚本的shebang行中使用LLM
本文介绍了一种创新方法,将LLM工具直接嵌入脚本的shebang行中执行指令。通过LLM的fragments模式,shebang行可执行简单任务,如生成SVG图像;使用-T选项能调用外部工具(如llm_time)创作包含当前时间的俳句;更复杂的是运行YAML模板,其中定义了Python函数作为工具进行数学计算,示例中演示了计算2344乘以5252加134的过程,并通过调试输出展示了分步结果,最终得到12,310,822。这展现了LLM作为脚本解释器的强大扩展性,能够支持从内容生成到数据查询的多样化任务。
Simon 这个 shebang 技巧让 LLM 直接变成脚本解释器,虽然是极客玩法,但对常写自动化脚本的开发者来说可以直接抄走,创意很妙。
TIL Using LLM in the shebang line of a script — [This comment](https://news.ycombinator.com/item?id=48073246#48090590) on Hacker News inspired me to investigate patterns for using my [LLM](https://llm.datasette.io/) CLI tool in a shebang line:
Kim_Bruning on Hacker News:
But seriously, you can put a shebang on an english text file now (if you're sufficiently brave) [...]
This inspired me to look at patterns for doing exactly that with LLM. Here's the simplest, which takes advantage of LLM fragments:
#!/usr/bin/env -S llm -f
Generate an SVG of a pelican riding a bicycle
But you can also incorporate tool calls using the -T name_of_tool option:
#!/usr/bin/env -S llm -T llm_time -f
Write a haiku that mentions the exact current time
Or even execute YAML templates directly that define extra tools as Python functions:
#!/usr/bin/env -S llm -t model: gpt-5.4-mini system: | Use tools to run calculations functions: | def add(a: int, b: int) -> int: return a + b def multiply(a: int, b: int) -> int: return a * b
Then:
./calc.sh 'what is 2344 * 5252 + 134' --td
Which outputs (thanks to that --td tools debug option):
Tool call: multiply({'a': 2344, 'b': 5252})
12310688
Tool call: add({'a': 12310688, 'b': 134})
12310822
2344 × 5252 + 134 = **12,310,822**
Read the full TIL for a more complex example that uses the Datasette SQL API to answer questions about content on my blog.
来源:Simon Willison 博客 · simonwillison.net