

At the end of 2024, we released the first iteration of the zeroheight API for enterprise customers. The API gives you read access for pulling the written content of pages down, as well as information about the styleguides and pages like categories, releases, and statuses.
It’s a cool first pass, and if you want an in-depth look at how the endpoints work and how to transform the data, I’d check out both the API docs and Dave’s tutorial on playing with the releases endpoint.
One of the cool use cases we’ve been asked about is being able to query the data in your zeroheight site in other ways, like using a chatbot. Especially for sites like Uber’s Base Design System, that have hundreds of pages, finding the information can be a bit of a pain. You can use search, but in the end, you will still have to read through loads of different pages. This is where LLMs and RAG apps become pretty powerful.
We’re all familiar with tools like ChatGPT and Claude. One of the problems with these is that they’re too generalized, because the information they query against is so broad that it can be hard to narrow it down without the AI starting to hallucinate. This is where Retrieval-Augmented Generation (RAG) comes in. RAG combines the power of large-language models (LLMs), the technology that powers these chat interfaces, with a specialized retrieval system (like Pinecone or Elasticsearch) to provide precise and context-aware answers.
The retrieval system stores and organizes a knowledge base (eg. documents, FAQs, transcripts, articles, your zeroheight documentation), allowing the app to fetch relevant information based on queries. This retrieved data is then used to inform the LLM’s response, making sure that it is basing the answers on reliable, up-to-date and contextual information.
In this case, we’re going to pull the information from zeroheight, transform the data into a usable format, and push it to the retrieval system (in this case, Pinecone), then build an interface that queries the data using an LLM model (in this case, OpenAI’s GPT 4o).
And if you want to have a play with a live version of the finished app, you can do so here on our demo styleguide: https://zhapi-chatbot.netlify.app/
Before you start anything, you’ll need to create an authentication token for your styleguide. The important thing here is to make sure that you define the scopes you need. For this particular example, I only need the page:read scope, as I’m only getting lists of the pages and the content itself. However, pulling in the statuses, categories, and versions could also provide more context via the metadata, so might be worth setting up. Just remember: you can only set your scoping once. If you want to update it in the future, you’ll have to revoke the token and create a new one.
You’ll also need to get your styleguide ID, which you can find in the URL in editor mode in zeroheight between the /s/ and /p/ :
https://styleguide.zeroheight.com/styleguide/s/{stylguideId}/p/{pageUid}-page_name
const fs = require('fs');
// Replace API_KEY and API_CLIENT with your zeroheight API credentials
const headers = {
'Accept': 'application/json',
'X-API-KEY': '{API_KEY}',
'X-API-CLIENT': '{API_CLIENT}'
};
// Replace STYLEGUIDE_ID with the ID of the styleguide you want to retrieve pages from
const styleguideId = '{STYLEGUIDE_ID}';
To begin with, you’ll need to grab all the page ids from your styleguide and store them as a json object.
const getPages = async () => {
try {
const response = await fetch(
`https://zeroheight.com/open_api/v2/styleguides/${styleguideId}/pages`,
{
method: "GET",
headers: headers
}
);
if (!response.ok) {
console.error('Error response:', response);
return null;
}
const json = await response.json();
if (!json || !json.data || !json.data.pages) {
console.error('Error: Invalid response format');
return null;
}
const pageIds = json.data.pages.map(page => page.id);
console.log('Page IDs:', pageIds);
return { pageIds };
} catch (error) {
console.error('Error fetching pages:', error);
return null;
}
};
What this function does is pull in the pageIds via the List endpoint, and if successful, will return an object with all of the page IDs in your styleguide, as well as printing them all in the console (so you can make sure they’re all there!). The error handling makes sure that the response is ok and it’s coming back in the right format!
Once we have the page ids, we can then pull the content itself down as a JSON file using the Get endpoint.
const getPageContent = (pageId) => {
const url = `https://zeroheight.com/open_api/v2/pages/${pageId}?format=markdown`;
console.log(`Fetching URL: ${url}`);
return fetch(url, {
method: "GET",
headers: headers
})
.then((response) => {
console.log(`Response status for ${pageId}: ${response.status}`);
if (response.ok) {
return response.json();
} else {
console.error(`${pageId} skipped because of error ${response.status}`);
return null;
}
})
.then((json) => {
if (!json || !json.data.page) {
console.error(`${pageId} skipped because of error ${json ? json.status : 'unknown'}`);
return null;
}
const page = json.data.page;
if (page.tabs) {
return {
name: page.name,
url: page.url,
tabs: page.tabs.map(tab => ({
name: tab.name,
content: tab.content
}))
};
} else {
return {
name: page.name,
url: page.url,
content: page.content
};
}
});
};
This function will use the page ID to pull the content for that page. It’s important to note that at the moment, this will only pull the text content from headings and paragraphs, so won’t pull anything from callouts, tables, design uploads or code blocks.
We’ve specified markdown as a URL parameter to be explicit in the format we want it to pull down, and then we’ve provided some logging to make sure you can see what’s happening. One important point here is if the page contains tabbed content, the data.page.content will be empty, so we have to make sure we account for that, by checking if page.tabs exists, and pulling the content from the tabs down, and otherwise pulling the content itself.
Finally, the error handling in this bit is important. At the moment, the API doesn’t play nicely with synced pages, and can sometimes try and fetch deleted pages. Putting in some error handling to skip these is important, otherwise it’ll hang your whole application.
Finally, we run all of those, format the JSON, then write it to a file.
async function writePageContentsToFile() {
const pages = await getPages();
if (!pages || !pages.pageIds) {
console.error('Error: getPages did not return a valid object with pageIds');
return;
}
const { pageIds } = pages;
const formattedContents = [];
for (const pageId of pageIds) {
const content = await getPageContent(pageId);
//flatten the tabbed content to make it easier to process by Pinecone
if (content) {
if (content.tabs) {
content.tabs.forEach(tab => {
formattedContents.push({
id: `${pageId}-${tab.name}`,
name: content.name,
url: content.url,
tabName: tab.name,
content: tab.content
});
});
} else {
formattedContents.push({
id: pageId,
name: content.name,
url: content.url,
content: content.content
});
}
}
}
fs.writeFileSync('formattedResponse.json', JSON.stringify(formattedContents, null, 2));
}
// Call the function to execute it
writePageContentsToFile();
The main thing to point out here is that when we’re running getPageContent() we’re checking if there is tabbed content and flattening it, so it’s easier to process with Pinecone. The only other thing to highlight is that the id needs to be a unique string, which is why we’re using the pageId for pages, and ${pageId}-${tab.name} for tabbed content. Finally, we’re using the file system (fs) module to write the contents to a JSON file.
run node fetchFromZeroheight.js and you’re reading to go.
The next step is taking that JSON and putting it into a format that is readable as a vector database. I use Pinecone to do this, which is a pretty simple way of doing it. They also have a free tier that works well for this kind of thing.

You’ll need to create an account with Pinecone and set up an index. For these kinds of systems, using the openAI text-embedding-3-small model is good enough to embed the data. You’ll also need to create an API key to allow you to interface with Pinecone and push your data. You’ll also need an OpenAI API key, as we’ll use this to create the vector mappings.
const fs = require('fs');
const axios = require('axios');
const { OpenAI } = require('openai');
const PINECONE_API_KEY = '{PINECONE_API_KEY}'; // Add your Pinecone API key
const PINECONE_INDEX_NAME = '{PINECONE_INDEX_NAME}'; // Add your Pinecone index name
const OPENAI_API_KEY = '{OPENAI_API_KEY}'; // Add your OpenAI API key
const PINECONE_URL = `{PIENCONE_URL}/vectors/upsert`; // Pinecone API URL. Replace {PINECONE_URL} with your Pinecone URL (found on your dashboard)
const pushToPinecone = async () => {
console.log('Starting script...');
try {
// Step 1: Read input file
console.log('Reading input file...');
const rawData = fs.readFileSync('formattedResponse.json', 'utf8');
const data = JSON.parse(rawData);
console.log(`Loaded ${data.length} records from file.`);
// Initialize OpenAI
const openai = new OpenAI({ apiKey: OPENAI_API_KEY });
// Step 2: Generate embeddings and push individually to Pinecone
console.log('Processing each record...');
for (const item of data) {
try {
console.log(`Generating embedding for item ID: ${item.id}`);
const response = await openai.embeddings.create({
model: 'text-embedding-ada-002',
input: item.content || '', // Use empty string if content is missing
});
const embedding = response.data[0].embedding;
const vector = {
vectors: [
{
id: String(item.id), // Convert ID to string
values: embedding,
metadata: {
name: item.name,
url: item.url,
tabName: item.tabName,
content: item.content, // Store the original text as metadata
},
},
],
};
console.log(`Pushing vector for item ID: ${item.id} to Pinecone...`);
const upsertResponse = await axios.post(PINECONE_URL, vector, {
headers: {
'Api-Key': PINECONE_API_KEY,
'Content-Type': 'application/json',
},
});
console.log(`Successfully pushed item ID: ${item.id}. Response:`, upsertResponse.data);
} catch (error) {
console.error(`Error processing item ID: ${item.id}:`, error.message);
if (error.response?.data) {
console.error('Detailed error response:', JSON.stringify(error.response.data, null, 2));
}
}
}
console.log('All records processed.');
} catch (error) {
console.error('Unexpected error:', error.message);
}
};
pushToPinecone();
What this does is grab the file that we created with fetchFromZeroheight.js and create vector embeddings for Pinecone. A vector embedding is a numerical representation of data, whether that be words, images, video, or audio, designed to capture the semantic meaning. These data points are mapped closer together in the vector space, enabling things like similarity searches, clustering, and information retrieval. This is how LLMs work to give you the best information. The good thing is, we can actually use an LLM to transform the data and create these vector embeddings for us.
In this case, we send the data off to OpenAI and create embeddings using their text-embedding-ada-002 model. The text embedding comes back as an array of coordinates. We don’t need to know how this works, know that it does. We then send that data to Pinecone using their upsert API endpoint.
The important things to note here are that the id needs to be a unique string, and all the actual text content you want to be able to reference needs to be in ‘metadata’. In this case, we’re sending through the name of the page, the name of the tab, the url, and the content of the page as markdown.
In this case, we’re pushing each record individually. You can batch push, but I found for error handling purposes this helped me more to be able to see what was going on, especially as the push can take a few minutes.
Once you’re ready to go, make sure you have all the required packages installed by running:
npm install axios openai
then run the script and watch it go:
node pushToPinecone.js
Now we have everything in Pinecone, it’s time to build a little NodeJS interface to be able to query the data!
app.js
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const axios = require('axios');
const path = require('path'); // Add this for serving static files
const app = express();
const PORT = 3000;
// Configure Pinecone and OpenAI
const PINECONE_API_KEY = '{PINECONE_API_KEY}'; // Add your Pinecone API key
const PINECONE_INDEX_NAME = '{PINECONE_INDEX_NAME}'; // Add your Pinecone index name
const PINECONE_QUERY_URL = `{PIENCONE_URL}/query`; // Pinecone API URL. Replace {PINECONE_URL} with your Pinecone URL (found on your dashboard)
const OPENAI_API_KEY = '{OPENAI_API_KEY}'; // Add your OpenAI API key
// Middleware
app.use(cors());
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'public')));
// Endpoint to handle chat queries
app.post('/query', async (req, res) => {
const { query } = req.body;
if (!query) {
return res.status(400).json({ error: 'Query is required' });
}
try {
// Step 1: Use OpenAI to generate a query embedding
const embeddingResponse = await axios.post(
'<https://api.openai.com/v1/embeddings>',
{
model: 'text-embedding-ada-002',
input: query,
},
{
headers: {
Authorization: `Bearer ${OPENAI_API_KEY}`,
},
}
);
const embedding = embeddingResponse.data.data[0].embedding;
// Step 2: Query Pinecone with the embedding
const pineconeResponse = await axios.post(
PINECONE_QUERY_URL,
{
vector: embedding,
topK: 5,
includeMetadata: true,
},
{
headers: {
'Api-Key': PINECONE_API_KEY,
'Content-Type': 'application/json',
},
}
);
const matches = pineconeResponse.data.matches;
if (!matches || matches.length === 0) {
return res.json({ response: "I couldn't find any relevant information." });
}
// Step 3: Fit analysis and deduplication
const SIMILARITY_THRESHOLD = 0.7;
const filteredMatches = matches.filter((match) => match.score >= SIMILARITY_THRESHOLD);
if (filteredMatches.length === 0) {
return res.json({ response: "No highly relevant content was found for your query." });
}
const uniqueContent = new Map();
filteredMatches.forEach((match) => {
if (!uniqueContent.has(match.metadata.content)) {
uniqueContent.set(match.metadata.content, {
name: match.metadata.name,
url: match.metadata.url,
});
}
});
const combinedContent = Array.from(uniqueContent.keys()).join('\n\n');
const sourcesHtml = Array.from(uniqueContent.values())
.map(
(source) =>
`<li><a href="${source.url}" target="_blank">${source.name}</a></li>`
)
.join('');
// Step 4: Generate a summary using OpenAI
const finalResponse = await axios.post(
'<https://api.openai.com/v1/chat/completions>',
{
model: 'gpt-4o',
messages: [
{ role: 'system', content: 'You are a helpful assistant that summarizes content from a design system docuementation site for users. The site is the AirOrange Design System. The Airorange design system is a fictional design system for a fictional airline brand, that was built to show off the features of zeroheight, the desig system management platform.' },
{ role: 'user', content: `Summarize the following highly relevant content based on the query: "${query}".\n\n${combinedContent}. Return the content in a nicely formatted way, with a short introduction paragraph explaining what you've found in a conversational way with the user. Then chunk the findings into bullet points underneath, summarizing it to 3-5 bullet points that are the most useful. Use emojis if you want to.` },
],
},
{
headers: {
Authorization: `Bearer ${OPENAI_API_KEY}`,
},
}
);
let summary = finalResponse.data.choices[0].message.content;
// Step 5: Format the summary into HTML
summary = formatSummary(summary);
// Return the formatted response with sources
res.json({
response: `${summary}<h4>Sources:</h4><ul>${sourcesHtml}</ul>`,
});
} catch (error) {
console.error('Error querying Pinecone or OpenAI:', error.message);
res.status(500).json({ error: 'An error occurred while processing the request.' });
}
});
// Helper function to format summary
function formatSummary(summary) {
// Replace markdown **text** with <h3>
summary = summary.replace(/\*\*(.*?)\*\*/g, '<h3>$1</h3>');
// Replace markdown - items with <ul><li> items
summary = summary.replace(/^- (.*)/gm, '<li>$1</li>');
summary = summary.replace(/(<li>.*<\/li>)/g, '<ul>$1</ul>');
// Remove duplicate <ul> tags for nested lists
summary = summary.replace(/<\/ul>\s*<ul>/g, '');
return summary;
}
// Start the server
app.listen(PORT, () => {
console.log(`Server is running on <http://localhost>:${PORT}`);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Chatbot</title>
<style>
body {
font-family: Arial, sans-serif;
margin: 20px;
}
.chatbox {
max-width: 600px;
margin: 0 auto;
}
textarea {
width: 100%;
height: 100px;
margin-top: 10px;
padding: 10px;
font-size: 16px;
}
button {
display: block;
width: 100%;
padding: 10px;
font-size: 16px;
margin-top: 10px;
cursor: pointer;
}
.response {
margin-top: 20px;
padding: 10px;
background: #f1f1f1;
border-radius: 5px;
}
</style>
</head>
<body>
<div class="chatbox">
<h1>Ask the Chatbot</h1>
<textarea id="query" placeholder="Type your question here..."></textarea>
<button onclick="askQuestion()">Ask</button>
<div class="response" id="response"></div>
</div>
<script>
async function askQuestion() {
const query = document.getElementById('query').value;
const responseDiv = document.getElementById('response');
responseDiv.textContent = 'Processing...';
try {
const response = await fetch('<http://localhost:3000/query>', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ query }),
});
const data = await response.json();
if (data.response) {
responseDiv.innerHTML = `<strong>Response:</strong><br>${data.response}`;
} else {
responseDiv.innerHTML = `<strong>Error:</strong><br>${data.error || 'Unknown error occurred.'}`;
}
} catch (error) {
responseDiv.innerHTML = `<strong>Error:</strong><br>${error.message}`;
}
}
</script>
</body>
</html>
First off all the stuff that we use to make this work easily. We’re using express (with cors and bodyParser) to run the server on our local machine, and we’re using Axios to handle the queries to Pinecone and OpenAI. So to begin with, install these:
npm install axios express
The first step in the process is to grab the /query from our index.html, and then transform it into a query embedding that openAI understands. Again, we can use text-embedding-ada-002 to do this for us.
We will then send that query to Pinecone to query against our database. The important variable here to know about is topK. Changing that value will change the amount of results that are returned. We can then specify how relevant we want the date with the SIMILARITY_THRESHOLD variable. If you have this set to 1, it will only return exact matches. If you have it set to 0.1, it will return everything it thinks could be relevant. Setting the threshold to around 0.7 means that you’ll have highly relevant, filtered matches to feed into OpenAI.
One thing I like to do here is then provide the sources for the information, especially if we’re trying to summarize it using OpenAI. To do that, it pulls the URLs of the filtered matches and puts them in a ‘sources’ section at the bottom of the response.
Finally, it summarizes the content that it’s received using OpenAI. This is the area that you will probably want to spend a fair amount of time tweaking to get the right output. If you’ve used ChatGPT, you’ll be familiar with the language you need to use here to get the prompt right. The first section (system) is where you’re defining how you want the LLM to act. The second section (user) is what the desired output is. You can be as descriptive as you like here, and keep testing to see what works.
One thing to note is that the response will come back as markdown, so you’ll need one extra step to format it. We’ve used a simple formatSummary to turn the markdown into html to serve up.

As you can see, this is a pretty simple implementation of how you can query your zeroheight content. Also, it’s worth noting that I’m not a developer, and ChatGPT actually helped me write most of this… The beauty of that is that if you’re trying to develop a proof of concept further, feeding this code into a ChatGPT instance and asking it to improve it based on your ideas, you’ll be able to take this and turn it into something way more powerful! Here are a few things that I’d do next:
One of the next steps I would take would be to create a script that runs via cron or actions to update the content in Pinecone on a regular basis. We could easily set up a daily job, and use the Pages list endpoint, combined with the data.pages.created_at and data.pages.updated_at to only pull updated content, and then push the content to either add or overwrite the data that exists in Pinecone. This would then mean your documentation is always in sync.
One improvement you could make for a better experience on the front end is to store the user’s chat in their session so they can have more contextual, flowing conversations. This is similar to what I did when I built a little proof of concept that queries the content on the zeroheight.com website.
If we’re considering user experience of the frontend, why not build something directly where people are, instead of requiring them to go somewhere else? This exact way of working could be built into a Slack or Figma app, so that folks can query directly in a Slack channel, or in an interface within Figma, so they can get the information without context switching.
One extra improvement I’d make is to expand out the way you handle queries… Using structured query understanding, you can segment off particular types of queries and make the responses more contextual. You can do this by either focusing the user and prompt that you send to openAI in the summary, or focus it based on the type of content it is referencing in Pinecone (or both).
For example, you could look for queries that are asking for content feedback or content audits, and have it specifically check against the content guidelines within zeroheight, and then structure the prompt so that it is specifically giving you feedback on what to improve based on those guidelines.
I could sit here for days and think of extra things that could be built in this way. The cool thing with this is that you can build small apps that meet your very specific needs. Want to build your own? Check out the API docs, fork this demo repo, and let me know what you build!
