LangChain Integration

Use deepseek-kit alongside LangChain.js — DeepSeek handles text reasoning and tool calling while LangChain handles multimodal and complex workflows.

LangChain.js is a feature-rich AI application development framework providing a complete ecosystem of agents, tools, middleware, memory systems, and more. By integrating deepseek-kit with LangChain, you can leverage LangChain's multimodal support, pre-built tools, and state management capabilities while enjoying DeepSeek's cost-effective text reasoning.

Installation

pnpm add deepseek-kit langchain @langchain/openai zod

Pattern 1: deepseek-kit as a LangChain Subagent

Wrap deepseek-kit agents as LangChain tools, using them as subagents within LangChain's createAgent. The LangChain main agent handles multimodal understanding and task orchestration, while DeepSeek subagents handle deep text reasoning.

Scenario: Multimodal Input + Text Research

import { ChatOpenAI } from '@langchain/openai'
import { createAgent, createModel } from 'deepseek-kit'
import { createAgent as createLangChainAgent, tool } from 'langchain'
import { z } from 'zod'

const deepseekModel = createModel({ model: 'deepseek-v4-flash' })

const researchAgent = createAgent({
  model: deepseekModel,
  system: 'You are a research assistant. Conduct in-depth analysis based on provided information and clearly summarize your findings in your final response.',
})

const researchTool = tool(
  async ({ topic, context }) => {
    const result = await researchAgent.generate({
      prompt: `Based on the following context, research in depth: ${topic}\n\nContext: ${context}`,
    })
    return result.text
  },
  {
    name: 'deepseek_research',
    description: 'Use DeepSeek for in-depth research and analysis on a given topic, suitable for text tasks requiring deep reasoning',
    schema: z.object({
      topic: z.string().describe('The topic to research'),
      context: z.string().describe('Related context information'),
    }),
  },
)

const mainAgent = createLangChainAgent({
  model: new ChatOpenAI({ model: 'gpt-4o' }),
  tools: [researchTool],
})

Scenario: Code Review Pipeline

LangChain orchestrates a multi-step workflow, while DeepSeek handles the specific code analysis and review:

import { ChatOpenAI } from '@langchain/openai'
import { createAgent, createModel, tool as dsTool } from 'deepseek-kit'
import { createAgent as createLangChainAgent, tool } from 'langchain'
import { z } from 'zod'

const deepseekModel = createModel({ model: 'deepseek-v4-flash' })

const codeAnalysisAgent = createAgent({
  model: deepseekModel,
  system: 'You are a code analysis expert. Analyze code structure, logic, and potential issues, providing detailed analysis reports.',
})

const codeReviewAgent = createAgent({
  model: deepseekModel,
  system: 'You are a code review expert. Based on analysis reports, provide specific improvement suggestions and fix proposals.',
  output: {
    schema: z.object({
      issues: z.array(z.object({
        severity: z.enum(['critical', 'warning', 'info']),
        description: z.string(),
        suggestion: z.string(),
      })),
      overallScore: z.number().min(0).max(100),
      summary: z.string(),
    }),
  },
})

const analyzeTool = tool(
  async ({ code }) => {
    const result = await codeAnalysisAgent.generate({
      prompt: `Analyze the following code:\n\`\`\`\n${code}\n\`\`\``,
    })
    return result.text
  },
  {
    name: 'analyze_code',
    description: 'Use DeepSeek to analyze code structure and logic',
    schema: z.object({ code: z.string().describe('Code to analyze') }),
  },
)

const reviewTool = tool(
  async ({ analysisReport }) => {
    const result = await codeReviewAgent.generate({
      prompt: `Conduct a code review based on the following analysis report:\n${analysisReport}`,
    })
    return JSON.stringify(result.output)
  },
  {
    name: 'review_code',
    description: 'Conduct a code review based on an analysis report, returning structured review results',
    schema: z.object({ analysisReport: z.string().describe('Code analysis report') }),
  },
)

const mainAgent = createLangChainAgent({
  model: new ChatOpenAI({ model: 'gpt-4o' }),
  tools: [analyzeTool, reviewTool],
})

Pattern 2: LangChain as a deepseek-kit Subagent

Wrap LangChain's capabilities as deepseek-kit tools, calling them on demand within a deepseek-kit agent.

Scenario: Image Understanding + Text Reasoning

The DeepSeek agent serves as the primary controller, calling LangChain's multimodal model when image understanding is needed:

import { HumanMessage } from '@langchain/core/messages'
import { ChatOpenAI } from '@langchain/openai'
import { createAgent, createModel, tool } from 'deepseek-kit'
import { z } from 'zod'

const deepseekModel = createModel({ model: 'deepseek-v4-flash' })

const visionModel = new ChatOpenAI({ model: 'gpt-4o' })

const analyzeImageTool = tool({
  name: 'analyzeImage',
  description: 'Analyze image content and return a detailed text description. Use this tool when users mention images, screenshots, or photos.',
  schema: z.object({
    imageUrl: z.string().describe('URL of the image'),
    question: z.string().describe('Specific question about the image'),
  }),
  execute: async (input) => {
    const response = await visionModel.invoke([
      new HumanMessage({
        content: [
          { type: 'text', text: input.question },
          { type: 'image_url', image_url: { url: input.imageUrl } },
        ],
      }),
    ])
    return response.content as string
  },
})

const agent = createAgent({
  model: deepseekModel,
  tools: [analyzeImageTool, searchTool],
  system: 'You are an assistant. When users send images, first use analyzeImage to understand the image, then answer based on the results.',
})

const result = await agent.generate({
  prompt: 'What does the error message in this screenshot say? Help me analyze possible causes.',
})

Scenario: Using LangChain Pre-built Tools

LangChain provides a rich set of pre-built tools (web search, database queries, etc.) that can be directly wrapped as deepseek-kit tools:

import { createAgent, createModel, tool } from 'deepseek-kit'
import { z } from 'zod'

const deepseekModel = createModel({ model: 'deepseek-v4-flash' })

const webSearchTool = tool({
  name: 'webSearch',
  description: 'Search the internet for real-time information',
  schema: z.object({
    query: z.string().describe('Search keywords'),
  }),
  execute: async (input) => {
    // Use LangChain's pre-built search tool or a custom search implementation
    const results = await performWebSearch(input.query)
    return results
  },
})

const agent = createAgent({
  model: deepseekModel,
  tools: [webSearchTool],
  system: 'You are a research assistant. Use the webSearch tool to get the latest information, then provide a comprehensive analysis.',
})

Hybrid Architecture Example

Here's a complete hybrid architecture example — LangChain handles user interaction and multimodal input, while DeepSeek handles text-intensive tasks:

import { ChatOpenAI } from '@langchain/openai'
import { createAgent, createModel, tool as dsTool } from 'deepseek-kit'
import { createAgent as createLangChainAgent, tool } from 'langchain'
import { z } from 'zod'

const deepseekModel = createModel({ model: 'deepseek-v4-flash' })

const writingAgent = createAgent({
  model: deepseekModel,
  system: 'You are a professional technical writing assistant. Write high-quality technical documentation based on provided information.',
})

const analysisAgent = createAgent({
  model: deepseekModel,
  system: 'You are a data analysis assistant. Analyze data and extract key insights.',
  output: {
    schema: z.object({
      summary: z.string(),
      keyFindings: z.array(z.string()),
      recommendation: z.string(),
    }),
  },
})

const writeDocTool = tool(
  async ({ topic, context }) => {
    const result = await writingAgent.generate({
      prompt: `Write technical documentation about ${topic}.\n\nReference material: ${context}`,
    })
    return result.text
  },
  {
    name: 'write_document',
    description: 'Use DeepSeek to write technical documentation',
    schema: z.object({
      topic: z.string().describe('Document topic'),
      context: z.string().describe('Reference material'),
    }),
  },
)

const analyzeDataTool = tool(
  async ({ data, question }) => {
    const result = await analysisAgent.generate({
      prompt: `Analyze the following data: ${data}\n\nQuestion: ${question}`,
    })
    return JSON.stringify(result.output)
  },
  {
    name: 'analyze_data',
    description: 'Use DeepSeek to analyze data and extract insights',
    schema: z.object({
      data: z.string().describe('Data to analyze'),
      question: z.string().describe('Analysis question'),
    }),
  },
)

const mainAgent = createLangChainAgent({
  model: new ChatOpenAI({ model: 'gpt-4o' }),
  tools: [writeDocTool, analyzeDataTool],
})

Considerations

  • Context Isolation — deepseek-kit subagents have their own isolated context window. If you need to pass the LangChain main agent's conversation history, manually construct the messages in the tool's execute function
  • Tool Format Differences — deepseek-kit's tool() and LangChain's tool() use different parameter formats and are not directly interchangeable. Adaptation is needed at the integration layer
  • Error Handling — Errors from deepseek-kit subagents are returned to the LangChain main agent as tool execution failures. You can handle these errors uniformly in LangChain's middleware
  • API Keys — Make sure both DEEPSEEK_API_KEY and the corresponding LangChain model's API key (e.g., OPENAI_API_KEY) are configured
  • Streaming — deepseek-kit subagent internal stream events don't propagate to LangChain's stream. If you need to display progress, handle it within the tool itself