January 29, 2025
Building a Real Estate AI-Agent with Express.js and GPT-4
Jose SandoyaAI is transforming industries, including real estate. In this article, I'll show how I built a smart real estate assistant with Express.js and OpenAI's GPT-4. This AI-powered tool handles property inquiries, provides lending details, and offers location insights in real time, streamlining the home search process. Discover how AI enhances real estate experiences with intelligent automation.

Architecture Overview
The implementation consists of three main components:
- An Express server handling HTTP requests
- A router managing API endpoints
- An AI agent powered by GPT-4 using the ReACT framework
The Express Server Setup
First, we set up a basic Express server with the necessary middleware:
1import express from 'express';
2import bodyParser from 'body-parser';
3
4const app = express();
5const port = 5005;
6
7// Parse JSON requests
8app.use(bodyParser.json());
The Agent Router
The router handles incoming requests and manages the communication with our AI agent:
1agentRouter.post('/', async (req, res) => {
2 const { question, maxTurns } = req.body;
3
4 // Validate the input
5 if (!question || typeof question !== 'string') {
6 return res.status(400).send('Invalid or missing "question" parameter.');
7 }
8
9 // Stream the AI response from the AI-Agent
10 const resultStream = await queryAgent(question, turns);
11 res.setHeader('Content-Type', 'text/plain');
12 res.setHeader('Transfer-Encoding', 'chunked');
13 resultStream.pipe(res);
14 ...
The AI Agent Implementation
At the heart of our system is the RealEstateAgent class that manages conversations with GPT-4:
1class RealEstateAgent {
2 system: string = "";
3 messages: any[] = [];
4
5 constructor(system: string) {
6 this.system = system;
7 this.messages = [];
8 if (this.system) {
9 this.messages.push({
10 role: "system",
11 content: this.system,
12 });
13 }
14 }
15
16 private async execute() {
17 const completion = await openai.chat.completions.create({
18 model: "gpt-4",
19 messages: this.messages,
20 temperature: 0.3, // Lower temperature for more focused responses
21 });
22 return completion.choices[0].message.content;
23 }
24}
The ReACT Framework Implementation
What makes this agent special is its use of the ReACT (Reason + Act) framework. The agent follows a structured thought process:
1const prompt = `
2You are an AI Agent specialized in Real Estate, designed to assist with property-related inquiries using the ReACT framework.
3
4You operate in a loop of:
5 - Thought: Explain your reasoning
6 - Action: Use available functions
7 - PAUSE
8 - Observation: Get results
9
10Example Session:
11Question: What is the price of property with ID 5?
12Thought: I should fetch the details of property with ID 5.
13Action: getPropertyById: 5
14PAUSE
15
16Observation: The property with ID 5 is listed at $350,000.
17Answer: The property with ID 5 is priced at $350,000.
18`;
Real-Time Streaming Responses
One of the coolest features is the real-time streaming of responses. Here's how we implement it:
1export async function queryAgent(question: string, maxTurns: number = 5): Promise<Readable> {
2 const stream = new Readable({
3 read() { }
4 });
5
6 (async () => {
7 try {
8 while (i < maxTurns) {
9 const result = await bot.generateResponse(nextPrompt);
10 stream.push(result + '\n');
11
12 // Check for actions and execute them
13 const actions = result?.split('\n')
14 .map(line => actionRe.exec(line))
15 .filter(match => match !== null);
16
17 if (actions.length > 0) {
18 const [action, actionInput] = actions[0].slice(1);
19 const observation = await functions[action](actionInput);
20 stream.push("Observation: " + observation + '\n');
21 }
22 }
23 } finally {
24 stream.push(null); // End the stream
25 }
26 })();
27
28 return stream;
29}
Available Functions
The agent can interact with three main data models through these functions:
1const functions = {
2 "getLenders": lender.getLenders,
3 "getProperties": property.getProperties,
4 "getPropertyById": property.getPropertyById,
5 "getLocations": location.getLocations,
6 // ... more functions
7};
Example Interaction
Here's how a typical conversation flows:
1User: "What properties are available in downtown?"
2
3Agent's Thought: I need to check all properties and filter by location
4Action: getProperties
5[System fetches properties]
6Observation: Retrieved 10 properties
7
8Agent's Thought: Now I need location details
9Action: getLocationById
10[System fetches location information]
11Answer: There are 3 properties available in downtown...
Usage
To interact with the AI agent, send a POST request to the /agent endpoint:
1curl -X POST http://localhost:5005/agent \
2 -H "Content-Type: application/json" \
3 -d '{"question": "What are the available properties in downtown?", "maxTurns": 3}'
Future Enhancements
This system has immense potential for future growth. Enhancements could include advanced property-matching algorithms, real-time market data integration, and image processing for property photos. Additionally, multi-language support would expand its accessibility for international clients, making it a truly global AI-powered real estate assistant.
Conclusion
This implementation demonstrates how modern AI can be practically applied to the real estate industry. By combining Express.js's robust routing capabilities with GPT-4's intelligence and the ReACT framework, we've created a powerful tool that can handle complex property-related inquiries in real-time.
The streaming capability ensures responsive user experience, while the modular structure allows for easy maintenance and scaling. As AI technology continues to evolve, implementations like this will become increasingly valuable in providing efficient, automated assistance in the real estate sector.