[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"tool-srush--MiniChain":3,"similar-srush--MiniChain":72},{"id":4,"github_repo":5,"name":6,"description_en":7,"description_zh":8,"ai_summary_zh":9,"readme_en":10,"readme_zh":11,"quickstart_zh":12,"use_case_zh":13,"hero_image_url":14,"owner_login":15,"owner_name":16,"owner_avatar_url":17,"owner_bio":18,"owner_company":19,"owner_location":20,"owner_email":21,"owner_twitter":22,"owner_website":23,"owner_url":24,"languages":25,"stars":38,"forks":39,"last_commit_at":40,"license":41,"difficulty_score":42,"env_os":43,"env_gpu":43,"env_ram":43,"env_deps":44,"category_tags":54,"github_topics":57,"view_count":42,"oss_zip_url":57,"oss_zip_packed_at":57,"status":58,"created_at":59,"updated_at":60,"faqs":61,"releases":62},8996,"srush\u002FMiniChain","MiniChain","A tiny library for coding with large language models.","MiniChain 是一个专为大型语言模型设计的轻量级编程库，旨在让开发者用极简的代码构建复杂的提示链（Prompt Chaining）应用。面对当前主流框架往往过于庞大复杂的问题，MiniChain 回归本质，通过“小而美”的设计降低了使用门槛。\n\n它核心解决了提示工程与业务逻辑耦合紧密、难以调试和维护的痛点。MiniChain 创新性地采用 Python 装饰器语法，允许开发者直接将函数标注为提示模板，实现了代码与提示词的清晰分离。其独特的技术亮点在于将调用过程构建为可视化的计算图（类似 PyTorch），支持惰性执行和灵活的转换操作，极大地方便了调试、错误处理及流程监控。此外，它还原生支持 OpenAI、Hugging Face、Google Search、Python 解释器及 Bash 等多种后端，能轻松实现检索增强生成（RAG）、思维链（CoT）等前沿模式。\n\n这款工具非常适合希望快速原型验证的 AI 研究人员、追求代码简洁优雅的 Python 开发者，以及需要深入理解提示链底层机制的技术人员。如果你厌倦了臃肿的框架，渴望一个直观、透明且易于掌控的工具来探索大模型潜力，Mi","MiniChain 是一个专为大型语言模型设计的轻量级编程库，旨在让开发者用极简的代码构建复杂的提示链（Prompt Chaining）应用。面对当前主流框架往往过于庞大复杂的问题，MiniChain 回归本质，通过“小而美”的设计降低了使用门槛。\n\n它核心解决了提示工程与业务逻辑耦合紧密、难以调试和维护的痛点。MiniChain 创新性地采用 Python 装饰器语法，允许开发者直接将函数标注为提示模板，实现了代码与提示词的清晰分离。其独特的技术亮点在于将调用过程构建为可视化的计算图（类似 PyTorch），支持惰性执行和灵活的转换操作，极大地方便了调试、错误处理及流程监控。此外，它还原生支持 OpenAI、Hugging Face、Google Search、Python 解释器及 Bash 等多种后端，能轻松实现检索增强生成（RAG）、思维链（CoT）等前沿模式。\n\n这款工具非常适合希望快速原型验证的 AI 研究人员、追求代码简洁优雅的 Python 开发者，以及需要深入理解提示链底层机制的技术人员。如果你厌倦了臃肿的框架，渴望一个直观、透明且易于掌控的工具来探索大模型潜力，MiniChain 将是理想的选择。","\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_fb4fb5b86864.png\" width=\"100%\">\n\nA tiny library for coding with **large** language models. Check out the [MiniChain Zoo](https:\u002F\u002Fsrush-minichain.hf.space\u002F) to get a sense of how it works.\n\n## Coding\n\n* Code ([math_demo.py](https:\u002F\u002Fgithub.com\u002Fsrush\u002FMiniChain\u002Fblob\u002Fmain\u002Fexamples\u002Fmath_demo.py)): Annotate Python functions that call language models.\n\n```python\n@prompt(OpenAI(), template_file=\"math.pmpt.tpl\")\ndef math_prompt(model, question):\n    \"Prompt to call GPT with a Jinja template\"\n    return model(dict(question=question))\n\n@prompt(Python(), template=\"import math\\n{{code}}\")\ndef python(model, code):\n    \"Prompt to call Python interpreter\"\n    code = \"\\n\".join(code.strip().split(\"\\n\")[1:-1])\n    return model(dict(code=code))\n\ndef math_demo(question):\n    \"Chain them together\"\n    return python(math_prompt(question))\n```\n\n* Chains ([Space](https:\u002F\u002Fsrush-minichain.hf.space\u002F)): MiniChain builds a graph (think like PyTorch) of all the calls you make for debugging and error handling.\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_f73d7f800ca0.png\" width=\"50%\">\n\n\n```python\nshow(math_demo,\n     examples=[\"What is the sum of the powers of 3 (3^i) that are smaller than 100?\",\n               \"What is the sum of the 10 first positive integers?\"],\n     subprompts=[math_prompt, python],\n     out_type=\"markdown\").queue().launch()\n```\n\n\n* Template ([math.pmpt.tpl](https:\u002F\u002Fgithub.com\u002Fsrush\u002FMiniChain\u002Fblob\u002Fmain\u002Fexamples\u002Fmath.pmpt.tpl)): Prompts are separated from code.\n\n```\n...\nQuestion:\nA robe takes 2 bolts of blue fiber and half that much white fiber. How many bolts in total does it take?\nCode:\n2 + 2\u002F2\n\nQuestion:\n{{question}}\nCode:\n```\n\n* Installation\n\n```bash\npip install minichain\nexport OPENAI_API_KEY=\"sk-***\"\n```\n\n## Examples\n\nThis library allows us to implement several popular approaches in a few lines of code.\n\n* [Retrieval-Augmented QA](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fqa\u002F)\n* [Chat with memory](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fchatgpt\u002F)\n* [Information Extraction](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fner\u002F)\n* [Interleaved Code (PAL)](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fpal\u002F) - [(Gao et al 2022)](https:\u002F\u002Farxiv.org\u002Fpdf\u002F2211.10435.pdf)\n* [Search Augmentation (Self-Ask)](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fselfask\u002F) - [(Press et al 2022)](https:\u002F\u002Fofir.io\u002Fself-ask.pdf)\n* [Chain-of-Thought](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fbash\u002F) - [(Wei et al 2022)](https:\u002F\u002Farxiv.org\u002Fabs\u002F2201.11903)\n\nIt supports the current backends.\n\n* OpenAI (Completions \u002F Embeddings)\n* Hugging Face 🤗\n* Google Search\n* Python\n* Manifest-ML (AI21, Cohere, Together)\n* Bash\n\n## Why Mini-Chain?\n\nThere are several very popular libraries for prompt chaining,\nnotably: [LangChain](https:\u002F\u002Flangchain.readthedocs.io\u002Fen\u002Flatest\u002F),\n[Promptify](https:\u002F\u002Fgithub.com\u002Fpromptslab\u002FPromptify), and\n[GPTIndex](https:\u002F\u002Fgpt-index.readthedocs.io\u002Fen\u002Flatest\u002Freference\u002Fprompts.html).\nThese library are useful, but they are extremely large and\ncomplex. MiniChain aims to implement the core prompt chaining\nfunctionality in a tiny digestable library.\n\n\n## Tutorial\n\nMini-chain is based on annotating functions as prompts.\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_70c93c7eb39b.png)\n\n\n```python\n@prompt(OpenAI())\ndef color_prompt(model, input):\n    return model(f\"Answer 'Yes' if this is a color, {input}. Answer:\")\n```\n\nPrompt functions act like python functions, except they are lazy to access the result you need to call `run()`.\n\n```python\nif color_prompt(\"blue\").run() == \"Yes\":\n    print(\"It's a color\")\n```\nAlternatively you can chain prompts together. Prompts are lazy, so if you want to manipulate them you need to add `@transform()` to your function. For example:\n\n```python\n@transform()\ndef said_yes(input):\n    return input == \"Yes\"\n```\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_127c32cf1c6d.png)\n\n```python\n@prompt(OpenAI())\ndef adjective_prompt(model, input):\n    return model(f\"Give an adjective to describe {input}. Answer:\")\n```\n\n\n```python\nadjective = adjective_prompt(\"rainbow\")\nif said_yes(color_prompt(adjective)).run():\n    print(\"It's a color\")\n```\n\n\nWe also include an argument `template_file` which assumes model uses template from the\n[Jinja](https:\u002F\u002Fjinja.palletsprojects.com\u002Fen\u002F3.1.x\u002Ftemplates\u002F) language.\nThis allows us to separate prompt text from the python code.\n\n```python\n@prompt(OpenAI(), template_file=\"math.pmpt.tpl\")\ndef math_prompt(model, question):\n    return model(dict(question=question))\n```\n\n### Visualization\n\nMiniChain has a built-in prompt visualization system using `Gradio`.\nIf you construct a function that calls a prompt chain you can visualize it\nby calling `show` and `launch`. This can be done directly in a notebook as well.\n\n```python\nshow(math_demo,\n     examples=[\"What is the sum of the powers of 3 (3^i) that are smaller than 100?\",\n              \"What is the sum of the 10 first positive integers?\"],\n     subprompts=[math_prompt, python],\n     out_type=\"markdown\").queue().launch()\n```\n\n\n### Memory\n\nMiniChain does not build in an explicit stateful memory class. We recommend implementing it as a queue.\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_0ed92d811a42.png)\n\nHere is a class you might find useful to keep track of responses.\n\n```python\n@dataclass\nclass State:\n    memory: List[Tuple[str, str]]\n    human_input: str = \"\"\n\n    def push(self, response: str) -> \"State\":\n        memory = self.memory if len(self.memory) \u003C MEMORY_LIMIT else self.memory[1:]\n        return State(memory + [(self.human_input, response)])\n```\n\nSee the full Chat example.\nIt keeps track of the last two responses that it has seen.\n\n### Tools and agents.\n\nMiniChain does not provide `agents` or `tools`. If you want that functionality you can use the `tool_num` argument of model which allows you to select from multiple different possible backends. It's easy to add new backends of your own (see the GradioExample).\n\n```python\n@prompt([Python(), Bash()])\ndef math_prompt(model, input, lang):\n    return model(input, tool_num= 0 if lang == \"python\" else 1)\n```\n\n### Documents and Embeddings\n\nMiniChain does not manage documents and embeddings. We recommend using\nthe [Hugging Face Datasets](https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Fdatasets\u002Findex) library with\nbuilt in FAISS indexing.\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_faf38156203c.png)\n\n\nHere is the implementation.\n\n```python\n# Load and index a dataset\nolympics = datasets.load_from_disk(\"olympics.data\")\nolympics.add_faiss_index(\"embeddings\")\n\n@prompt(OpenAIEmbed())\ndef get_neighbors(model, inp, k):\n    embedding = model(inp)\n    res = olympics.get_nearest_examples(\"embeddings\", np.array(embedding), k)\n    return res.examples[\"content\"]\n```\n\nThis creates a K-nearest neighbors (KNN) prompt that looks up the\n3 closest documents based on embeddings of the question asked.\nSee the full [Retrieval-Augemented QA](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fqa\u002F)\nexample.\n\n\nWe recommend creating these embeddings offline using the batch map functionality of the\ndatasets library.\n\n```python\ndef embed(x):\n    emb = openai.Embedding.create(input=x[\"content\"], engine=EMBEDDING_MODEL)\n    return {\"embeddings\": [np.array(emb['data'][i]['embedding'])\n                           for i in range(len(emb[\"data\"]))]}\nx = dataset.map(embed, batch_size=BATCH_SIZE, batched=True)\nx.save_to_disk(\"olympics.data\")\n```\n\nThere are other ways to do this such as [sqllite](https:\u002F\u002Fgithub.com\u002Fasg017\u002Fsqlite-vss)\nor [Weaviate](https:\u002F\u002Fweaviate.io\u002F).\n\n\n### Typed Prompts\n\nMiniChain can automatically generate a prompt header for you that aims to ensure the\noutput follows a given typed specification. For example, if you run the following code\nMiniChain will produce prompt that returns a list of `Player` objects.\n\n```python\nclass StatType(Enum):\n    POINTS = 1\n    REBOUNDS = 2\n    ASSISTS = 3\n\n@dataclass\nclass Stat:\n    value: int\n    stat: StatType\n\n@dataclass\nclass Player:\n    player: str\n    stats: List[Stat]\n\n\n@prompt(OpenAI(), template_file=\"stats.pmpt.tpl\", parser=\"json\")\ndef stats(model, passage):\n    out = model(dict(passage=passage, typ=type_to_prompt(Player)))\n    return [Player(**j) for j in out]\n```\n\nSpecifically it will provide your template with a string `typ` that you can use. For this example the string will be of the following form:\n\n\n```\nYou are a highly intelligent and accurate information extraction system. You take passage as input and your task is to find parts of the passage to answer questions.\n\nYou need to output a list of JSON encoded values\n\nYou need to classify in to the following types for key: \"color\":\n\nRED\nGREEN\nBLUE\n\n\nOnly select from the above list, or \"Other\".⏎\n\n\nYou need to classify in to the following types for key: \"object\":⏎\n\nString\n\n\n\nYou need to classify in to the following types for key: \"explanation\":\n\nString\n\n[{ \"color\" : \"color\" ,  \"object\" : \"object\" ,  \"explanation\" : \"explanation\"}, ...]\n\nMake sure every output is exactly seen in the document. Find as many as you can.\n```\n\nThis will then be converted to an object automatically for you.\n\n\n","\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_fb4fb5b86864.png\" width=\"100%\">\n\n一个用于与**大型**语言模型协作编码的轻量级库。请查看 [MiniChain Zoo](https:\u002F\u002Fsrush-minichain.hf.space\u002F)，以了解其工作方式。\n\n## 编码\n\n* 代码（[math_demo.py](https:\u002F\u002Fgithub.com\u002Fsrush\u002FMiniChain\u002Fblob\u002Fmain\u002Fexamples\u002Fmath_demo.py)）：为调用语言模型的 Python 函数添加注解。\n  \n```python\n@prompt(OpenAI(), template_file=\"math.pmpt.tpl\")\ndef math_prompt(model, question):\n    \"使用 Jinja 模板调用 GPT 的提示\"\n    return model(dict(question=question))\n\n@prompt(Python(), template=\"import math\\n{{code}}\")\ndef python(model, code):\n    \"调用 Python 解释器的提示\"\n    code = \"\\n\".join(code.strip().split(\"\\n\")[1:-1])\n    return model(dict(code=code))\n\ndef math_demo(question):\n    \"将它们串联起来\"\n    return python(math_prompt(question))\n```\n\n* 链条（[Space](https:\u002F\u002Fsrush-minichain.hf.space\u002F)）：MiniChain 会构建一张图（类似于 PyTorch），记录你所有的调用操作，便于调试和错误处理。\n\u003Cimg src=\"https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_f73d7f800ca0.png\" width=\"50%\">\n\n\n```python\nshow(math_demo,\n     examples=[\"小于 100 的 3 的幂之和是多少？\",\n               \"前 10 个正整数的和是多少？\"],\n     subprompts=[math_prompt, python],\n     out_type=\"markdown\").queue().launch()\n```\n\n\n* 模板（[math.pmpt.tpl](https:\u002F\u002Fgithub.com\u002Fsrush\u002FMiniChain\u002Fblob\u002Fmain\u002Fexamples\u002Fmath.pmpt.tpl)）：提示与代码分离。\n\n```\n...\n问题：\n一件长袍需要 2 匹蓝色纤维和一半数量的白色纤维。总共需要多少匹纤维？\n代码：\n2 + 2\u002F2\n\n问题：\n{{question}}\n代码：\n```\n\n* 安装\n\n```bash\npip install minichain\nexport OPENAI_API_KEY=\"sk-***\"\n```\n\n## 示例\n\n借助这个库，我们可以在几行代码中实现几种流行的方法。\n\n* [检索增强问答](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fqa\u002F)\n* [带记忆的聊天](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fchatgpt\u002F)\n* [信息抽取](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fner\u002F)\n* [交错代码（PAL）](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fpal\u002F) - [(Gao 等人 2022)](https:\u002F\u002Farxiv.org\u002Fpdf\u002F2211.10435.pdf)\n* [搜索增强（Self-Ask）](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fselfask\u002F) - [(Press 等人 2022)](https:\u002F\u002Fofir.io\u002Fself-ask.pdf)\n* [思维链](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fbash\u002F) - [(Wei 等人 2022)](https:\u002F\u002Farxiv.org\u002Fabs\u002F2201.11903)\n\n它支持当前主流的后端服务。\n\n* OpenAI（补全 \u002F 嵌入）\n* Hugging Face 🤗\n* Google 搜索\n* Python\n* Manifest-ML（AI21、Cohere、Together）\n* Bash\n\n## 为什么选择 Mini-Chain？\n\n目前有许多非常流行的提示链库，例如：[LangChain](https:\u002F\u002Flangchain.readthedocs.io\u002Fen\u002Flatest\u002F)、[Promptify](https:\u002F\u002Fgithub.com\u002Fpromptslab\u002FPromptify) 和 [GPTIndex](https:\u002F\u002Fgpt-index.readthedocs.io\u002Fen\u002Flatest\u002Freference\u002Fprompts.html)。这些库确实很有用，但它们体积庞大且复杂。MiniChain 的目标是用一个轻量级、易于理解的库来实现核心的提示链功能。\n\n## 教程\n\nMini-Chain 的核心思想是将函数标注为提示。\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_70c93c7eb39b.png)\n\n\n```python\n@prompt(OpenAI())\ndef color_prompt(model, input):\n    return model(f\"如果这是颜色，请回答‘是’，{input}。答案：\")\n```\n\n提示函数的行为类似于普通的 Python 函数，但它们是惰性的；你需要调用 `run()` 才能获取结果。\n\n```python\nif color_prompt(\"blue\").run() == \"Yes\":\n    print(\"这是一种颜色\")\n```\n\n你也可以将多个提示串联起来。由于提示是惰性的，如果你想对它们进行操作，需要在函数上添加 `@transform()` 装饰器。例如：\n\n```python\n@transform()\ndef said_yes(input):\n    return input == \"Yes\"\n```\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_127c32cf1c6d.png)\n\n```python\n@prompt(OpenAI())\ndef adjective_prompt(model, input):\n    return model(f\"请给出一个形容词来描述 {input}。答案：\")\n```\n\n\n```python\nadjective = adjective_prompt(\"彩虹\")\nif said_yes(color_prompt(adjective)).run():\n    print(\"这是一种颜色\")\n```\n\n\n我们还提供了一个 `template_file` 参数，假设模型使用来自 [Jinja](https:\u002F\u002Fjinja.palletsprojects.com\u002Fen\u002F3.1.x\u002Ftemplates\u002F) 语言的模板。这使得我们可以将提示文本与 Python 代码分离。\n\n```python\n@prompt(OpenAI(), template_file=\"math.pmpt.tpl\")\ndef math_prompt(model, question):\n    return model(dict(question=question))\n```\n\n### 可视化\n\nMiniChain 内置了基于 Gradio 的提示可视化系统。如果你构建了一个调用提示链的函数，可以通过调用 `show` 和 `launch` 来可视化整个流程。这也可以直接在笔记本中完成。\n\n```python\nshow(math_demo,\n     examples=[\"小于 100 的 3 的幂之和是多少？\",\n               \"前 10 个正整数的和是多少？\"],\n     subprompts=[math_prompt, python],\n     out_type=\"markdown\").queue().launch()\n```\n\n\n### 内存\n\nMiniChain 并没有内置显式的有状态内存类。我们建议将其实现为一个队列。\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_0ed92d811a42.png)\n\n以下是一个可能对你跟踪响应有用的类。\n\n```python\n@dataclass\nclass State:\n    memory: List[Tuple[str, str]]\n    human_input: str = \"\"\n\n    def push(self, response: str) -> \"State\":\n        memory = self.memory 如果长度未超过 MEMORY_LIMIT，则保留全部；否则只保留最近的记录。\n        return State(memory + [(self.human_input, response)])\n```\n\n请参阅完整的聊天示例。它会记录最近两次收到的回复。\n\n### 工具与智能体\n\nMiniChain 不提供“智能体”或“工具”。如果你需要这些功能，可以使用模型的 `tool_num` 参数，允许你在多个不同的后端之间进行选择。你也可以轻松添加自己的后端（参见 GradioExample）。\n\n```python\n@prompt([Python(), Bash()])\ndef math_prompt(model, input, lang):\n    return model(input, tool_num= 0 if lang == \"python\" else 1)\n```\n\n### 文档与嵌入\n\nMiniChain 不管理文档和嵌入。我们建议使用 [Hugging Face Datasets](https:\u002F\u002Fhuggingface.co\u002Fdocs\u002Fdatasets\u002Findex) 库，并结合 FAISS 索引功能。\n\n![image](https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_readme_faf38156203c.png)\n\n\n以下是实现方法。\n\n# 加载并索引数据集\nolympics = datasets.load_from_disk(\"olympics.data\")\nolympics.add_faiss_index(\"embeddings\")\n\n@prompt(OpenAIEmbed())\ndef get_neighbors(model, inp, k):\n    embedding = model(inp)\n    res = olympics.get_nearest_examples(\"embeddings\", np.array(embedding), k)\n    return res.examples[\"content\"]\n```\n\n这会创建一个 K 近邻（KNN）提示，它会根据所提问题的嵌入向量查找最接近的 3 个文档。\n请参阅完整的 [检索增强型问答](https:\u002F\u002Fsrush.github.io\u002FMiniChain\u002Fexamples\u002Fqa\u002F) 示例。\n\n\n我们建议使用 datasets 库的批处理映射功能离线生成这些嵌入。\n\n```python\ndef embed(x):\n    emb = openai.Embedding.create(input=x[\"content\"], engine=EMBEDDING_MODEL)\n    return {\"embeddings\": [np.array(emb['data'][i]['embedding'])\n                           for i in range(len(emb[\"data\"]))]}\nx = dataset.map(embed, batch_size=BATCH_SIZE, batched=True)\nx.save_to_disk(\"olympics.data\")\n```\n\n还有其他方法可以实现这一点，例如 [sqllite](https:\u002F\u002Fgithub.com\u002Fasg017\u002Fsqlite-vss) 或 [Weaviate](https:\u002F\u002Fweaviate.io\u002F)。\n\n\n### 类型化提示\n\nMiniChain 可以自动为你生成一个提示头，旨在确保输出符合给定的类型规范。例如，如果你运行以下代码，MiniChain 将生成一个返回 `Player` 对象列表的提示。\n\n```python\nclass StatType(Enum):\n    POINTS = 1\n    REBOUNDS = 2\n    ASSISTS = 3\n\n@dataclass\nclass Stat:\n    value: int\n    stat: StatType\n\n@dataclass\nclass Player:\n    player: str\n    stats: List[Stat]\n\n\n@prompt(OpenAI(), template_file=\"stats.pmpt.tpl\", parser=\"json\")\ndef stats(model, passage):\n    out = model(dict(passage=passage, typ=type_to_prompt(Player)))\n    return [Player(**j) for j in out]\n```\n\n具体来说，它会为你的模板提供一个字符串 `typ`，你可以使用它。对于这个示例，该字符串将如下所示：\n\n\n```\n你是一个高度智能且准确的信息提取系统。你以段落作为输入，任务是找出段落中回答问题的部分。\n\n你需要输出一个 JSON 编码的值列表。\n\n你需要将“color”键分类到以下类型：\n\nRED\nGREEN\nBLUE\n\n\n只能从上述列表或“Other”中选择。⏎\n\n\n你需要将“object”键分类到以下类型：⏎\n\nString\n\n\n\n你需要将“explanation”键分类到以下类型：⏎\n\nString\n\n[{ \"color\" : \"color\" ,  \"object\" : \"object\" ,  \"explanation\" : \"explanation\"}, ...]\n\n请确保每个输出都与文档中的内容完全一致。尽可能多地找到它们。\n```\n\n然后，这段文本会被自动转换为你所需的对象。","# MiniChain 快速上手指南\n\nMiniChain 是一个轻量级的 Python 库，专为使用大型语言模型（LLM）进行编程而设计。它通过装饰器将函数标注为提示词（Prompt），支持构建复杂的调用链、可视化调试以及类型化输出，旨在以极简的代码实现 LangChain 等大型库的核心功能。\n\n## 环境准备\n\n*   **系统要求**：Python 3.8+\n*   **前置依赖**：\n    *   OpenAI API Key（用于调用 GPT 模型）\n    *   可选：Hugging Face 账号（用于本地模型或数据集）、Google Search API 等\n*   **网络环境**：由于需要连接 OpenAI 或其他海外模型服务，请确保网络通畅或配置好代理。\n\n## 安装步骤\n\n1.  使用 pip 安装 MiniChain：\n    ```bash\n    pip install minichain\n    ```\n\n2.  配置 OpenAI API 密钥（Linux\u002FmacOS）：\n    ```bash\n    export OPENAI_API_KEY=\"sk-***\"\n    ```\n    *(Windows PowerShell 用户请使用 `$env:OPENAI_API_KEY=\"sk-***\"`)*\n\n## 基本使用\n\nMiniChain 的核心理念是将函数装饰为 Prompt。以下是两个最基础的使用场景。\n\n### 1. 最简单的 Prompt 调用\n\n使用 `@prompt` 装饰器定义一个函数，该函数在调用时是“惰性”的（lazy），需要执行 `.run()` 才能获取结果。\n\n```python\nfrom minichain import prompt, OpenAI\n\n@prompt(OpenAI())\ndef color_prompt(model, input):\n    return model(f\"Answer 'Yes' if this is a color, {input}. Answer:\")\n\n# 调用并运行\nif color_prompt(\"blue\").run() == \"Yes\":\n    print(\"It's a color\")\n```\n\n### 2. 构建提示词链 (Chaining)\n\n你可以将多个 Prompt 函数串联起来。如果需要处理中间结果，可以使用 `@transform` 装饰器。\n\n```python\nfrom minichain import prompt, transform, OpenAI\n\n@transform()\ndef said_yes(input):\n    return input == \"Yes\"\n\n@prompt(OpenAI())\ndef adjective_prompt(model, input):\n    return model(f\"Give an adjective to describe {input}. Answer:\")\n\n@prompt(OpenAI())\ndef color_prompt(model, input):\n    return model(f\"Answer 'Yes' if this is a color, {input}. Answer:\")\n\n# 链式调用：先生成形容词，再判断是否为颜色\nadjective = adjective_prompt(\"rainbow\")\nif said_yes(color_prompt(adjective)).run():\n    print(\"It's a color\")\n```\n\n### 3. 使用模板分离代码与提示词\n\n为了保持代码整洁，MiniChain 支持使用 Jinja2 模板文件来管理提示词内容。\n\n**模板文件 (`math.pmpt.tpl`)：**\n```text\nQuestion:\n{{question}}\nCode:\n```\n\n**Python 代码：**\n```python\nfrom minichain import prompt, OpenAI\n\n@prompt(OpenAI(), template_file=\"math.pmpt.tpl\")\ndef math_prompt(model, question):\n    return model(dict(question=question))\n\n# 运行\nresult = math_prompt(\"What is 2 + 2?\").run()\nprint(result)\n```\n\n### 4. 可视化调试 (可选)\n\nMiniChain 内置基于 Gradio 的可视化系统，可以直观地看到 Prompt 链的执行图和结果。\n\n```python\nfrom minichain import show\n\n# 假设 math_demo 是你定义的一个组合函数\nshow(math_demo,\n     examples=[\"What is the sum of the powers of 3 (3^i) that are smaller than 100?\"],\n     subprompts=[math_prompt],\n     out_type=\"markdown\").queue().launch()\n```","某初创公司的数据工程师需要构建一个能自动解析复杂数学应用题并执行代码计算答案的智能问答系统。\n\n### 没有 MiniChain 时\n- **代码与提示词耦合严重**：开发者被迫将冗长的 Prompt 模板硬编码在 Python 字符串中，导致逻辑混乱且难以维护。\n- **调试过程如同“黑盒”**：当 LLM 生成的代码出错或推理中断时，缺乏可视化的调用链路，难以定位是模型理解偏差还是代码执行失败。\n- **多步骤协作实现困难**：手动串联“自然语言转代码”与“代码执行”两个环节需要编写大量胶水代码，极易出现上下文丢失或格式解析错误。\n- **迭代验证成本高昂**：每次调整 Prompt 模板或更换后端模型，都需要重构大量底层逻辑，无法快速验证新想法。\n\n### 使用 MiniChain 后\n- **模板与逻辑清晰分离**：利用 Jinja 模板文件管理提示词，通过 `@prompt` 装饰器标注函数，使代码结构像普通 Python 程序一样直观易读。\n- **全链路可视化调试**：MiniChain 自动构建类似 PyTorch 的计算图，开发者可直接查看每个节点的输入输出，迅速锁定推理链条中的断裂点。\n- **声明式链式调用**：只需简单组合带装饰器的函数即可实现“生成代码 - 执行代码”的闭环，库内部自动处理懒加载与结果传递，大幅减少样板代码。\n- **敏捷实验与扩展**：支持一键切换 OpenAI、Hugging Face 等不同后端，并能轻松复用官方提供的 PAL 或思维链示例，几分钟内即可完成原型验证。\n\nMiniChain 通过将复杂的提示工程简化为直观的函数注解与可视化图谱，让开发者能以最小的代码代价构建可靠的大模型应用链条。","https:\u002F\u002Foss.gittoolsai.com\u002Fimages\u002Fsrush_MiniChain_fb4fb5b8.png","srush","Sasha Rush","https:\u002F\u002Foss.gittoolsai.com\u002Favatars\u002Fsrush_0d88b2d1.jpg","Cornell Tech \u002F Hugging Face","Cornell","New York","srush.research@gmail.com","srush_nlp","http:\u002F\u002Frush-nlp.com","https:\u002F\u002Fgithub.com\u002Fsrush",[26,30,34],{"name":27,"color":28,"percentage":29},"Python","#3572A5",94.4,{"name":31,"color":32,"percentage":33},"Smarty","#f0c040",4.8,{"name":35,"color":36,"percentage":37},"Makefile","#427819",0.9,1233,76,"2026-03-17T08:05:29","MIT",2,"未说明",{"notes":45,"python":43,"dependencies":46},"该库是一个轻量级工具，主要用于编排提示链。运行需配置 OPENAI_API_KEY 环境变量。支持多种后端（OpenAI, Hugging Face, Google Search, Python, Bash 等）。文档和嵌入管理推荐结合 Hugging Face Datasets 和 FAISS 使用，需自行离线生成嵌入。不包含内置的状态记忆类或 Agent\u002FTool 框架，需用户自行实现或使用特定参数选择后端。",[47,48,49,50,51,52,53],"minichain","jinja2","gradio","openai","transformers","datasets","faiss",[55,56],"语言模型","开发框架",null,"ready","2026-03-27T02:49:30.150509","2026-04-18T17:04:38.631865",[],[63,67],{"id":64,"version":65,"summary_zh":57,"released_at":66},323755,"v0.2","2023-04-18T19:58:46",{"id":68,"version":69,"summary_zh":70,"released_at":71},323756,"v0.1","原始迷你链版本","2023-03-22T18:44:44",[73,85,93,101,109,118],{"id":74,"name":75,"github_repo":76,"description_zh":77,"stars":78,"difficulty_score":79,"last_commit_at":80,"category_tags":81,"status":58},4358,"openclaw","openclaw\u002Fopenclaw","OpenClaw 是一款专为个人打造的本地化 AI 助手，旨在让你在自己的设备上拥有完全可控的智能伙伴。它打破了传统 AI 助手局限于特定网页或应用的束缚，能够直接接入你日常使用的各类通讯渠道，包括微信、WhatsApp、Telegram、Discord、iMessage 等数十种平台。无论你在哪个聊天软件中发送消息，OpenClaw 都能即时响应，甚至支持在 macOS、iOS 和 Android 设备上进行语音交互，并提供实时的画布渲染功能供你操控。\n\n这款工具主要解决了用户对数据隐私、响应速度以及“始终在线”体验的需求。通过将 AI 部署在本地，用户无需依赖云端服务即可享受快速、私密的智能辅助，真正实现了“你的数据，你做主”。其独特的技术亮点在于强大的网关架构，将控制平面与核心助手分离，确保跨平台通信的流畅性与扩展性。\n\nOpenClaw 非常适合希望构建个性化工作流的技术爱好者、开发者，以及注重隐私保护且不愿被单一生态绑定的普通用户。只要具备基础的终端操作能力（支持 macOS、Linux 及 Windows WSL2），即可通过简单的命令行引导完成部署。如果你渴望拥有一个懂你",349277,3,"2026-04-06T06:32:30",[82,56,83,84],"Agent","图像","数据工具",{"id":86,"name":87,"github_repo":88,"description_zh":89,"stars":90,"difficulty_score":79,"last_commit_at":91,"category_tags":92,"status":58},3808,"stable-diffusion-webui","AUTOMATIC1111\u002Fstable-diffusion-webui","stable-diffusion-webui 是一个基于 Gradio 构建的网页版操作界面，旨在让用户能够轻松地在本地运行和使用强大的 Stable Diffusion 图像生成模型。它解决了原始模型依赖命令行、操作门槛高且功能分散的痛点，将复杂的 AI 绘图流程整合进一个直观易用的图形化平台。\n\n无论是希望快速上手的普通创作者、需要精细控制画面细节的设计师，还是想要深入探索模型潜力的开发者与研究人员，都能从中获益。其核心亮点在于极高的功能丰富度：不仅支持文生图、图生图、局部重绘（Inpainting）和外绘（Outpainting）等基础模式，还独创了注意力机制调整、提示词矩阵、负向提示词以及“高清修复”等高级功能。此外，它内置了 GFPGAN 和 CodeFormer 等人脸修复工具，支持多种神经网络放大算法，并允许用户通过插件系统无限扩展能力。即使是显存有限的设备，stable-diffusion-webui 也提供了相应的优化选项，让高质量的 AI 艺术创作变得触手可及。",162132,"2026-04-05T11:01:52",[56,83,82],{"id":94,"name":95,"github_repo":96,"description_zh":97,"stars":98,"difficulty_score":42,"last_commit_at":99,"category_tags":100,"status":58},1381,"everything-claude-code","affaan-m\u002Feverything-claude-code","everything-claude-code 是一套专为 AI 编程助手（如 Claude Code、Codex、Cursor 等）打造的高性能优化系统。它不仅仅是一组配置文件，而是一个经过长期实战打磨的完整框架，旨在解决 AI 代理在实际开发中面临的效率低下、记忆丢失、安全隐患及缺乏持续学习能力等核心痛点。\n\n通过引入技能模块化、直觉增强、记忆持久化机制以及内置的安全扫描功能，everything-claude-code 能显著提升 AI 在复杂任务中的表现，帮助开发者构建更稳定、更智能的生产级 AI 代理。其独特的“研究优先”开发理念和针对 Token 消耗的优化策略，使得模型响应更快、成本更低，同时有效防御潜在的攻击向量。\n\n这套工具特别适合软件开发者、AI 研究人员以及希望深度定制 AI 工作流的技术团队使用。无论您是在构建大型代码库，还是需要 AI 协助进行安全审计与自动化测试，everything-claude-code 都能提供强大的底层支持。作为一个曾荣获 Anthropic 黑客大奖的开源项目，它融合了多语言支持与丰富的实战钩子（hooks），让 AI 真正成长为懂上",159636,"2026-04-17T23:33:34",[56,82,55],{"id":102,"name":103,"github_repo":104,"description_zh":105,"stars":106,"difficulty_score":42,"last_commit_at":107,"category_tags":108,"status":58},2271,"ComfyUI","Comfy-Org\u002FComfyUI","ComfyUI 是一款功能强大且高度模块化的视觉 AI 引擎，专为设计和执行复杂的 Stable Diffusion 图像生成流程而打造。它摒弃了传统的代码编写模式，采用直观的节点式流程图界面，让用户通过连接不同的功能模块即可构建个性化的生成管线。\n\n这一设计巧妙解决了高级 AI 绘图工作流配置复杂、灵活性不足的痛点。用户无需具备编程背景，也能自由组合模型、调整参数并实时预览效果，轻松实现从基础文生图到多步骤高清修复等各类复杂任务。ComfyUI 拥有极佳的兼容性，不仅支持 Windows、macOS 和 Linux 全平台，还广泛适配 NVIDIA、AMD、Intel 及苹果 Silicon 等多种硬件架构，并率先支持 SDXL、Flux、SD3 等前沿模型。\n\n无论是希望深入探索算法潜力的研究人员和开发者，还是追求极致创作自由度的设计师与资深 AI 绘画爱好者，ComfyUI 都能提供强大的支持。其独特的模块化架构允许社区不断扩展新功能，使其成为当前最灵活、生态最丰富的开源扩散模型工具之一，帮助用户将创意高效转化为现实。",108322,"2026-04-10T11:39:34",[56,83,82],{"id":110,"name":111,"github_repo":112,"description_zh":113,"stars":114,"difficulty_score":42,"last_commit_at":115,"category_tags":116,"status":58},6121,"gemini-cli","google-gemini\u002Fgemini-cli","gemini-cli 是一款由谷歌推出的开源 AI 命令行工具，它将强大的 Gemini 大模型能力直接集成到用户的终端环境中。对于习惯在命令行工作的开发者而言，它提供了一条从输入提示词到获取模型响应的最短路径，无需切换窗口即可享受智能辅助。\n\n这款工具主要解决了开发过程中频繁上下文切换的痛点，让用户能在熟悉的终端界面内直接完成代码理解、生成、调试以及自动化运维任务。无论是查询大型代码库、根据草图生成应用，还是执行复杂的 Git 操作，gemini-cli 都能通过自然语言指令高效处理。\n\n它特别适合广大软件工程师、DevOps 人员及技术研究人员使用。其核心亮点包括支持高达 100 万 token 的超长上下文窗口，具备出色的逻辑推理能力；内置 Google 搜索、文件操作及 Shell 命令执行等实用工具；更独特的是，它支持 MCP（模型上下文协议），允许用户灵活扩展自定义集成，连接如图像生成等外部能力。此外，个人谷歌账号即可享受免费的额度支持，且项目基于 Apache 2.0 协议完全开源，是提升终端工作效率的理想助手。",100752,"2026-04-10T01:20:03",[117,82,83,56],"插件",{"id":119,"name":120,"github_repo":121,"description_zh":122,"stars":123,"difficulty_score":42,"last_commit_at":124,"category_tags":125,"status":58},4721,"markitdown","microsoft\u002Fmarkitdown","MarkItDown 是一款由微软 AutoGen 团队打造的轻量级 Python 工具，专为将各类文件高效转换为 Markdown 格式而设计。它支持 PDF、Word、Excel、PPT、图片（含 OCR）、音频（含语音转录）、HTML 乃至 YouTube 链接等多种格式的解析，能够精准提取文档中的标题、列表、表格和链接等关键结构信息。\n\n在人工智能应用日益普及的今天，大语言模型（LLM）虽擅长处理文本，却难以直接读取复杂的二进制办公文档。MarkItDown 恰好解决了这一痛点，它将非结构化或半结构化的文件转化为模型“原生理解”且 Token 效率极高的 Markdown 格式，成为连接本地文件与 AI 分析 pipeline 的理想桥梁。此外，它还提供了 MCP（模型上下文协议）服务器，可无缝集成到 Claude Desktop 等 LLM 应用中。\n\n这款工具特别适合开发者、数据科学家及 AI 研究人员使用，尤其是那些需要构建文档检索增强生成（RAG）系统、进行批量文本分析或希望让 AI 助手直接“阅读”本地文件的用户。虽然生成的内容也具备一定可读性，但其核心优势在于为机器",93400,"2026-04-06T19:52:38",[117,56]]