{"id":24823968,"url":"https://github.com/cvs-health/langfair","last_synced_at":"2025-10-13T22:31:42.787Z","repository":{"id":258740154,"uuid":"860612327","full_name":"cvs-health/langfair","owner":"cvs-health","description":"LangFair is a Python library for conducting use-case level LLM bias and fairness assessments","archived":false,"fork":false,"pushed_at":"2025-10-08T01:30:37.000Z","size":33250,"stargazers_count":236,"open_issues_count":21,"forks_count":40,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-10-10T16:38:02.353Z","etag":null,"topics":["ai","ai-safety","artificial-intelligence","bias","bias-detection","ethical-ai","fairness","fairness-ai","fairness-ml","fairness-testing","large-language-models","llm","llm-evaluation","llm-evaluation-framework","llm-evaluation-metrics","python","responsible-ai"],"latest_commit_sha":null,"homepage":"https://cvs-health.github.io/langfair/","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/cvs-health.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":"security-insights.yml","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2024-09-20T19:11:29.000Z","updated_at":"2025-10-05T06:52:15.000Z","dependencies_parsed_at":"2025-05-03T03:38:54.161Z","dependency_job_id":"c24db849-abce-42e9-a443-e22177d9ace2","html_url":"https://github.com/cvs-health/langfair","commit_stats":null,"previous_names":["cvs-health/llambda","cvs-health/langfair"],"tags_count":24,"template":false,"template_full_name":null,"purl":"pkg:github/cvs-health/langfair","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cvs-health%2Flangfair","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cvs-health%2Flangfair/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cvs-health%2Flangfair/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cvs-health%2Flangfair/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/cvs-health","download_url":"https://codeload.github.com/cvs-health/langfair/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/cvs-health%2Flangfair/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":279006611,"owners_count":26084148,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-11T02:00:06.511Z","response_time":55,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","ai-safety","artificial-intelligence","bias","bias-detection","ethical-ai","fairness","fairness-ai","fairness-ml","fairness-testing","large-language-models","llm","llm-evaluation","llm-evaluation-framework","llm-evaluation-metrics","python","responsible-ai"],"created_at":"2025-01-30T20:02:00.749Z","updated_at":"2025-10-13T22:31:42.781Z","avatar_url":"https://github.com/cvs-health.png","language":"Python","funding_links":[],"categories":["*Ops for AI","Recently Updated","Technical Resources","Safety \u0026 Governance","Tools","LLMOps"],"sub_categories":["LLMOps","[Jan 30, 2025](/content/2025/01/30/README.md)","Open Source/Access Responsible AI Software Packages","Sandboxing \u0026 Execution","Services","LLM Evaluation \u0026 Testing"],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://raw.githubusercontent.com/cvs-health/langfair/main/assets/images/langfair-logo.png\" /\u003e\n\u003c/p\u003e\n\n# LangFair: Use-Case Level LLM Bias and Fairness Assessments\n[![Build Status](https://github.com/cvs-health/langfair/actions/workflows/ci.yaml/badge.svg)](https://github.com/cvs-health/langfair/actions)\n[![PyPI version](https://badge.fury.io/py/langfair.svg)](https://pypi.org/project/langfair/)\n[![Downloads](https://img.shields.io/pepy/dt/langfair)](https://pepy.tech/projects/langfair?timeRange=threeMonths\u0026category=version\u0026includeCIDownloads=true\u0026granularity=daily\u0026viewType=line\u0026versions=0.6.3%2C0.6.2%2C0.6.1)\n[![Documentation Status](https://img.shields.io/badge/docs-latest-blue.svg)](https://cvs-health.github.io/langfair/latest/index.html)\n[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff)\n[![](https://img.shields.io/badge/arXiv-2407.10853-B31B1B.svg)](https://arxiv.org/abs/2407.10853)\n\n\nLangFair is a comprehensive Python library designed for conducting bias and fairness assessments of large language model (LLM) use cases. This repository includes various supporting resources, including\n\n- [Documentation site](https://cvs-health.github.io/langfair/) with complete API reference\n- [Comprehensive framework](https://github.com/cvs-health/langfair/tree/main#-choosing-bias-and-fairness-metrics-for-an-llm-use-case) for choosing bias and fairness metrics\n- [Demo notebooks](https://github.com/cvs-health/langfair/tree/main#-example-notebooks) providing illustrative examples\n- [LangFair tutorial](https://medium.com/cvs-health-tech-blog/how-to-assess-your-llm-use-case-for-bias-and-fairness-with-langfair-7be89c0c4fab) on Medium\n- [Software paper](https://arxiv.org/abs/2501.03112v1) on how LangFair compares to other toolkits\n- [Research paper](https://arxiv.org/abs/2407.10853) on our evaluation approach\n\n## 🚀 Why Choose LangFair?\nStatic benchmark assessments, which are typically assumed to be sufficiently representative, often fall short in capturing the risks associated with all possible use cases of LLMs. These models are increasingly used in various applications, including recommendation systems, classification, text generation, and summarization. However, evaluating these models without considering use-case-specific prompts can lead to misleading assessments of their performance, especially regarding bias and fairness risks.\n \nLangFair addresses this gap by adopting a Bring Your Own Prompts (BYOP) approach, allowing users to tailor bias and fairness evaluations to their specific use cases. This ensures that the metrics computed reflect the true performance of the LLMs in real-world scenarios, where prompt-specific risks are critical. Additionally, LangFair's focus is on output-based metrics that are practical for governance audits and real-world testing, without needing access to internal model states.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://raw.githubusercontent.com/cvs-health/langfair/release-branch/v0.4.0/assets/images/langfair_graphic.png\" /\u003e\n\u003c/p\u003e\n\n**Note:** This diagram illustrates the workflow for assessing bias and fairness in text generation and summarization use cases.\n\n## ⚡ Quickstart Guide\n### (Optional) Create a virtual environment for using LangFair\nWe recommend creating a new virtual environment using venv before installing LangFair. To do so, please follow instructions [here](https://docs.python.org/3/library/venv.html).\n\n### Installing LangFair\nThe latest version can be installed from PyPI:\n\n```bash\npip install langfair\n```\n\n### Usage Examples\nBelow are code samples illustrating how to use LangFair to assess bias and fairness risks in text generation and summarization use cases. The below examples assume the user has already defined a list of prompts from their use case, `prompts`. \n\n##### Generate LLM responses\nTo generate responses, we can use LangFair's `ResponseGenerator` class. First, we must create a `langchain` LLM object. Below we use `ChatVertexAI`, but **any of [LangChain’s LLM classes](https://js.langchain.com/docs/integrations/chat/) may be used instead**. Note that `InMemoryRateLimiter` is to used to avoid rate limit errors.\n```python\nfrom langchain_google_vertexai import ChatVertexAI\nfrom langchain_core.rate_limiters import InMemoryRateLimiter\nrate_limiter = InMemoryRateLimiter(\n    requests_per_second=4.5, check_every_n_seconds=0.5, max_bucket_size=280,  \n)\nllm = ChatVertexAI(\n    model_name=\"gemini-pro\", temperature=0.3, rate_limiter=rate_limiter\n)\n```\nWe can use `ResponseGenerator.generate_responses` to generate 25 responses for each prompt, as is convention for toxicity evaluation.\n```python\nfrom langfair.generator import ResponseGenerator\nrg = ResponseGenerator(langchain_llm=llm)\ngenerations = await rg.generate_responses(prompts=prompts, count=25)\nresponses = generations[\"data\"][\"response\"]\nduplicated_prompts = generations[\"data\"][\"prompt\"] # so prompts correspond to responses\n```\n\n##### Compute toxicity metrics\nToxicity metrics can be computed with `ToxicityMetrics`. Note that use of `torch.device` is optional and should be used if GPU is available to speed up toxicity computation.\n```python\n# import torch # uncomment if GPU is available\n# device = torch.device(\"cuda\") # uncomment if GPU is available\nfrom langfair.metrics.toxicity import ToxicityMetrics\ntm = ToxicityMetrics(\n    # device=device, # uncomment if GPU is available,\n)\ntox_result = tm.evaluate(\n    prompts=duplicated_prompts, \n    responses=responses, \n    return_data=True\n)\ntox_result['metrics']\n# # Output is below\n# {'Toxic Fraction': 0.0004,\n# 'Expected Maximum Toxicity': 0.013845130120171235,\n# 'Toxicity Probability': 0.01}\n```\n\n##### Compute stereotype metrics\nStereotype metrics can be computed with `StereotypeMetrics`.\n```python\nfrom langfair.metrics.stereotype import StereotypeMetrics\nsm = StereotypeMetrics()\nstereo_result = sm.evaluate(responses=responses, categories=[\"gender\"])\nstereo_result['metrics']\n# # Output is below\n# {'Stereotype Association': 0.3172750176745329,\n# 'Cooccurrence Bias': 0.44766333654278373,\n# 'Stereotype Fraction - gender': 0.08}\n```\n\n##### Generate counterfactual responses and compute metrics\nWe can generate counterfactual responses with `CounterfactualGenerator`.\n```python\nfrom langfair.generator.counterfactual import CounterfactualGenerator\ncg = CounterfactualGenerator(langchain_llm=llm)\ncf_generations = await cg.generate_responses(\n    prompts=prompts, attribute='gender', count=25\n)\nmale_responses = cf_generations['data']['male_response']\nfemale_responses = cf_generations['data']['female_response']\n```\n\nCounterfactual metrics can be easily computed with `CounterfactualMetrics`.\n```python\nfrom langfair.metrics.counterfactual import CounterfactualMetrics\ncm = CounterfactualMetrics()\ncf_result = cm.evaluate(\n    texts1=male_responses, \n    texts2=female_responses,\n    attribute='gender'\n)\ncf_result['metrics']\n# # Output is below\n# {'Cosine Similarity': 0.8318708,\n# 'RougeL Similarity': 0.5195852482361165,\n# 'Bleu Similarity': 0.3278433712872481,\n# 'Sentiment Bias': 0.0009947145187601957}\n```\n\n##### Alternative approach: Semi-automated evaluation with `AutoEval`\nTo streamline assessments for text generation and summarization use cases, the `AutoEval` class conducts a multi-step process that completes all of the aforementioned steps with two lines of code.\n```python\nfrom langfair.auto import AutoEval\nauto_object = AutoEval(\n    prompts=prompts, \n    langchain_llm=llm,\n    # toxicity_device=device # uncomment if GPU is available\n)\nresults = await auto_object.evaluate()\nresults['metrics']\n# # Output is below\n# {'Toxicity': {'Toxic Fraction': 0.0004,\n#   'Expected Maximum Toxicity': 0.013845130120171235,\n#   'Toxicity Probability': 0.01},\n#  'Stereotype': {'Stereotype Association': 0.3172750176745329,\n#   'Cooccurrence Bias': 0.44766333654278373,\n#   'Stereotype Fraction - gender': 0.08,\n#   'Expected Maximum Stereotype - gender': 0.60355167388916,\n#   'Stereotype Probability - gender': 0.27036},\n#  'Counterfactual': {'male-female': {'Cosine Similarity': 0.8318708,\n#    'RougeL Similarity': 0.5195852482361165,\n#    'Bleu Similarity': 0.3278433712872481,\n#    'Sentiment Bias': 0.0009947145187601957}}}\n```\n\n## 📚 Example Notebooks\nExplore the following demo notebooks to see how to use LangFair for various bias and fairness evaluation metrics:\n\n- [Toxicity Evaluation](https://github.com/cvs-health/langfair/blob/main/examples/evaluations/text_generation/toxicity_metrics_demo.ipynb): A notebook demonstrating toxicity metrics.\n- [Counterfactual Fairness Evaluation](https://github.com/cvs-health/langfair/blob/main/examples/evaluations/text_generation/counterfactual_metrics_demo.ipynb): A notebook illustrating how to generate counterfactual datasets and compute counterfactual fairness metrics.\n- [Stereotype Evaluation](https://github.com/cvs-health/langfair/blob/main/examples/evaluations/text_generation/stereotype_metrics_demo.ipynb): A notebook demonstrating stereotype metrics.\n- [AutoEval for Text Generation / Summarization (Toxicity, Stereotypes, Counterfactual)](https://github.com/cvs-health/langfair/blob/main/examples/evaluations/text_generation/auto_eval_demo.ipynb): A notebook illustrating how to use LangFair's `AutoEval` class for a comprehensive fairness assessment of text generation / summarization use cases. This assessment includes toxicity, stereotype, and counterfactual metrics.\n- [Classification Fairness Evaluation](https://github.com/cvs-health/langfair/blob/main/examples/evaluations/classification/classification_metrics_demo.ipynb): A notebook demonstrating classification fairness metrics.\n- [Recommendation Fairness Evaluation](https://github.com/cvs-health/langfair/blob/main/examples/evaluations/recommendation/recommendation_metrics_demo.ipynb): A notebook demonstrating recommendation fairness metrics.\n\n\n## 🛠 Choosing Bias and Fairness Metrics for an LLM Use Case\nSelecting the appropriate bias and fairness metrics is essential for accurately assessing the performance of large language models (LLMs) in specific use cases. Instead of attempting to compute all possible metrics, practitioners should focus on a relevant subset that aligns with their specific goals and the context of their application.\n\nOur decision framework for selecting appropriate evaluation metrics is illustrated in the diagram below. For more details, refer to our [research paper](https://arxiv.org/abs/2407.10853) detailing the evaluation approach.\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://raw.githubusercontent.com/cvs-health/langfair/main/assets/images/use_case_framework.PNG\" /\u003e\n\u003c/p\u003e\n\n**Note:** Fairness through unawareness means none of the prompts for an LLM use case include any mention of protected attribute words.\n\n## 📊 Supported Bias and Fairness Metrics\nBias and fairness metrics offered by LangFair are grouped into several categories. The full suite of metrics is displayed below.\n\n##### Toxicity Metrics\n* Expected Maximum Toxicity ([Gehman et al., 2020](https://arxiv.org/abs/2009.11462))\n* Toxicity Probability ([Gehman et al., 2020](https://arxiv.org/abs/2009.11462))\n* Toxic Fraction ([Liang et al., 2023](https://arxiv.org/abs/2211.09110))\n\n##### Counterfactual Fairness Metrics\n* Strict Counterfactual Sentiment Parity ([Huang et al., 2020](https://arxiv.org/abs/1911.03064))\n* Weak Counterfactual Sentiment Parity ([Bouchard, 2024](https://arxiv.org/abs/2407.10853))\n* Counterfactual Cosine Similarity Score ([Bouchard, 2024](https://arxiv.org/abs/2407.10853))\n* Counterfactual BLEU ([Bouchard, 2024](https://arxiv.org/abs/2407.10853))\n* Counterfactual ROUGE-L ([Bouchard, 2024](https://arxiv.org/abs/2407.10853))\n\n##### Stereotype Metrics\n* Stereotypical Associations ([Liang et al., 2023](https://arxiv.org/abs/2211.09110))\n* Co-occurrence Bias Score ([Bordia \u0026 Bowman, 2019](https://arxiv.org/abs/1904.03035))\n* Stereotype classifier metrics ([Zekun et al., 2023](https://arxiv.org/abs/2311.14126), [Bouchard, 2024](https://arxiv.org/abs/2407.10853))\n\n##### Recommendation (Counterfactual) Fairness Metrics\n* Jaccard Similarity ([Zhang et al., 2023](https://dl.acm.org/doi/10.1145/3604915.3608860))\n* Search Result Page Misinformation Score ([Zhang et al., 2023](https://dl.acm.org/doi/10.1145/3604915.3608860))\n* Pairwise Ranking Accuracy Gap ([Zhang et al., 2023](https://dl.acm.org/doi/10.1145/3604915.3608860))\n\n##### Classification Fairness Metrics\n* Predicted Prevalence Rate Disparity ([Feldman et al., 2015](https://arxiv.org/abs/1412.3756); [Bellamy et al., 2018](https://arxiv.org/abs/1810.01943); [Saleiro et al., 2019](https://arxiv.org/abs/1811.05577))\n* False Negative Rate Disparity ([Bellamy et al., 2018](https://arxiv.org/abs/1810.01943); [Saleiro et al., 2019](https://arxiv.org/abs/1811.05577))\n* False Omission Rate Disparity ([Bellamy et al., 2018](https://arxiv.org/abs/1810.01943); [Saleiro et al., 2019](https://arxiv.org/abs/1811.05577))\n* False Positive Rate Disparity ([Bellamy et al., 2018](https://arxiv.org/abs/1810.01943); [Saleiro et al., 2019](https://arxiv.org/abs/1811.05577))\n* False Discovery Rate Disparity ([Bellamy et al., 2018](https://arxiv.org/abs/1810.01943); [Saleiro et al., 2019](https://arxiv.org/abs/1811.05577))\n\n\n## 📖 Associated Research\nA technical description and a practitioner's guide for selecting evaluation metrics is contained in **[this paper](https://arxiv.org/abs/2407.10853)**. If you use our evaluation approach, we would appreciate citations to the following paper:\n\n```bibtex\n@misc{bouchard2024actionableframeworkassessingbias,\n      title={An Actionable Framework for Assessing Bias and Fairness in Large Language Model Use Cases}, \n      author={Dylan Bouchard},\n      year={2024},\n      eprint={2407.10853},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL},\n      url={https://arxiv.org/abs/2407.10853}, \n}\n```\n\nA high-level description of LangFair's functionality is contained in **[this paper](https://arxiv.org/abs/2501.03112)**. If you use LangFair, we would appreciate citations to the following paper:\n\n```bibtex\n@misc{bouchard2025langfairpythonpackageassessing,\n      title={LangFair: A Python Package for Assessing Bias and Fairness in Large Language Model Use Cases}, \n      author={Dylan Bouchard and Mohit Singh Chauhan and David Skarbrevik and Viren Bajaj and Zeya Ahmad},\n      year={2025},\n      eprint={2501.03112},\n      archivePrefix={arXiv},\n      primaryClass={cs.CL},\n      url={https://arxiv.org/abs/2501.03112}, \n}\n```\n\n## 📄 Code Documentation\nPlease refer to our [documentation site](https://cvs-health.github.io/langfair/) for more details on how to use LangFair.\n\n## 🤝 Development Team\nThe open-source version of LangFair is the culmination of extensive work carried out by a dedicated team of developers. While the internal commit history will not be made public, we believe it's essential to acknowledge the significant contributions of our development team who were instrumental in bringing this project to fruition:\n\n- [Dylan Bouchard](https://github.com/dylanbouchard)\n- [Mohit Singh Chauhan](https://github.com/mohitcek)\n- [David Skarbrevik](https://github.com/dskarbrevik)\n- [Viren Bajaj](https://github.com/virenbajaj)\n- [Zeya Ahmad](https://github.com/zeya30)\n\n## 🤗 Contributing\nContributions are welcome. Please refer [here](https://github.com/cvs-health/langfair/tree/main/CONTRIBUTING.md) for instructions on how to contribute to LangFair.","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcvs-health%2Flangfair","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fcvs-health%2Flangfair","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fcvs-health%2Flangfair/lists"}