LangChain

LangChain gives you tools for every step of the agent development lifecycle. This guide demonstrates how to integrate Vercel AI Gateway with LangChain to access various AI models and providers.

  1. First, create a new directory for your project and initialize it:

    terminal
    mkdir langchain-ai-gateway
    cd langchain-ai-gateway
    pnpm dlx init -y
  2. Install the required LangChain packages along with the dotenv and @types/node packages:

    pnpm i langchain @langchain/core @langchain/openai dotenv @types/node
  3. Create a .env file with your Vercel AI Gateway API key:

    .env
    AI_GATEWAY_API_KEY=your-api-key-here

    If you're using the AI Gateway from within a Vercel deployment, you can also use the VERCEL_OIDC_TOKEN environment variable which will be automatically provided.

  4. Create a new file called index.ts with the following code:

    index.ts
    import 'dotenv/config';
    import { ChatOpenAI } from '@langchain/openai';
    import { HumanMessage } from '@langchain/core/messages';
     
    async function main() {
      console.log('=== LangChain Chat Completion with AI Gateway ===');
     
      const apiKey =
        process.env.AI_GATEWAY_API_KEY || process.env.VERCEL_OIDC_TOKEN;
     
      const chat = new ChatOpenAI({
        apiKey: apiKey,
        modelName: 'openai/gpt-4o-mini',
        temperature: 0.7,
        configuration: {
          baseURL: 'https://ai-gateway.vercel.sh/v1',
        },
      });
     
      try {
        const response = await chat.invoke([
          new HumanMessage('Write a one-sentence bedtime story about a unicorn.'),
        ]);
     
        console.log('Response:', response.content);
      } catch (error) {
        console.error('Error:', error);
      }
    }
     
    main().catch(console.error);

    The following code:

    • Initializes a ChatOpenAI instance configured to use the AI Gateway
    • Sets the model temperature to 0.7
    • Makes a chat completion request
    • Handles any potential errors
  5. Run your application using Node.js:

    pnpm dlx tsx index.ts 

    You should see a response from the AI model in your console.

Last updated on August 1, 2025

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy