LLM Adapters:使用多种结构化输出后端
Ragas 通过 adapter 模式支持多种结构化输出后端。本指南说明如何为不同 LLM 提供商使用不同 adapters。
概述
Ragas 使用 adapters 来处理来自不同 LLM 提供商的结构化输出:
- Instructor Adapter:适用于 OpenAI、Anthropic、Azure、Groq、Mistral、Cohere 以及许多其他提供商
- LiteLLM Adapter:适用于全部 100+ LiteLLM 支持的提供商(Gemini、Ollama、vLLM、Bedrock 等)
框架会自动为你的提供商选择最佳 adapter,但你也可以显式选择。
快速开始
自动 Adapter 选择(推荐)
让 Ragas 自动检测最佳 adapter:
from ragas.llms import llm_factory
from openai import OpenAI
# For OpenAI - automatically uses Instructor adapter
client = OpenAI(api_key="...")
llm = llm_factory("gpt-4o-mini", client=client)
from ragas.llms import llm_factory
import google.generativeai as genai
# For Gemini - automatically uses LiteLLM adapter
genai.configure(api_key="...")
client = genai.GenerativeModel("gemini-2.0-flash")
llm = llm_factory("gemini-2.0-flash", provider="google", client=client)
显式 Adapter 选择
如果你需要更多控制,选择特定 adapter:
from ragas.llms import llm_factory
# Force using Instructor adapter
llm = llm_factory("gpt-4o", client=client, adapter="instructor")
# Force using LiteLLM adapter
llm = llm_factory("gemini-2.0-flash", client=client, adapter="litellm")
自动检测逻辑
当 adapter="auto"(默认)时,Ragas 使用以下逻辑:
- 检查 client 类型:如果 client 来自
litellm模块 → 使用 LiteLLM adapter - 检查 provider:如果 provider 是
google或gemini→ 使用 LiteLLM adapter - 默认:其他所有情况使用 Instructor adapter
from ragas.llms.adapters import auto_detect_adapter
# See which adapter will be used
adapter_name = auto_detect_adapter(client, "google")
print(adapter_name) # Output: "litellm"
adapter_name = auto_detect_adapter(client, "openai")
print(adapter_name) # Output: "instructor"
提供商特定示例
OpenAI
from openai import OpenAI
from ragas.llms import llm_factory
client = OpenAI(api_key="your-key")
llm = llm_factory("gpt-4o", client=client)
# Uses Instructor adapter automatically
Anthropic Claude
from anthropic import Anthropic
from ragas.llms import llm_factory
client = Anthropic(api_key="your-key")
llm = llm_factory("claude-3-sonnet", provider="anthropic", client=client)
# Uses Instructor adapter automatically
Google Gemini(使用 google-generativeai - 推荐)
import google.generativeai as genai
from ragas.llms import llm_factory
genai.configure(api_key="your-key")
client = genai.GenerativeModel("gemini-2.0-flash")
llm = llm_factory("gemini-2.0-flash", provider="google", client=client)
# Uses LiteLLM adapter automatically for google provider
Google Gemini(使用 LiteLLM Proxy - 高级)
from openai import OpenAI
from ragas.llms import llm_factory
# Requires running: litellm --model gemini-2.0-flash
client = OpenAI(
api_key="anything",
base_url="http://0.0.0.0:4000" # LiteLLM proxy endpoint
)
llm = llm_factory("gemini-2.0-flash", client=client, adapter="litellm")
# Uses LiteLLM adapter explicitly
本地模型(Ollama)
from openai import OpenAI
from ragas.llms import llm_factory
# Ollama exposes OpenAI-compatible API
client = OpenAI(
api_key="ollama",
base_url="http://localhost:11434/v1"
)
llm = llm_factory("mistral", provider="openai", client=client)
# Uses Instructor adapter
AWS Bedrock
from openai import OpenAI
from ragas.llms import llm_factory
# Use LiteLLM proxy for Bedrock
# Note: Set up LiteLLM with Bedrock credentials first
client = OpenAI(
api_key="", # Bedrock uses IAM auth
base_url="http://0.0.0.0:4000" # LiteLLM proxy endpoint
)
llm = llm_factory("claude-3-sonnet", client=client, adapter="litellm")
Groq
from groq import Groq
from ragas.llms import llm_factory
client = Groq(api_key="your-key")
llm = llm_factory("mixtral-8x7b", provider="groq", client=client)
# Uses Instructor adapter automatically
Mistral
from mistralai import Mistral
from ragas.llms import llm_factory
client = Mistral(api_key="your-key")
llm = llm_factory("mistral-large", provider="mistral", client=client)
# Uses Instructor adapter automatically
Cohere
from cohere import Cohere
from ragas.llms import llm_factory
client = Cohere(api_key="your-key")
llm = llm_factory("command-r-plus", provider="cohere", client=client)
# Uses Instructor adapter automatically
Adapter 选择指南
根据你的需求选择 adapter:
在以下情况使用 Instructor Adapter:
- 使用 OpenAI、Anthropic、Azure、Groq、Mistral 或 Cohere
- 提供商被 Instructor 原生支持
- 你想要最稳定、经过充分测试的选项
- 提供商不需要特殊处理
在以下情况使用 LiteLLM Adapter:
- 使用 Google Gemini
- 使用本地模型(Ollama、vLLM 等)
- 使用有 100+ 选项的提供商(Bedrock 等)
- 你需要最大的提供商兼容性
- 自动检测为你的提供商选择了它
直接使用 Adapters
获取可用 Adapters
from ragas.llms.adapters import ADAPTERS
print(ADAPTERS)
# Output: {
# "instructor": InstructorAdapter(),
# "litellm": LiteLLMAdapter()
# }
获取特定 Adapter
from ragas.llms.adapters import get_adapter
instructor = get_adapter("instructor")
litellm = get_adapter("litellm")
# Create LLM using adapter directly
llm = instructor.create_llm(client, "gpt-4o", "openai")
高级用法
模型参数
所有 adapters 支持相同的模型参数:
llm = llm_factory(
"gpt-4o",
client=client,
temperature=0.7,
max_tokens=2048,
top_p=0.9,
)
System Prompts
两个 adapters 都支持需要特定指令的模型的 system prompts:
llm = llm_factory(
"gpt-4o",
client=client,
system_prompt="You are a helpful assistant that evaluates RAG systems."
)
System prompts 在以下情况有用: - 你的 LLM 需要特定行为指令 - 你在使用带自定义 system prompts 的微调模型 - 你想在所有指标中引导评测风格
System prompt 会作为 system message 前置到所有 LLM 调用中。
自定义 Instructor Modes
instructor adapter 支持多种结构化输出生成模式。默认使用 Mode.JSON,但你可以为不支持某些功能的后端指定不同模式:
import instructor
from ragas.llms import llm_factory
from openai import OpenAI
# Use MD_JSON mode for backends without response_format support
client = OpenAI(api_key="...", base_url="https://custom-backend")
llm = llm_factory(
"custom-model",
provider="openai",
client=client,
mode=instructor.Mode.MD_JSON
)
可用的 instructor modes:
- Mode.JSON(默认)- 使用 OpenAI 的 response_format 参数
- Mode.MD_JSON - 在 prompt 中使用 markdown JSON(不支持的后端的回退)
- Mode.TOOLS - 使用 function calling
- Mode.JSON_SCHEMA - 使用 JSON schema 验证
当你遇到如下错误时使用 Mode.MD_JSON:
Error code: 400 - {'message': 'only pytorch backend can use response_format now'}
异步支持
两个 adapters 都支持异步操作:
from openai import AsyncOpenAI
from ragas.llms import llm_factory
async_client = AsyncOpenAI(api_key="...")
llm = llm_factory("gpt-4o", client=async_client)
# Async generation
response = await llm.agenerate(prompt, ResponseModel)
用 LiteLLM 使用自定义提供商
LiteLLM 支持许多 Instructor 未覆盖的提供商。使用 LiteLLM proxy 方法:
from openai import OpenAI
from ragas.llms import llm_factory
# Set up LiteLLM proxy first:
# litellm --model grok-1 (for xAI)
# litellm --model deepseek-chat (for DeepSeek)
# etc.
client = OpenAI(
api_key="your-provider-api-key",
base_url="http://0.0.0.0:4000" # LiteLLM proxy endpoint
)
# xAI Grok
llm = llm_factory("grok-1", client=client, adapter="litellm")
# DeepSeek
llm = llm_factory("deepseek-chat", client=client, adapter="litellm")
# Together AI
llm = llm_factory("mistral-7b", client=client, adapter="litellm")
完整评测示例
from datasets import Dataset
from ragas import evaluate
from ragas.llms import llm_factory
from ragas.metrics import (
ContextPrecision,
ContextRecall,
Faithfulness,
AnswerCorrectness,
)
# Initialize LLM with your provider
import google.generativeai as genai
genai.configure(api_key="...")
client = genai.GenerativeModel("gemini-2.0-flash")
llm = llm_factory("gemini-2.0-flash", provider="google", client=client)
# Create evaluation dataset
data = {
"question": ["What is the capital of France?"],
"answer": ["Paris"],
"contexts": [["France is in Europe. Paris is its capital."]],
"ground_truth": ["Paris"]
}
dataset = Dataset.from_dict(data)
# Define metrics
metrics = [
ContextPrecision(llm=llm),
ContextRecall(llm=llm),
Faithfulness(llm=llm),
AnswerCorrectness(llm=llm),
]
# Evaluate
results = evaluate(dataset, metrics=metrics)
print(results)
故障排查
"Unknown adapter: xyz"
确保你使用的是有效的 adapter 名称:
# Valid: "instructor" or "litellm"
llm = llm_factory("model", client=client, adapter="instructor")
# Invalid: "dspy" (not yet implemented)
# llm = llm_factory("model", client=client, adapter="dspy") # Error!
"Failed to initialize provider client"
确保: 1. 你的 client 已正确初始化 2. 你的 API key 有效 3. 该提供商被 adapter 支持
# Check if adapter can handle your provider
from ragas.llms.adapters import auto_detect_adapter
adapter = auto_detect_adapter(client, "my-provider")
print(f"Will use: {adapter}")
Adapter 不匹配
自动检测能处理大多数情况,但显式选择可以提供帮助:
# If auto-detection picks the wrong adapter:
llm = llm_factory(
"model",
provider="provider-name",
client=client,
adapter="litellm" # Explicit override
)
迁移指南
从纯文本到结构化输出
如果你正在从纯文本 LLM 用法升级:
# Before (deprecated)
# from ragas.llms import LangchainLLMWrapper
# llm = LangchainLLMWrapper(langchain_llm)
# After (new way)
from ragas.llms import llm_factory
llm = llm_factory("gpt-4o", client=client)
切换提供商
要从 OpenAI 切换到 Gemini:
# Before: OpenAI
from openai import OpenAI
client = OpenAI(api_key="...")
llm = llm_factory("gpt-4o", client=client)
# After: Gemini (similar code pattern!)
import google.generativeai as genai
genai.configure(api_key="...")
client = genai.GenerativeModel("gemini-2.0-flash")
llm = llm_factory("gemini-2.0-flash", provider="google", client=client)
# Adapter automatically switches to LiteLLM for google provider
另见
- Gemini Integration Guide - 详细的 Gemini 设置
- LLM Factory Reference - 完整 API 参考
- Metrics Documentation - 将指标与 LLM 一起使用