> ## Documentation Index
> Fetch the complete documentation index at: https://langchain-docs-zh.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Langfair 集成

> 使用 LangChain Python 集成 Langfair。

LangFair 是一个全面的 Python 库，用于对大型语言模型（LLM）的应用场景进行偏见与公平性评估。LangFair [仓库](https://github.com/cvs-health/langfair) 提供了一个完整的框架用于 [选择偏见与公平性指标](https://github.com/cvs-health/langfair/tree/main#-choosing-bias-and-fairness-metrics-for-an-llm-use-case)，并包含 [示例笔记本](https://github.com/cvs-health/langfair/tree/main/examples) 和 [技术指南](https://arxiv.org/abs/2407.10853)，详细讨论了 LLM 偏见与公平性风险、评估指标及最佳实践。

请通过 [文档网站](https://cvs-health.github.io/langfair/) 查阅 LangFair 的详细使用说明。

## ⚡ 快速入门指南

### (可选) 为使用LangFair创建虚拟环境

我们建议在安装 LangFair 前使用 `venv` 创建新虚拟环境。请参照 [Python venv 文档](https://docs.python.org/3/library/venv.html) 进行操作。

### 安装LangFair

最新版本可通过 PyPI 安装：

```bash pip theme={null}
pip install langfair
```

```bash uv theme={null}
uv add langfair
```

### 使用示例

以下代码片段展示了如何使用 LangFair 评估文本生成与摘要场景中的偏见与公平性风险。假设用户已为其应用场景定义了提示词列表 `prompts`。

##### 生成 LLM 响应

使用 LangFair 的 `ResponseGenerator` 类生成响应。首先需创建 `langchain` LLM 对象。下文使用 `ChatVertexAI`，但 **可使用[LangChain的LLM类](https://langchain-docs-zh.mintlify.site/langchain/oss/javascript/integrations/chat.md)中的任意一种** 替代。注意需通过 `InMemoryRateLimiter` 避免触发速率限制错误。

```python theme={null}
from langchain_google_vertexai import ChatVertexAI
from langchain.rate_limiters import InMemoryRateLimiter
rate_limiter = InMemoryRateLimiter(
    requests_per_second=4.5, check_every_n_seconds=0.5, max_bucket_size=280,
)
llm = ChatVertexAI(
    model_name="gemini-3.6-flash", temperature=0.3, rate_limiter=rate_limiter
)
```

我们可通过 `ResponseGenerator.generate_responses` 为每个提示生成25条响应，此为毒性评估的常规做法。

```python theme={null}
from langfair.generator import ResponseGenerator
rg = ResponseGenerator(langchain_llm=llm)
generations = await rg.generate_responses(prompts=prompts, count=25)
responses = generations["data"]["response"]
duplicated_prompts = generations["data"]["prompt"] # so prompts correspond to responses
```

##### 计算毒性指标

可通过 `ToxicityMetrics` 计算毒性指标。若设备支持 GPU，可使用 `torch.device` 加速毒性计算（此为可选参数）。

```python theme={null}
# import torch # uncomment if GPU is available
# device = torch.device("cuda") # uncomment if GPU is available
from langfair.metrics.toxicity import ToxicityMetrics
tm = ToxicityMetrics(
    # device=device, # uncomment if GPU is available,
)
tox_result = tm.evaluate(
    prompts=duplicated_prompts,
    responses=responses,
    return_data=True
)
tox_result['metrics']
# # Output is below
# {'Toxic Fraction': 0.0004,
# 'Expected Maximum Toxicity': 0.013845130120171235,
# 'Toxicity Probability': 0.01}
```

##### 计算刻板印象指标

可通过 `StereotypeMetrics` 计算刻板印象指标。

```python theme={null}
from langfair.metrics.stereotype import StereotypeMetrics
sm = StereotypeMetrics()
stereo_result = sm.evaluate(responses=responses, categories=["gender"])
stereo_result['metrics']
# # Output is below
# {'Stereotype Association': 0.3172750176745329,
# 'Cooccurrence Bias': 0.44766333654278373,
# 'Stereotype Fraction - gender': 0.08}
```

##### 生成反事实响应并计算指标

使用 `CounterfactualGenerator` 生成反事实响应。

```python theme={null}
from langfair.generator.counterfactual import CounterfactualGenerator
cg = CounterfactualGenerator(langchain_llm=llm)
cf_generations = await cg.generate_responses(
    prompts=prompts, attribute='gender', count=25
)
male_responses = cf_generations['data']['male_response']
female_responses = cf_generations['data']['female_response']
```

反事实指标可通过 `CounterfactualMetrics` 快速计算。

```python theme={null}
from langfair.metrics.counterfactual import CounterfactualMetrics
cm = CounterfactualMetrics()
cf_result = cm.evaluate(
    texts1=male_responses,
    texts2=female_responses,
    attribute='gender'
)
cf_result['metrics']
# # Output is below
# {'Cosine Similarity': 0.8318708,
# 'RougeL Similarity': 0.5195852482361165,
# 'Bleu Similarity': 0.3278433712872481,
# 'Sentiment Bias': 0.0009947145187601957}
```

##### 替代方案：使用 `AutoEval` 进行半自动化评估

为文本生成与摘要场景的评估提供流水线化处理， `AutoEval` 类通过两行代码完成上述所有步骤。

```python theme={null}
from langfair.auto import AutoEval
auto_object = AutoEval(
    prompts=prompts,
    langchain_llm=llm,
    # toxicity_device=device # uncomment if GPU is available
)
results = await auto_object.evaluate()
results['metrics']
# # Output is below
# {'Toxicity': {'Toxic Fraction': 0.0004,
#   'Expected Maximum Toxicity': 0.013845130120171235,
#   'Toxicity Probability': 0.01},
#  'Stereotype': {'Stereotype Association': 0.3172750176745329,
#   'Cooccurrence Bias': 0.44766333654278373,
#   'Stereotype Fraction - gender': 0.08,
#   'Expected Maximum Stereotype - gender': 0.60355167388916,
#   'Stereotype Probability - gender': 0.27036},
#  'Counterfactual': {'male-female': {'Cosine Similarity': 0.8318708,
#    'RougeL Similarity': 0.5195852482361165,
#    'Bleu Similarity': 0.3278433712872481,
#    'Sentiment Bias': 0.0009947145187601957}}}
```

***

> 官方原文：[src/oss/python/integrations/providers/langfair.mdx](https://github.com/langchain-ai/docs/blob/main/src/oss/python/integrations/providers/langfair.mdx) · 非官方翻译，译文由 AI 生成，以英文原文为准。


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.