# 使用开放权重模型的 LangChain 和 LlamaIndex

> 在 LangChain 和 LlamaIndex 中使用开放权重 LLM：通过 base_url 使用 ChatOpenAI、工具绑定、LangChain.js 和 OpenAILike。按 token 用加密货币支付。

- URL: https://llmwithcrypto.com/zh/docs/langchain/
- 最后更新: 2026-10-23
- 发布者: LLMwithCrypto (https://llmwithcrypto.com)

LangChain 和 LlamaIndex 都提供了支持自定义 base URL 的 OpenAI 对话模型。将其指向我们的 API，你构建的每条链、每个 agent 和每个检索器都能继续工作，现在运行在 DeepSeek、Qwen、gpt-oss 和其他开放权重模型上。

**快速回答 — 如何在 LangChain 中使用 LLMwithCrypto？**

安装 `langchain-openai` 并创建 `ChatOpenAI(model="deepseek-v4-pro", base_url="https://llmwithcrypto.com/api/v1", api_key=…)`。**LLMwithCrypto** 使用 OpenAI 对话格式，因此 `invoke`、流式传输和 `bind_tools` 与使用 OpenAI 时一样，适用于支持工具的模型。LlamaIndex 使用 `OpenAILike`，base URL 相同。记录于 2026 年 10 月 23 日。

## 使用哪个类

| 属性 | 值 |
| --- | --- |
| LangChain（Python） | `ChatOpenAI` 起价 `langchain-openai`，包含 `base_url` |
| LangChain.js | `ChatOpenAI` 起价 `@langchain/openai`，包含 `configuration.baseURL` |
| LlamaIndex | `OpenAILike` 起价 `llama-index-llms-openai-like`，包含 `api_base` 和 `is_chat_model=True` |
| Model id | 在 [models 页面](https://llmwithcrypto.com/zh/models/) |

## 如何设置 ChatOpenAI？

创建模型时传入 base URL 和密钥。设置 `max_tokens` 可让链或 agent 的每一步都不会超出你愿意支付的额度；回复中的 `usage_metadata` 显示每次调用的 token 数。

*LangChain：在 DeepSeek V4 Pro 上使用 ChatOpenAI*

```python
import os

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="deepseek-v4-pro",
    base_url="https://llmwithcrypto.com/api/v1",
    api_key=os.environ["LLMWITHCRYPTO_API_KEY"],
    max_tokens=300,
    temperature=0.3,
)
reply = llm.invoke("Explain what a vector database is in two sentences.")
print(reply.content)
print(reply.usage_metadata)

```

## 工具和 agent 能用吗？

可以，在支持 tool calling 的模型上。所有模型都支持流式输出；工具调用和 JSON 输出取决于各模型本身的支持情况。`bind_tools` 以 OpenAI 格式发送你的工具；在依赖它之前，先在你选定的模型上测试你的 schema。基于 `ChatOpenAI` 构建的 LangGraph agent 工作方式相同。

*LangChain：绑定到 gpt-oss-120b 的工具*

```python
import os

from langchain_core.tools import tool
from langchain_openai import ChatOpenAI


@tool
def convert_currency(amount: float, rate: float) -> float:
    """Convert an amount with an exchange rate."""
    return round(amount * rate, 2)


llm = ChatOpenAI(
    model="gpt-oss-120b",
    base_url="https://llmwithcrypto.com/api/v1",
    api_key=os.environ["LLMWITHCRYPTO_API_KEY"],
)
llm_with_tools = llm.bind_tools([convert_currency])
msg = llm_with_tools.invoke("How much is 250 at a rate of 0.92?")
for call in msg.tool_calls:
    print(call["name"], call["args"], "->", convert_currency.invoke(call["args"]))

```

## 那 JavaScript 呢？

LangChain.js 在 `configuration` 中接收 base URL，并把它传给底层的 OpenAI 客户端。

*LangChain.js：带 baseURL 的 ChatOpenAI*

```javascript
import { ChatOpenAI } from '@langchain/openai';

const llm = new ChatOpenAI({
  model: 'qwen3-235b-a22b-instruct-2507',
  apiKey: process.env.LLMWITHCRYPTO_API_KEY,
  configuration: { baseURL: 'https://llmwithcrypto.com/api/v1' },
  maxTokens: 300,
});
const reply = await llm.invoke('Give me a three-step plan to learn SQL.');
console.log(reply.content);

```

## 如何在 LlamaIndex 中使用？

使用 `OpenAILike`，它不会拿模型名去对照 OpenAI 的列表。设置 `is_chat_model=True` 让它发送聊天消息，并提供模型的上下文窗口，以便 LlamaIndex 调整 prompt 大小：截至 2026 年 10 月 23 日，DeepSeek V4.1 Flash 最多可读取 1M 个 token，示例故意设置了更小的窗口以保持 prompt 简短。

*LlamaIndex：在 DeepSeek V4.1 Flash 上使用 OpenAILike*

```python
import os

from llama_index.llms.openai_like import OpenAILike

llm = OpenAILike(
    model="deepseek-v4.1-flash",
    api_base="https://llmwithcrypto.com/api/v1",
    api_key=os.environ["LLMWITHCRYPTO_API_KEY"],
    is_chat_model=True,
    context_window=131072,
    max_tokens=300,
)
print(llm.complete("Name three uses of a knowledge graph."))

```

## 如何控制 agent 成本？

agent 每个任务会多次调用模型：一次用于规划，每个工具结果一次，一次用于回答。每次调用都会重发整个对话，因此输入在每一步都会增长。

- **限制每次调用**，用 `max_tokens`，并用最大步数限制整个运行。
- **够用时就用小模型。** 截至 2026 年 10 月 23 日，gpt-oss-20b 每百万输入 token 收费 $0.033，而 DeepSeek V4 Pro 为 $1.254：把简单步骤路由到小模型，把大模型留给最终回答。
- **精简历史记录**，在长对话中或对旧轮次做摘要。
- **留意积分**，在大规模运行前用 `GET https://llmwithcrypto.com/api/v1/credits` 查看。

dashboard 会列出每次调用及其 token 和费用，能很快看出链中哪一步最贵。

## 框架：常见问题

### 一条链里可以混用模型吗？

可以：为每个模型各创建一个 `ChatOpenAI`，例如用便宜的做路由，用大的做最终回答。它们都消耗同一份积分。

### embeddings 能用吗？

不能。该 API 只提供 chat completions；请在你现有的 embedding 模型旁并用它。

### 一次 agent 运行要付多少？

按 token 计，运行中的每次模型调用都收费。按 token 从余额扣费：输入和输出 token 由模型自己的 tokenizer 计数，按该模型每 1M token 的价格计费。以错误结束的调用不收费。各模型价格见 [pricing 页面](https://llmwithcrypto.com/zh/pricing/)。

---

LLMwithCrypto: LLMwithCrypto 是一个兼容 OpenAI 的开放权重模型 LLM API，涵盖 DeepSeek V4 Pro、DeepSeek V4.1 Flash、DeepSeek R1、Qwen3.5 397B A17B、Qwen3 235B A22B Instruct、gpt-oss-120b、gpt-oss-20b、GLM-4.7、Llama 3.3 70B Instruct、Gemma 4 31B、Mistral Large 3、Mistral Small 4，按 token 从预付加密货币余额中扣费，价格比公共托管商的中位价低 5%。无需 KYC：无需身份证件、无需自拍、无需文件。不存储提示词和输出。
