> ## Documentation Index
> Fetch the complete documentation index at: https://novita.ai/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# LangChain

> Novita AI を LangChain と統合して、インテリジェントな言語モデル駆動アプリケーションを構築します。セットアップ、API の使用方法、関数呼び出しワークフローについて学びます。

このガイドでは、Novita AI を LangChain と統合する手順を説明します。Novita AI の強力な言語モデルを、言語モデル駆動アプリケーションを構築するための LangChain の堅牢なツールと組み合わせて利用できるようになります。

## LangChain とは？

LangChain は、言語モデルを活用したアプリケーションを開発するためのフレームワークです。これにより、次のようなアプリケーションを実現できます。

* **コンテキストを認識できる**: LangChain は、言語モデルをコンテキストのソース（プロンプト指示、few-shot の例、応答の根拠となるコンテンツなど）に接続します。
* **推論できる**: LangChain により、言語モデルは推論できます。提供されたコンテキストに基づいてどのように回答するかを判断したり、どのアクションを実行するかを決定したりできます。

LangChain を使用すると、複雑なワークフローの構築、外部知識によるモデル動作の強化、ユーザーやデータソースと動的に対話できるインテリジェントなシステムの作成が可能になります。

## 前提条件

始める前に、次のものが揃っていることを確認してください。

* **Novita AI LLM API Key**:
  * [Novita AI のウェブサイト](https://novita.ai/)にアクセスして、アカウントを作成します。
  * ログイン後、[**Key Management**](https://novita.ai/settings/key-management) ページに移動して **API Key** を生成します。このキーは、Novita AI のモデルを LangChain に接続するために必要です。

    <Frame>
      ![Novita AI key management](https://mintlify.s3.us-west-1.amazonaws.com/novitaai/images/third-party/dify-1.png)
    </Frame>
* Node.js、JavaScript、および環境変数の使用方法に関する基本的な理解。

## 統合

### Step 1: API キーを設定する

ほとんどの環境では、環境変数 `NOVITA_API_KEY` を次のように設定します。

```bash theme={"system"}
export NOVITA_API_KEY="your-api-key"
```

`your-api-key` を、Novita AI から取得した実際のキーに置き換えてください。

### Step 2: 必要なパッケージをインストールする

Novita AI を LangChain と統合するには、Novita AI 統合を含む `@langchain-community` パッケージをインストールする必要があります。

必要なパッケージをインストールするには、次のいずれかのコマンドを選択してください。

**npm を使用する場合:**

```bash theme={"system"}
npm install @langchain/community @langchain/core
```

**yarn を使用する場合:**

```bash theme={"system"}
yarn add @langchain/community @langchain/core
```

**pnpm を使用する場合:**

```bash theme={"system"}
pnpm add @langchain/community @langchain/core
```

### Step 3: Novita AI モデルをインスタンス化する

必要なパッケージをインストールしたら、`ChatNovitaAI` クラスを使用して Novita AI モデルをインスタンス化できます。

以下は、その方法を示す例です。

```javascript theme={"system"}
import { ChatNovitaAI } from "@langchain/community/chat_models/novita";

const llm = new ChatNovitaAI({
  model: "deepseek/deepseek-r1", // You can choose the model you want to use
  temperature: 0, // Optional: Controls randomness. 0 is deterministic.
  // other parameters can be set here...
});
```

### Step 4: チャット補完のためにモデルを呼び出す

モデルをインスタンス化したら、メッセージを指定して呼び出すことで、チャット補完を生成できます。

メッセージを送信し、応答を取得する例を以下に示します。

```javascript theme={"system"}
const aiMsg = await llm.invoke([
  {
    role: "system",
    content: "You are a helpful assistant that translates English to French. Translate the user sentence.",
  },
  {
    role: "human",
    content: "I love programming.",
  },
]);

console.log(aiMsg.content); // The model’s response will be printed here
```

### Step 5: モデルをプロンプトテンプレートとチェーンする

LangChain では、モデルをプロンプトテンプレートとチェーンすることで、強力なワークフローを作成できます。これは、複数の入力に対して同じ形式を再利用したい場合に特に便利です。

以下は、言語間翻訳用のカスタムプロンプトテンプレートと Novita AI モデルをチェーンする例です。

```javascript theme={"system"}
import { ChatPromptTemplate } from "@langchain/core/prompts";

// Create a template for translating languages
const prompt = ChatPromptTemplate.fromMessages([
  [
    "system",
    "You are a helpful assistant that translates {input_language} to {output_language}.",
  ],
  ["human", "{input}"],
]);

// Chain the prompt with the model
const chain = prompt.pipe(llm);

// Invoke the chain with inputs for translation
const result = await chain.invoke({
  input_language: "English",
  output_language: "German",
  input: "I love programming.",
});

console.log(result.content); // The translated text will be printed here
```

### Step 6: ワークフローをカスタマイズする

ユースケースに応じて、temperature を変更したり、メッセージを追加したり、その他のパラメータを調整したりできます。LangChain は非常に柔軟で、複数のプロンプトをチェーンしたり、条件分岐ロジックを追加したり、異なるモデルを扱ったりすることで、複雑なインタラクションを設計できます。

## Novita AI と LangChain による関数呼び出し

Novita AI の LLM API で関数呼び出し（またはツール使用）を実装するには、LangChain を便利なフレームワークとして利用できます。この例では、モデルが関数呼び出しを通じて加算と乗算を実行できる、シンプルな数学アプリケーションを作成します。

💡 このガイドでは利便性のために LangChain を使用していますが、関数呼び出しの実装に特定のフレームワークは必要ありません。重要なのは、モデルが関数を理解し、正しく呼び出せるように適切なプロンプトを設計することです。ここでは実装を効率化するために LangChain を使用しています。

### 前提条件

まず、必要なパッケージをインストールします。

```bash theme={"system"}
pip install langchain-openai python-dotenv
```

### 環境のセットアップ

プロジェクトルートに `.env` ファイルを作成し、Novita AI API キーを追加します。

```
NOVITA_API_KEY=your_api_key_here
```

### 実装手順

1. **ツールを定義する**

まず、LangChain の `@tool` デコレーターを使用して、2 つのシンプルな数学ツールを作成しましょう。

```python theme={"system"}
from langchain_core.tools import tool

@tool
def multiply(x: float, y: float) -> float:
    """Multiply two numbers together."""
    return x * y

@tool
def add(x: int, y: int) -> int:
    """Add two numbers."""
    return x + y

tools = [multiply, add]
```

2. **ツール実行関数を作成する**

次に、ツールを実行する関数を実装します。

```python theme={"system"}
from typing import Any, Dict, Optional, TypedDict
from langchain_core.runnables import RunnableConfig

class ToolCallRequest(TypedDict):
    name: str
    arguments: Dict[str, Any]

def invoke_tool(
    tool_call_request: ToolCallRequest, 
    config: Optional[RunnableConfig] = None
):
    """Execute the specified tool with given arguments."""
    tool_name_to_tool = {tool.name: tool for tool in tools}
    name = tool_call_request["name"]
    requested_tool = tool_name_to_tool[name]
    return requested_tool.invoke(tool_call_request["arguments"], config=config)
```

3. **LangChain パイプラインをセットアップする**

Novita AI の LLM を使用してツール呼び出しを選択し、準備するチェーンを作成します。

```python theme={"system"}
from langchain_openai import ChatOpenAI
from langchain_core.output_parsers import JsonOutputParser
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.tools import render_text_description
import os

def create_chain():
    """Create a chain that uses the specified LLM model to select and prepare tool calls."""
    model = ChatOpenAI(
        model="meta-llama/llama-3.3-70b-instruct",
        api_key=os.getenv("NOVITA_API_KEY"),
        base_url="https://api.novita.ai/openai",
    )
    
    rendered_tools = render_text_description(tools)
    system_prompt = f"""\
    You are an assistant that has access to the following set of tools. 
    Here are the names and descriptions for each tool:

    {rendered_tools}

    Given the user input, return the name and input of the tool to use. 
    Return your response as a JSON blob with 'name' and 'arguments' keys.

    The `arguments` should be a dictionary, with keys corresponding 
    to the argument names and the values corresponding to the requested values.
    """

    prompt = ChatPromptTemplate.from_messages(
        [("system", system_prompt), ("user", "{input}")]
    )

    return prompt | model | JsonOutputParser()
```

4. **メイン処理関数を作成する**

数学的なクエリを処理するメイン関数を実装します。

```python theme={"system"}
def process_math_query(query: str):
    """Process a mathematical query by using an LLM to select the appropriate tool and execute it."""
    chain = create_chain()
    message = chain.invoke({"input": query})
    result = invoke_tool(message, config=None)
    return message, result
```

5. **使用例**

この実装の使い方は次のとおりです。

```python theme={"system"}
if __name__ == "__main__":
    message, result = process_math_query(
        "meta-llama/llama-3.3-70b-instruct", 
        "what's 3 plus 1132"
    )
    print(result)  # Output: 1135
```
