cheapaimodel

LangChain

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

複製

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

LangChain 設定值
Base URLbase_urlhttps://api.cheapaimodel.ai/v1
API Keyapi_key你在控制台 API Key 頁面建立的 Key
模型 IDmodeldeepseek-v4-1-flash,或目錄中的任一模型 ID

設定

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

目前版本的 langchain-openai 需要 Python 3.10 以上。

終端機
pip install -U langchain-openai
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)

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

使用 init_chat_model

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

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

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 設為目錄中的模型 ID。

Base URL 漏了 /v1 這類錯誤,請參閱 Base URL。

複製
開啟方式

本頁內容