项目介绍
Agent 开发框架 · 2026-11-09 更新 · 本站尚未实测
Guidance 是 guidance-ai 组织维护的开源 Python 框架,README 将其定位为“an efficient programming paradigm for steering language models”,即引导大语言模型的编程范式。它的核心思路是把提示、控制流(条件、循环、工具调用)与生成过程交织在一起,并对输出施加结构约束,从而按用例获得更可控、结构更规整的结果。
需要注意的是,Guidance 是一个需要编写 Python 代码并安装到本地或服务端环境中的框架/库,而不是可以直接双击运行的“Agent”应用,也不是 MCP 服务或 Skill 包。是否适合你的场景,取决于你是否在 Python 项目中调用大模型并需要结构化输出。
核心能力
点击能力名称查看输入、输出和原文依据。
根据 README,Guidance 提供以下能力:
- 类似常规 Python 代码的模型调用接口,使用
system、user、assistant、gen等构造对话与生成。 - 约束生成:
gen()可用正则表达式限定输出格式;select()可从预设选项集合中取值。 - 上下文无关文法(CFG)约束,README 说明只要后端模型对 Guidance 有完整支持,输出即可符合任意上下文无关文法。
- JSON 生成支持:README 说明 JSON Schema 本身即上下文无关文法,并提供基于 Pydantic 模型的
gen_json用法示例。 - 自定义 Guidance 函数:通过
@guidance装饰器编写可复用的生成函数,并可组合成完整文法。 - 离线调试文法:使用
Mock模型在本地校验候选字符串,无需调用模型 API。 - token 快进:当文法已确定后续 token 时,框架可自行填入,减少模型前向计算。
README 提到支持多种后端,包括 Transformers、llama.cpp、OpenAI 等,并在示例中使用 microsoft/Phi-4-mini-instruct 本地模型。
实际应用场景
适用场景
- 需要模型稳定输出固定格式(如数字、单选选项、JSON 结构)的工程场景。
- 构建带条件分支、循环和工具调用交织的复杂生成流程。
- 在本地用 Mock 模型离线迭代文法约束,减少调试时的 API 开销。
- 需要从业务数据(如 Pydantic 模型)反推输出结构、并直接做校验的开发者。
安装与接入
README 说明 Guidance 通过 PyPI 发布。若已具备所用模型对应的后端,可直接运行:
pip install guidance
接入方式为在 Python 代码中导入 guidance 与 guidance.models,按需选择 Transformers、LlamaCpp 等模型类并加载模型。README 给出的本地模型示例使用 microsoft/Phi-4-mini-instruct;使用远程 API 后端时的密钥与配置细节,本次资料未提供,待核验。依据是否可在 Windows、macOS 或特定 Linux 发行版安装运行,文件未说明,待核验。
使用条件与限制
- 是否需要部署
- 需自行准备运行环境,具体要求见正文
- 是否需要注册
- 账号和认证要求见正文;未明确说明的项目仍待核验
- 是否需要 API Key
- 待核验
- 费用与额度
- 费用边界见正文,项目许可不代表模型或托管服务免费
- 所需权限
- 待核验
- 许可证与服务条款
- 待核验
权限费用与限制
- 仓库代码以 MIT 许可证发布,允许使用、复制、修改、合并、发布、再许可和销售,需保留版权与许可声明。
- 框架本身免费,但模型可能产生费用:使用 OpenAI 等远程后端时,费用与计费规则取决于对应服务商;资料未给出任何价格,须以官方为准,本页不做报价。
- 本地运行需要自行准备模型权重与运行环境,硬件要求(显存、内存)资料未说明,待核验。
- README 称约束生成可降低延迟与成本(相比常规提示或微调),这是项目作者的描述,本站未对该结论进行实测,实际效果需自行评估。
- 资料未说明数据隐私、安全策略或合规认证情况,待核验。
国内使用情况
网友核验 用户经验分享
与站长实测独立,不代表官方认证或本站已实测。
最近核验:暂无有效核验。参与人数按当前项目有效身份去重;不同核验项分别统计,不合并成用户总结果。仅统计审核通过且未过期的记录。
分项统计、有效期与样本量
| 核验项目 | 有效人数 | 成功 / 部分 / 失败 / 无法判断 | 成功率 | 最近核验 / 有效期 |
|---|---|---|---|---|
| 官方网站访问 | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 7 天 |
| GitHub 仓库访问 | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 7 天 |
| 安装与运行 | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 30 天 |
| 官方服务国内连接 / MCP 连接 | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 30 天 |
| 国内网络情况 | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 7 天 |
| 国内模型兼容性 | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 30 天 |
| 自定义 API | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 30 天 |
| 海外服务依赖 | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 30 天 |
| 海外账号要求 | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 30 天 |
| 中文界面 | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 30 天 |
| 客户端兼容性 | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 30 天 |
| 账号及费用信息 | 0 | 0 / 0 / 0 / 0 | 样本不足 | 暂无 / 30 天 |
成功率 = 成功 ÷(成功 + 部分成功 + 失败);无法判断不计入分母。至少 5 份可判断结果才显示成功率。账号、费用、海外依赖与语言等事实项,成功表示核查结论与资料吻合,具体观察另行统计;不表示免费或没有海外依赖。不同网络、客户端和版本的结果不能直接等同。
最近有效核验
暂无审核通过且未过期的网友核验。欢迎提交真实使用记录。
查看全部有效核验 →国内实测状态:国内可用性待核验。协议兼容和官方资料说明不等于国内网络可用。
- 官方网站访问
- 尚未实测 待核验
- GitHub 仓库访问
- 尚未实测 待核验
- 官方服务国内连接
- 尚未实测 待核验
- 国内网络情况
- 尚未实测 待核验
- 国内模型兼容性
- 尚未实测 待核验
- 自定义 API
- 尚未实测 待核验
- 海外服务依赖
- 尚未实测 待核验
- 海外账号要求
- 尚未实测 待核验
- 中文界面
- 尚未实测 待核验
- 国内最后核验时间
- 尚未实测
许可与国内使用
仓库包含 MIT 许可证文件,许可证文本以仓库为准。模型权重、第三方推理后端和云 API 各自有其许可与使用条款,需分别核对,不能因仓库开源而视为全部免费或可任意商用。README 未说明在中国大陆的网络可达性、镜像源、中文支持或合规情况,这些均待核验;邮件联系信息为 guidanceai@microsoft.com,Discord 为项目支持渠道。
项目资料与来源
字段依据与待核验事项
access:来源确认 · If you already have the backend required for your model, you can simply run
project_type:来源确认 · Guidance is an efficient programming paradigm for steering language models.
原始 README(折叠技术参考)
<div align="right">
<a href="https://discord.gg/cjPfAK43dz"><img src="https://img.shields.io/badge/Discord-Join%20Us-5865F2?logo=discord&logoColor=white" alt="Discord"></a>
<a href="mailto:guidanceai@microsoft.com"><img src="https://img.shields.io/badge/Email-guidanceai%40microsoft.com-0078D4?logo=microsoft-outlook&logoColor=white" alt="Email"></a>
<img src="https://img.shields.io/badge/Hours-10am--2pm%20Pacific-gray" alt="Hours">
</div>
<div align="center"><picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/figures/guidance_logo_blue_dark.svg">
<img alt="guidance" src="docs/figures/guidance_logo_blue.svg" width=300">
</picture></div>
<br/>
**Guidance is an efficient programming paradigm for steering language models.** With Guidance, you can control how output is structured and get high-quality output for your use case—*while reducing latency and cost vs. conventional prompting or fine-tuning.* It allows users to constrain generation (e.g. with regex and CFGs) as well as to interleave control (conditionals, loops, tool use) and generation seamlessly.
* [Install](#install)
* [Features](#features)
## Install
Guidance is available through PyPI and supports a variety of backends (Transformers, llama.cpp, OpenAI, etc.).
If you already have the backend required for your model, you can simply run
```bash
pip install guidance
```
## Features
### A Pythonic interface for language models
When using Guidance, you can work with large language models using common Python idioms:
```python
from guidance import system, user, assistant, gen
from guidance.models import Transformers
# Could also do LlamaCpp or many other models
phi_lm = Transformers("microsoft/Phi-4-mini-instruct")
# Model objects are immutable, so this is a copy
lm = phi_lm
with system():
lm += "You are a helpful assistant"
with user():
lm += "Hello. What is your name?"
with assistant():
lm += gen(max_tokens=20)
print(lm)
```
If run at the command line, this will produce output like:
```
<|system|>You are a helpful assistant<|end|><|user|>Hello. What is your name?<|end|><|assistant|>I am Phi, an AI developed by Microsoft. How can I help you today?
```
However, if running in a Jupyter notebook, then Guidance provides a widget for a richer user experience:
<img src="docs/figures/widget_basic_example_20250703.png" alt="Guidance widget showing HTML generation" />
With Guidance, it's really easy to capture generated text:
```python
# Get a new copy of the Model
lm = phi_lm
with system():
lm += "You are a helpful assistant"
with user():
lm += "Hello. What is your name?"
with assistant():
lm += gen(name="lm_response", max_tokens=20)
print(f"{lm['lm_response']=}")
```
```
lm['lm_response']='I am Phi, an AI developed by Microsoft. How can I help you today?'
```
### Guarantee output syntax with constrained generation
Guidance provides an easy to use, yet immensely powerful syntax for constraining the output of a language model.
For example, a `gen()` call can be constrained to match a regular expression:
```python
lm = phi_lm
with system():
lm += "You are a teenager"
with user():
lm += "How old are you?"
with assistant():
lm += gen("lm_age", regex=r"\d+", temperature=0.8)
print(f"The language model is {lm['lm_age']} years old")
```
```
The language model is 13 years old
```
Often, we know that the output has to be an item from a list we know in advance.
Guidance provides a `select()` function for this scenario:
```python
from guidance import select
lm = phi_lm
with system():
lm += "You are a geography expert"
with user():
lm += """What is the capital of Sweden? Answer with the correct letter.
A) Helsinki
B) Reykjavík
C) Stockholm
D) Oslo
"""
with assistant():
lm += select(["A", "B", "C", "D"], name="model_selection")
print(f"The model selected {lm['model_selection']}")
```
```
The model selected C
```
The constraint system offered by Guidance is extremely powerful.
It can ensure that the output conforms to any context free grammar (so long as the backend LLM has full support for Guidance).
More on this below.
### Debug grammars offline (no model API calls)
When iterating on constraints, you can validate candidate strings locally and test a full run with the `Mock` model.
```python
from guidance import gen
from guidance.models import Mock
grammar = "expr=" + gen(regex=r"\d+([+*]\d+)*", name="expr")
# 1) Validate strings directly against the grammar
assert grammar.match("expr=12+7*3") is not None
assert grammar.match("expr=12+*3") is None
# 2) Run the same grammar with a local mock model
lm = Mock(b"<s>expr=12+7*3")
lm += grammar
print(lm["expr"]) # 12+7*3
```
### Create your own Guidance functions
With Guidance, you can create your own Guidance functions which can interact with language models.
These are marked using the `@guidance` decorator.
Suppose we wanted to answer lots of multiple choice questions.
We could do something like the following:
```python
import guidance
from guidance.models import Model
ASCII_OFFSET = ord("a")
@guidance
def zero_shot_multiple_choice(
language_model: Model,
question: str,
choices: list[str],
):
with user():
language_model += question + "\n"
for i, choice in enumerate(choices):
language_model += f"{chr(i+ASCII_OFFSET)} : {choice}\n"
with assistant():
language_model += select(
[chr(i + ASCII_OFFSET) for i in range(len(choices))], name="string_choice"
)
return language_model
```
Now, define some questions:
```python
questions = [
{
"question" : "Which state has the northernmost capital?",
"choices" : [
"New South Wales",
"Northern Territory",
"Queensland",
"South Australia",
"Tasmania",
"Victoria",
"Western Australia",
],
"answer" : 1,
},
{
"question" : "Which of the following is venomous?",
"choices" : [
"Kangaroo",
"Koala Bear",
"Platypus",
],
"answer" : 2,
}
]
```
We can use our decorated function like `gen()` or `select()`.
The `language_model` argument will be filled in for us automatically:
```python
lm = phi_lm
with system():
lm += "You are a student taking a multiple choice test."
for mcq in questions:
lm_temp = lm + zero_shot_multiple_choice(question=mcq["question"], choices=mcq["choices"])
converted_answer = ord(lm_temp["string_choice"]) - ASCII_OFFSET
print(lm_temp)
print(f"LM Answer: {converted_answer}, Correct Answer: {mcq['answer']}")
```
```
<|system|>You are a student taking a multiple choice test.<|end|><|user|>Which state has the northernmost capital?
a : New South Wales
b : Northern Territory
c : Queensland
d : South Australia
e : Tasmania
f : Victoria
g : Western Australia
<|end|><|assistant|>b
LM Answer: 1, Correct Answer: 1
<|system|>You are a student taking a multiple choice test.<|end|><|user|>Which of the following is venomous?
a : Kangaroo
b : Koala Bear
c : Platypus
<|end|><|assistant|>c
LM Answer: 2, Correct Answer: 2
```
Guidance functions can be composed, in order to construct a full context free grammar.
For example, we can create Guidance functions to build a simple HTML webpage (note that this is _not_ a full implementation of HTML).
We start with a simple function which will generate text which does not contain any HTML tags.
The function is marked as `stateless` to indicate that we intend to use it for composing a grammar:
```python
@guidance(stateless=True)
def _gen_text(lm: Model):
return lm + gen(regex="[^<>]+")
```
We can then use this function to generate text within an arbitrary HTML tag:
```python
@guidance(stateless=True)
def _gen_text_in_tag(lm: Model, tag: str):
lm += f"<{tag}>"
lm += _gen_text()
lm += f"</{tag}>"
return lm
```
Now, let us create the page header. As part of this, we need to generate a page title:
```python
@guidance(stateless=True)
def _gen_header(lm: Model):
lm += "<head>\n"
lm += _gen_text_in_tag("title") + "\n"
lm += "</head>\n"
return lm
```
The body of the HTML page is going to be filled with headings and paragraphs.
We can define a function to do each:
```python
from guidance.library import one_or_more
@guidance(stateless=True)
def _gen_heading(lm: Model):
lm += select(
options=[_gen_text_in_tag("h1"), _gen_text_in_tag("h2"), _gen_text_in_tag("h3")]
)
lm += "\n"
return lm
@guidance(stateless=True)
def _gen_para(lm: Model):
lm += "<p>"
lm += one_or_more(
select(
options=[
_gen_text(),
_gen_text_in_tag("em"),
_gen_text_in_tag("strong"),
"<br />",
],
)
)
lm += "</p>\n"
return lm
```
Now, the function to define the body of the HTML itself:
```python
@guidance(stateless=True)
def _gen_body(lm: Model):
lm += "<body>\n"
lm += one_or_more(select(options=[_gen_heading(), one_or_more(_gen_para())]))
lm += "</body>\n"
return lm
```
Next, we come to the function which generates the complete HTML page.
We add the HTML start tag, then generate the header, then body, and then append the ending HTML tag:
```python
@guidance(stateless=True)
def _gen_html(lm: Model):
lm += "<html>\n"
lm += _gen_header()
lm += _gen_body()
lm += "</html>\n"
return lm
```
Finally, we provide a user-friendly wrapper, which will allow us to:
- Set the temperature of the generation
- Capture the generated page from the Model object
```python
from guidance.library import capture, with_temperature
@guidance(stateless=True)
def make_html(
lm,
name: str | None = None,
*,
temperature: float = 0.0,
):
return lm + capture(
with_temperature(_gen_html(), temperature=temperature),
name=name,
)
```
Now, use this to generate a simple webpage:
```python
lm = phi_lm
with system():
lm += "You are an expert in HTML"
with user():
lm += "Create a simple and short web page about your life story."
with assistant():
lm += make_html(name="html_text", temperature=0.7)
```
When running in a Jupyter Notebook so that the widget is active, we get the following output:
<img src="docs/figures/widget_make_html_20250703.png" alt="Guidance widget showing HTML generation with token fast-forwarding" />
Note the varying highlighting of the generation.
This is showing another of Guidance's capabilities: fast-forwarding of tokens.
The constraints imposed by a grammar often mean that some tokens are known in advance.
Guidance doesn't need the model to generate these; instead it can insert them into the generation.
This saves forward passes through the model, and hence reduces GPU usage.
For example, in the above HTML generation, Guidance always knows the last opening tag.
If the last opened tag was `<h1>` (for example), then as soon as the model generates `</`, Guidance can fill in `h1>` without needing the model to perform a forward pass.
### Generating JSON
A JSON schema is actually a context free grammar, and hence it can be used to constrain an LLM using Guidance.
This is a common enough case that Guidance provides special support for it.
A quick sample, based on a Pydantic model:
```python
import json
from pydantic import BaseModel, Field
from guidance import json as gen_json
class BloodPressure(BaseModel):
systolic: int = Field(gt=300, le=400)
diastolic: int = Field(gt=0, le=20)
location: str = Field(max_length=50)
model_config = dict(extra="forbid")
lm = phi_lm
with system():
lm += "You are a doctor taking a patient's blood pressure taken from their arm"
with user():
lm += "Report the blood pressure"
with assistant():
lm += gen_json(name="bp", schema=BloodPressure)
print(f"{lm['bp']=}")
# Use Python's JSON library
loaded_json = json.loads(lm["bp"])
print(json.dumps(loaded_json, indent=4))
# Use Pydantic
result = BloodPressure.model_validate_json(lm["bp"])
print(result.model_dump_json(indent=8))
```
```
lm['bp']='{"systolic": 301, "diastolic": 15, "location": "arm"}'
{
"systolic": 301,
"diastolic": 15,
"location": "arm"
}
{
"systolic": 301,
"diastolic": 15,
"location": "arm"
}
```
Note that the generated blood pressure is not one the model will have seen for a human.
When generating JSON, a substantial number of tokens can often be fast-forwarded, due to the structural constraints imposed by the schema.
历史前置条件说明(补充参考)
Python 环境(版本要求待核验);需自行选择并配置模型后端(Transformers、llama.cpp、OpenAI 等),API Key 与费用按所选服务商规则,资料未给出具体配置;本地模型需自行准备权重与算力,硬件要求待核验;平台支持情况待核验。
项目来源与清单版权许可
https://github.com/guidance-ai/guidance
https://guidance.readthedocs.org/
整理来源:https://github.com/slavakurilyak/awesome-ai-agents
清单版权与许可:
MIT License
Copyright (c) 2024 Slava Kurilyak
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.