🦈

DeepSeek APIをLangChainで使う

に公開

DeepSeek APIは、OpenAI APIと互換性のあるAPIフォーマットを使用しています。なので、OpenAIのSDKやOpenAI APIと互換性のあるソフトであれば、エンドポイントとAPIキーを変更するだけで使用することができます。

LangChainも同様に、OpenAI APIと互換性のあるlangchain-openaiライブラリのChatOpenAIを使用することで簡単に動かすことができます。

import os
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="deepseek-chat",
    openai_api_key=os.getenv("DEEPSEEK_API_KEY"),
    openai_api_base="https://api.deepseek.com",
)

response = llm.invoke("Hello!")
print(response.content)
Hello! How can I assist you today? 😊

APIキーとエンドポイントをdeepseek用のものにしてあげるだけで簡単に動きました。

Function CallingやStructured Outputといった機能も互換性があるので問題なく使用できます。

Function Calling

import os
from langchain_core.tools import tool
from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    model="deepseek-chat",
    openai_api_key=os.getenv("DEEPSEEK_API_KEY"),
    openai_api_base="https://api.deepseek.com",
    max_tokens=1024,
)

@tool
def get_weather(location: str) -> str:
    """Get the current weather in a given location"""
    return f"The current weather in {location} is sunny!"

llm_with_tools = llm.bind_tools([get_weather])
response = llm_with_tools.invoke("What is the weather in Tokyo?")
print(response.additional_kwargs["tool_calls"][0]["function"])
{'arguments': '{"location":"Tokyo"}', 'name': 'get_weather'}

Structured Output

import os
from pydantic import BaseModel, Field
from langchain_core.tools import tool

class ResponseFormat(BaseModel):
    thinking: str = Field(description="The thinking process of the LLM")
    answer: int = Field(description="The answer to the question")

llm = ChatOpenAI(
    model="deepseek-chat",
    openai_api_key=os.getenv("DEEPSEEK_API_KEY"),
    openai_api_base="https://api.deepseek.com",
    max_tokens=1024,
)

model_with_structure = llm.with_structured_output(ResponseFormat)
response = model_with_structure.invoke(
    "もし3人の生徒がそれぞれ7個のりんごを持っていて、それを4人の友達に均等に分けたとき、1人あたり何個のりんごをもらえるでしょうか?また余りは何個でしょうか?"
)
print(response)
thinking='まず、3人の生徒がそれぞれ7個のりんごを持っているので、りんごの総数は3 × 7 = 21個です。これを4人の友達に均等に分けます。21を4で割ると、1人あたり5個のりんごをもらえ、余りは1個です。' answer=5

OpenAIと同じように使えるので、既存のアプリケーションへの移行もやりやすくていいですね。
GPT-4o-miniと同じくらいの価格で、GPT-4o並の精度があるそうなので、一度試してみてはいかがでしょうか

Discussion