Introduction
This blog post will guide you through the process of building an AI agent using Langchain and integrating it with a Next.js application. Langchain provides a powerful framework for building AI agents, while Next.js allows you to create a dynamic and interactive user interface for your agent.
Prerequisites
Before you begin, make sure you have the following installed:
- Node.js (version 18 or higher)
- npm or yarn
- An OpenAI API key
Setting up the Next.js Application
First, let's create a new Next.js application:
npx create-next-app@latest ai-agent-app
cd ai-agent-app
Installing Dependencies
Next, install the necessary dependencies:
npm install langchain openai @pinecone-database/pinecone
or
yarn add langchain openai @pinecone-database/pinecone
Creating the Langchain Agent
Now, let's create the Langchain agent. This will involve setting up the language model, defining the tools the agent can use, and creating the agent executor.
// filepath: /home/ranker/Desktop/portfolio/lib/langchain.js
import { OpenAI } from "langchain/llms/openai";
import { SerpAPI } from "langchain/tools";
import { initializeAgentExecutorWithOptions } from "langchain/agents";
export const createAgent = async () => {
const model = new OpenAI({ temperature: 0.7, openAIApiKey: process.env.OPENAI_API_KEY });
const tools = [
new SerpAPI(process.env.SERPAPI_API_KEY, {
hl: "en",
gl: "us",
}),
];
const executor = await initializeAgentExecutorWithOptions(tools, model, {
agentType: "zero-shot-react-description",
verbose: true,
});
return executor;
};
Integrating with Next.js API
Create an API endpoint in Next.js to interact with the Langchain agent.
// filepath: /home/ranker/Desktop/portfolio/pages/api/agent.js
import { createAgent } from "../../lib/langchain";
export default async function handler(req, res) {
if (req.method === "POST") {
const { input } = req.body;
const executor = await createAgent();
try {
const result = await executor.call({ input });
res.status(200).json({ output: result.output });
} catch (error) {
console.error(error);
res.status(500).json({ error: error.message });
}
} else {
res.status(405).json({ message: "Method Not Allowed" });
}
}
Creating the User Interface
Now, let's create a simple user interface in Next.js to interact with the agent.
// filepath: /home/ranker/Desktop/portfolio/pages/index.js
import { useState } from "react";
export default function Home() {
const [input, setInput] = useState("");
const [output, setOutput] = useState("");
const [loading, setLoading] = useState(false);
const handleSubmit = async (e) => {
e.preventDefault();
setLoading(true);
try {
const response = await fetch("/api/agent", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ input }),
});
const data = await response.json();
setOutput(data.output);
} catch (error) {
console.error(error);
setOutput("Error: " + error.message);
} finally {
setLoading(false);
}
};
return (
<div>
<h1>AI Agent with Langchain and Next.js</h1>
<form onSubmit={handleSubmit}>
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Enter your query"
/>
<button type="submit" disabled={loading}>
{loading ? "Loading..." : "Submit"}
</button>
</form>
<div>
<h2>Output:</h2>
<p>{output}</p>
</div>
</div>
);
}
Setting Environment Variables
You'll need to set your OpenAI API key and SerpAPI API key as environment variables. Create a .env.local
file in your Next.js project and add the following:
OPENAI_API_KEY=YOUR_OPENAI_API_KEY
SERPAPI_API_KEY=YOUR_SERPAPI_API_KEY
Replace YOUR_OPENAI_API_KEY
and YOUR_SERPAPI_API_KEY
with your actual API keys.
Running the Application
Now you can run the Next.js application:
npm run dev
or
yarn dev
Open your browser and go to http://localhost:3000
to see the application running.
Conclusion
In this blog post, you learned how to build an AI agent using Langchain and integrate it with a Next.js application. This setup allows you to create dynamic and interactive user interfaces for your AI agents, making them more accessible and user-friendly. You can further extend this application by adding more tools to the agent, improving the user interface, and integrating it with other services.