以编程方式使用文档

>Parallel 是一个专为 LLM 和 AI 应用构建的实时网络搜索和内容提取平台。

ChatParallel 是 Parallel 模型的 OpenAI 兼容聊天接口。 speed 模型是一个低延迟的对话模型,无引用;研究模型(lite, base, core)浏览网络并通过 JSON schema 返回每个字段的引用和结构化输出。

概述

集成详情

ClassPackageSerializableJS/TS SupportDownloadsLatest Version
ChatParallellangchain-parallel<a href="https://pypi.org/project/langchain-parallel/" target="_blank"><img src="https://static.pepy.tech/badge/langchain-parallel/month" alt="Downloads per month" noZoom height="100" class="rounded" /></a><a href="https://pypi.org/project/langchain-parallel/" target="_blank"><img src="https://img.shields.io/pypi/v/langchain-parallel?style=flat-square&label=%20&color=orange" alt="PyPI - Latest version" noZoom height="100" class="rounded" /></a>

模型特性

工具调用结构化输出图片输入音频输入视频输入Token 级流式输出原生异步Token 使用量对数概率
✅(研究模型)

选择模型

模型延迟网页浏览引用结构化输出适用场景
speed基于模型参数化知识的对话回答。
lite中等带引用的信息查询。
base中高带引用的中等深度研究。
core更高带引用的多源研究。

speed 不遵守 response_format, so with_structured_output() 会引发明确的错误。当需要解析的 pydantic 输出或每个字段的引用时,请使用研究模型。

安装

要访问 Parallel 模型,请安装 langchain-parallel 集成包并获取 Parallel API 密钥。

安装

    pip install -U langchain-parallel
    
    uv add langchain-parallel
    

凭证

访问 Parallel 注册并生成 API 密钥。在环境中设置 PARALLEL_API_KEY

if not os.environ.get("PARALLEL_API_KEY"):
    os.environ["PARALLEL_API_KEY"] = getpass.getpass("Parallel API key:\n")

实例化

from langchain_parallel import ChatParallel

llm = ChatParallel(
    model="speed",
    # timeout=None,
    # max_retries=2,
    # api_key="...",  # optional if PARALLEL_API_KEY is set
    # base_url="https://api.parallel.ai",  # default
)

参见 ChatParallel API 参考以获取所有可用参数。

调用

messages = [
    ("system", "You are a helpful assistant with access to real-time web information."),
    ("human", "What are the latest developments in AI?"),
]
ai_msg = llm.invoke(messages)
print(ai_msg.content)

链接

将模型与提示模板链接:

from langchain_core.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate(
    [
        (
            "system",
            "You are a research assistant with access to real-time web information. "
            "Answer questions about {topic} using current sources.",
        ),
        ("human", "{question}"),
    ]
)

chain = prompt | llm
chain.invoke(
    {
        "topic": "artificial intelligence",
        "question": "What are the most significant AI breakthroughs in 2026?",
    }
)

结构化输出

在研究模型上(lite, base, core), ChatParallel.with_structured_output(...) 绑定了 JSON-schema response_format 并返回解析后的 pydantic 对象(或字典)。在 speed 上调用会引发 ValueError,因为 speed 静默忽略 response_format.

from pydantic import BaseModel, Field

class Founder(BaseModel):
    name: str = Field(description="Full name of the founder")
    company: str = Field(description="Company they founded")

structured = ChatParallel(model="lite").with_structured_output(Founder)
parsed = structured.invoke([("human", "Who founded SpaceX?")])
print(parsed)
name='Elon Musk' company='SpaceX'

method="json_schema" (默认设置), method="json_mode",和 method="function_calling" 均被接受。传入 include_raw=True 以接收完整的 {"raw", "parsed", "parsing_error"} 信封并捕获解析器错误:

structured = ChatParallel(model="lite").with_structured_output(Founder, include_raw=True)
res = structured.invoke([("human", "Who founded SpaceX?")])
res["parsed"]          # Founder(...) or None
res["parsing_error"]   # Exception or None
res["raw"]             # original AIMessage

引用

研究模型会填充 AIMessage.response_metadata["basis"] 每个字段的引用、模型的推理过程和置信度标签。 response_metadata["interaction_id"] 用于多轮上下文链接; system_fingerprint 存在时会被转发。

cited = ChatParallel(model="lite").invoke([
    ("human", "Who is the current CEO of OpenAI? One sentence."),
])
print(cited.content)
print("\nbasis:", cited.response_metadata.get("basis"))
print("interaction_id:", cited.response_metadata.get("interaction_id"))

流式传输

ChatParallel 支持逐 token 流式传输:

stream = llm.stream_events(messages, version="v3")
for token in stream.text:
    print(token, end="", flush=True)

异步

ai_msg = await llm.ainvoke(messages)

stream = await llm.astream_events(messages, version="v3")
async for token in stream.text:
    print(token, end="", flush=True)

Token 使用量

Parallel 目前不提供 token 使用量元数据。 usage_metadata is None.

ai_msg = llm.invoke(messages)
print(ai_msg.usage_metadata)
# None

响应元数据

ai_msg = llm.invoke(messages)
print(ai_msg.response_metadata)
# {'model_name': 'speed', 'finish_reason': 'stop', 'created': 1764043410}

对于研究模型, response_metadata 还包含 basis (每个字段的引用), interaction_id (用于多轮链接),以及 system_fingerprint (可用时)。

错误处理

该集成会抛出 ValueError 并附带常见失败模式的描述性消息:

from langchain_parallel import ChatParallel

try:
    llm = ChatParallel(api_key="invalid-key")
    response = llm.invoke([("human", "Hello")])
except ValueError as e:
    if "Authentication failed" in str(e):
        print("Invalid API key provided")
    elif "Rate limit exceeded" in str(e):
        print("API rate limit exceeded, please try again later")

OpenAI 兼容性

ChatParallel 接受许多 OpenAI 聊天补全 API 参数以实现 OpenAI 客户端的直接迁移。高级参数如 tools, tool_choice, top_p、和 frequency_penalty 会被接受但会被 Parallel API 忽略。

llm = ChatParallel(
    model="speed",
    # accepted but ignored by Parallel:
    tools=[{"type": "function", "function": {"name": "example"}}],
    tool_choice="auto",
    top_p=1.0,
    frequency_penalty=0.0,
    presence_penalty=0.0,
    logit_bias={},
    seed=42,
    user="user-123",
)

对于结构化输出,建议使用 ChatParallel.with_structured_output(...) (参见 结构化输出),而不是直接传递 response_format 。它适用于研究模型并返回解析后的对象。

消息处理

该集成会合并相同类型的连续消息以满足 API 要求:

from langchain.messages import HumanMessage, SystemMessage

# Consecutive system messages are automatically merged before the API call.
messages = [
    SystemMessage("You are a helpful assistant."),
    SystemMessage("Always be polite and concise."),
    HumanMessage("What is the weather like today?"),
]

response = llm.invoke(messages)

API 参考

如需详细文档,请访问 ChatParallel API 参考或 Parallel 聊天 API 快速入门.