Getting Started with LangChain.js: Calling OpenAI to Tell a Joke
Rany ElHousieny, PhD???
Generative AI ENGINEERING MANAGER | ex-Microsoft | AI Solutions Architect | Generative AI & NLP Expert | Proven Leader in AI-Driven Innovation | Former Microsoft Research & Azure AI | Software Engineering Manager
Artificial Intelligence is becoming more accessible for frontend developers, thanks to LangChain.js. If you've ever wanted to integrate OpenAI’s GPT models directly into a React app—without needing a backend—this guide is for you!
In this tutorial, we’ll walk through a super simple example: asking OpenAI to tell a joke using LangChain.js.
What is LangChain.js?
LangChain.js is a JavaScript library that makes it easy to interact with Large Language Models (LLMs) like OpenAI’s GPT-4.
Instead of manually crafting API calls to OpenAI, LangChain handles it for us, allowing a more structured way to build AI-powered applications.
?? Why use LangChain?
Today, we'll use LangChain in a React app to call OpenAI and generate a joke.
Step 1: Set Up a React Project
If you don’t have a React project, create one by running:
npx create-react-app langchain-openai
cd langchain-openai
npm install @langchain/openai langchain
This installs LangChain.js, which we’ll use to talk to OpenAI.
Install MUI
npm install @mui/material @emotion/react @emotion/styled
Step 2: Modify App.js to Use LangChain.js
Replace everything in src/App.js with the following code:
import React, { useState } from "react";
import { Button, TextField, Typography, Container, Box } from "@mui/material";
import { ChatOpenAI } from "@langchain/openai";
function App() {
const [apiKey, setApiKey] = useState(""); // Stores OpenAI API key
const [joke, setJoke] = useState(""); // Stores AI-generated joke
// Handle API key input
const handleApiKeyChange = (event) => {
setApiKey(event.target.value);
};
// Call OpenAI using LangChain
const handleTellJoke = async () => {
if (!apiKey) {
alert("Please enter your OpenAI API key.");
return;
}
const model = new ChatOpenAI({
openAIApiKey: apiKey, // Provide the API key
modelName: "gpt-4", // Choose model
});
try {
const response = await model.invoke([
{ role: "system", content: "You are a funny comedian. Keep jokes clean and family-friendly." },
{ role: "user", content: "Tell me a funny joke." }
]);
setJoke(response.content); // Display the AI-generated joke
} catch (error) {
console.error("Error calling OpenAI:", error);
setJoke("Failed to get a joke. Check API key.");
}
};
return (
<Container maxWidth="sm" style={{ marginTop: "20px" }}>
<Typography variant="h4" align="center" gutterBottom>
LangChain Joke Generator ??
</Typography>
{/* API Key Input */}
<Box marginBottom="20px">
<Typography variant="h6">OpenAI API Key:</Typography>
<TextField
fullWidth
type="password"
placeholder="Enter your API key"
value={apiKey}
onChange={handleApiKeyChange}
/>
</Box>
{/* Joke Button */}
<Button variant="contained" color="primary" onClick={handleTellJoke} fullWidth>
Tell Me a Joke
</Button>
{/* Display Joke */}
{joke && (
<Box marginTop="20px">
<Typography variant="h6">Generated Joke:</Typography>
<Typography variant="body1">{joke}</Typography>
</Box>
)}
</Container>
);
}
export default App;
Explaining the Code: LangChain Joke Generator in React
This React application is a simple AI-powered joke generator that interacts with OpenAI’s GPT-4 using LangChain.js. It runs entirely in the browser with no backend required.
1. Imports & Dependencies
import React, { useState } from "react";
import { Button, TextField, Typography, Container, Box } from "@mui/material";
import { ChatOpenAI } from "@langchain/openai";
What’s Happening Here?
2. State Management
const [apiKey, setApiKey] = useState(""); // Stores OpenAI API key
const [joke, setJoke] = useState(""); // Stores AI-generated joke
3. Handling User Input
const handleApiKeyChange = (event) => {
setApiKey(event.target.value);
};
4. Calling OpenAI Using LangChain
const handleTellJoke = async () => {
if (!apiKey) {
alert("Please enter your OpenAI API key.");
return;
}
const model = new ChatOpenAI({
openAIApiKey: apiKey, // Provide the API key
modelName: "gpt-4", // Choose model
});
What’s Happening Here?
1?? Checks if an API key is provided.
2?? Creates a ChatOpenAI instance using LangChain.js.
5. Sending a Structured Conversation to OpenAI
try {
const response = await model.invoke([
{ role: "system", content: "You are a funny comedian. Keep jokes clean and family-friendly." },
{ role: "user", content: "Tell me a funny joke." }
]);
setJoke(response.content); // Display the AI-generated joke
} catch (error) {
console.error("Error calling OpenAI:", error);
setJoke("Failed to get a joke. Check API key.");
}
This code:
Here is step by step:
Executing the AI Call
const response = await model.invoke([
{ role: "system", content: "You are a funny comedian. Keep jokes clean and family-friendly." },
{ role: "user", content: "Tell me a funny joke." }
]);
Handling the AI’s Response
setJoke(response.content); // Display the AI-generated joke
Error Handling
} catch (error) {
console.error("Error calling OpenAI:", error);
setJoke("Failed to get a joke. Check API key.");
}
6. The User Interface (React JSX)
return (
<Container maxWidth="sm" style={{ marginTop: "20px" }}>
<Typography variant="h4" align="center" gutterBottom>
LangChain Joke Generator ??
</Typography>
API Key Input Field
<Box marginBottom="20px">
<Typography variant="h6">OpenAI API Key:</Typography>
<TextField
fullWidth
type="password"
placeholder="Enter your API key"
value={apiKey}
onChange={handleApiKeyChange}
/>
</Box>
Joke Button
<Button variant="contained" color="primary" onClick={handleTellJoke} fullWidth>
Tell Me a Joke
</Button>
Displaying the AI-Generated Joke
{joke && (
<Box marginTop="20px">
<Typography variant="h6">Generated Joke:</Typography>
<Typography variant="body1">{joke}</Typography>
</Box>
)}
7. Exporting the Component
export default App;
How It Works
1?? User enters their OpenAI API key.
2?? Clicks “Tell Me a Joke”.
3?? LangChain sends a structured conversation (system + user prompt).
4?? OpenAI returns a joke.
5?? The joke is displayed on the screen.
? No backend required—everything runs in the browser!
What’s Next?
Now that we’ve called OpenAI from LangChain.js, we can move to Step 2: Prompt Templates