# LangChain (/zh-Hant/docs/guides/langchain)

透過 OpenAI 相容 API 在 LangChain 中使用 cheapaimodel 的模型。



LangChain 透過它的 OpenAI 整合連接 OpenAI 相容服務：Python 用 `langchain-openai` 的 `ChatOpenAI`，TypeScript 用 `@langchain/openai` 的 `ChatOpenAI`。把它指向我們的 Base URL，並傳入你的 cheapaimodel Key。

|          | LangChain 設定 | 值                                                               |
| -------- | ------------ | --------------------------------------------------------------- |
| Base URL | `base_url`   | `https://api.cheapaimodel.ai/v1`                                |
| API Key  | `api_key`    | 你在控制台 [API Key](https://console.cheapaimodel.ai/keys) 頁面建立的 Key |
| 模型 ID    | `model`      | `deepseek-v4-1-flash`，或[目錄](/zh-Hant/models)中的任一模型 ID           |

## 設定 [#設定]

表格列的是 Python 的參數名。TypeScript 中對應的是 `configuration.baseURL`、`apiKey` 與 `model`：Base URL 要放在 `configuration` 裡。

<Tabs items="[&#x22;Python&#x22;, &#x22;TypeScript&#x22;]">
  <Tab value="Python">
    目前版本的 `langchain-openai` 需要 Python 3.10 以上。

    ```bash title="終端機"
    pip install -U langchain-openai
    ```

    ```python title="main.py"
    import os
    from langchain_openai import ChatOpenAI

    llm = ChatOpenAI(
        model="deepseek-v4-1-flash",
        base_url="https://api.cheapaimodel.ai/v1",
        api_key=os.environ["CHEAPAIMODEL_API_KEY"],
    )

    response = llm.invoke("Explain recursion in one sentence.")
    print(response.text)

    # Streaming
    for chunk in llm.stream("Write a haiku about the sea."):
        print(chunk.text, end="", flush=True)
    ```
  </Tab>

  <Tab value="TypeScript">
    ```bash title="終端機"
    npm install @langchain/openai @langchain/core
    ```

    ```ts title="main.ts"
    import { ChatOpenAI } from "@langchain/openai";

    const llm = new ChatOpenAI({
      model: "deepseek-v4-1-flash",
      apiKey: process.env.CHEAPAIMODEL_API_KEY,
      configuration: {
        baseURL: "https://api.cheapaimodel.ai/v1",
      },
    });

    const response = await llm.invoke("Explain recursion in one sentence.");
    console.log(response.text);

    // Streaming
    const stream = await llm.stream("Write a haiku about the sea.");
    for await (const chunk of stream) {
      process.stdout.write(chunk.text);
    }
    ```
  </Tab>
</Tabs>

`ChatOpenAI` 會把請求送往 `/v1/chat/completions`。[目錄](/zh-Hant/models)中列有這個端點的模型都能取代 `deepseek-v4-1-flash`。

## 使用 init\_chat\_model [#使用-init_chat_model]

在 Python 中，`langchain` 套件的 `init_chat_model` 接受同樣的設定。請傳入 `model_provider="openai"`：少了它，LangChain 會依模型 ID 猜測供應商，結果選錯整合，或者找不到整合。

```python title="main.py"
import os
from langchain.chat_models import init_chat_model

llm = init_chat_model(
    "deepseek-v4-1-flash",
    model_provider="openai",
    base_url="https://api.cheapaimodel.ai/v1",
    api_key=os.environ["CHEAPAIMODEL_API_KEY"],
)
```

## Embeddings [#embeddings]

cheapaimodel 目前沒有 embeddings 模型。`OpenAIEmbeddings`，或你的檢索器使用的任何 embeddings 類別，請繼續使用它原本的供應商，不要指向我們的 Base URL。

## 常見錯誤 [#常見錯誤]

* **`'baseURL' does not exist in type 'ChatOpenAIFields'`**（TypeScript）。`baseURL` 應放在 `configuration` 裡。純 JavaScript 會直接忽略最外層的這個欄位，不會顯示任何錯誤，請求於是帶著你的 cheapaimodel Key 送往 OpenAI。
* **`init_chat_model` 回報 `requires the langchain-deepseek package` 或 `Unable to infer model provider`。** 請加上 `model_provider="openai"`。
* **`/v1/embeddings` 回傳 `503` 與 `model_not_found`。** 環境變數 `OPENAI_BASE_URL` 或 `OPENAI_API_BASE` 匯出了我們的 Base URL。`ChatOpenAI` 會讀取它，`OpenAIEmbeddings` 也會，於是向我們要求 embeddings 模型。請在程式碼中傳入 `base_url`，不要匯出環境變數。
* **印出 `<bound method BaseMessage.text ...>`。** Python 版本低於 3.10，pip 於是裝了 0.3 版，那一版的 `text` 是方法。請升級 Python 後重新安裝。
* **`/v1/chat/completions` 回傳 `503` 與 `model_not_found`。** 漏了 `model`，LangChain 於是送出它的 OpenAI 預設值 `gpt-3.5-turbo`；或者這個 ID 不在目錄中。請把 `model` 設為[目錄](/zh-Hant/models)中的模型 ID。

Base URL 漏了 `/v1` 這類錯誤，請參閱 [Base URL](/zh-Hant/docs/api/base-url#common-mistakes)。
