Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CODEOWNERS
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,5 @@ media @GoogleCloudPlatform/cloud-media-team @GoogleCloudPlatform/nodejs-samples-
healthcare @GoogleCloudPlatform/healthcare-life-sciences @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers
routeoptimization @GoogleCloudPlatform/geo-routeoptimization @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers
translate @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers @GoogleCloudPlatform/cloud-ml-translate-dev
developer-knowledge @GoogleCloudPlatform/nodejs-samples-reviewers @GoogleCloudPlatform/cloud-samples-reviewers

19 changes: 19 additions & 0 deletions developer-knowledge/.eslintrc.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

---
rules:
no-console: off
node/no-unsupported-features/node-builtins: off

29 changes: 29 additions & 0 deletions developer-knowledge/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Google Developer Knowledge API Node.js Samples

This directory contains Node.js code samples demonstrating how to use the [Google Developer Knowledge API](https://developers.google.com/knowledge) client library (`@google/developer-knowledge`).

## Setup

1. Enable the Developer Knowledge API on your Google Cloud project:

```bash
gcloud services enable developerknowledge.googleapis.com
```

2. Install dependencies:
```bash
npm install
```

## Samples

- **[Answer Query](answerQuery.js)**: Get a grounded, cited answer to a technical question (`developerknowledge_answer_query`).
- **[Get Document](getDocument.js)**: Retrieve a single documentation page with full markdown content (`developerknowledge_get_document`).
- **[Batch Get Documents](batchGetDocuments.js)**: Fetch multiple documentation pages in one call (`developerknowledge_batch_get_documents`).
- **[Search Document Chunks](searchDocumentChunks.js)**: Search public developer documentation chunks by query (`developerknowledge_search_document_chunks`).

## Running Tests

```bash
npm test
```
57 changes: 57 additions & 0 deletions developer-knowledge/answerQuery.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// [START developerknowledge_answer_query]
const {DeveloperKnowledgeClient} = require('@google/developer-knowledge');

/**
* Answers a developer question grounded in Google developer documentation.
*
* @param {string} query The technical question to answer.
*/
async function answerQuery(
query = 'How do I create a Google Cloud Storage bucket?'
) {
const client = new DeveloperKnowledgeClient();

const request = {
query,
};

const [response] = await client.answerQuery(request);

console.log(`Answer:\n${response.answer.answerText}\n`);
const citationsCount = response.answer.citations
? response.answer.citations.length
: 0;
const referencesCount = response.answer.references
? response.answer.references.length
: 0;
Comment on lines +36 to +42

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If response.answer is undefined or null (for example, if no answer could be generated for the query), accessing response.answer.answerText or its other properties directly will throw a TypeError. Use optional chaining or default values to safely handle cases where the answer is missing.

Suggested change
console.log(`Answer:\n${response.answer.answerText}\n`);
const citationsCount = response.answer.citations
? response.answer.citations.length
: 0;
const referencesCount = response.answer.references
? response.answer.references.length
: 0;
const answerText = response.answer?.answerText || '';
console.log('Answer:\n' + answerText + '\n');
const citationsCount = response.answer?.citations?.length || 0;
const referencesCount = response.answer?.references?.length || 0;

console.log(`Citations count: ${citationsCount}`);
console.log(`References count: ${referencesCount}`);

return response;
}
// [END developerknowledge_answer_query]

module.exports = {answerQuery};

if (require.main === module) {
answerQuery(...process.argv.slice(2)).catch(err => {
console.error(err);
process.exitCode = 1;
});
}
58 changes: 58 additions & 0 deletions developer-knowledge/batchGetDocuments.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// [START developerknowledge_batch_get_documents]
const {DeveloperKnowledgeClient} = require('@google/developer-knowledge');

/**
* Retrieves multiple developer documentation pages in a single request.
*
* @param {string[]} names Array of resource names in format 'documents/{uri_without_scheme}'.
*/
async function batchGetDocuments(
names = [
'documents/docs.cloud.google.com/storage/docs/creating-buckets',
'documents/docs.cloud.google.com/storage/docs/deleting-buckets',
]
) {
const client = new DeveloperKnowledgeClient();

const request = {
names,
};

const [response] = await client.batchGetDocuments(request);

if (response.documents) {
for (const doc of response.documents) {
console.log(`Title: ${doc.title}`);
console.log(`URI: ${doc.uri}`);
console.log(`Content Length: ${doc.contentLengthBytes} bytes\n`);
}
}

return response;
}
// [END developerknowledge_batch_get_documents]

module.exports = {batchGetDocuments};

if (require.main === module) {
batchGetDocuments().catch(err => {
console.error(err);
process.exitCode = 1;
});
}
53 changes: 53 additions & 0 deletions developer-knowledge/getDocument.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// [START developerknowledge_get_document]
const {DeveloperKnowledgeClient} = require('@google/developer-knowledge');

/**
* Retrieves a single developer documentation page by its resource name.
*
* @param {string} name The resource name in format 'documents/{uri_without_scheme}'.
*/
async function getDocument(
name = 'documents/docs.cloud.google.com/storage/docs/creating-buckets'
) {
const client = new DeveloperKnowledgeClient();

const request = {
name,
};

const [document] = await client.getDocument(request);

console.log(`Title: ${document.title}`);
console.log(`URI: ${document.uri}`);
console.log(`Data Source: ${document.dataSource}`);
console.log(`Content Length: ${document.contentLengthBytes} bytes`);
console.log(`Content Preview: ${document.content.substring(0, 150)}...\n`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If document.content is undefined or null, calling .substring() on it will throw a TypeError. Use a fallback empty string or optional chaining to safely handle missing content.

Suggested change
console.log(`Content Preview: ${document.content.substring(0, 150)}...\n`);
const contentPreview = (document.content || '').substring(0, 150);
console.log('Content Preview: ' + contentPreview + '...\n');


return document;
}
// [END developerknowledge_get_document]

module.exports = {getDocument};

if (require.main === module) {
getDocument(...process.argv.slice(2)).catch(err => {
console.error(err);
process.exitCode = 1;
});
}
28 changes: 28 additions & 0 deletions developer-knowledge/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"name": "nodejs-developer-knowledge-samples",
"description": "Node.js samples for Google Developer Knowledge API",
"version": "0.0.1",
"private": true,
"license": "Apache-2.0",
"author": "Google LLC",
"repository": {
"type": "git",
"url": "https://github.com/GoogleCloudPlatform/nodejs-docs-samples.git",
"directory": "developer-knowledge"
},
"engines": {
"node": ">=18.0.0"
},
"files": [
"*.js"
],
"scripts": {
"test": "mocha test/*.test.js --timeout 60000"
},
"dependencies": {
"@google/developer-knowledge": "^0.5.0"
},
"devDependencies": {
"mocha": "^10.0.0"
}
}
61 changes: 61 additions & 0 deletions developer-knowledge/searchDocumentChunks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
// Copyright 2026 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

'use strict';

// [START developerknowledge_search_document_chunks]
const {DeveloperKnowledgeClient} = require('@google/developer-knowledge');

/**
* Searches developer documentation chunks for a given query.
*
* @param {string} query The search query string.
* @param {number} pageSize The maximum number of document chunks to return.
*/
async function searchDocumentChunks(
query = 'How to create a Cloud Storage bucket',
pageSize = 5
) {
const client = new DeveloperKnowledgeClient();

const request = {
query,
pageSize,
};

// Warning: Should always disable autoPaginate to avoid iterating through all pages.
// By default NodeJS SDK returns an iterable where you can iterate through all
// search results instead of only the limited number of results requested on pageSize.
const [chunks] = await client.searchDocumentChunks(request, {
autoPaginate: false,
});

for (const chunk of chunks) {
console.log(`Parent Document: ${chunk.parent}`);
console.log(`Chunk ID: ${chunk.id}`);
console.log(`Content Preview: ${chunk.content.substring(0, 100)}...\n`);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

If chunk.content is undefined or null, calling .substring() on it will throw a TypeError. Use a fallback empty string or optional chaining to safely handle missing content.

    const contentPreview = (chunk.content || '').substring(0, 100);
    console.log('Content Preview: ' + contentPreview + '...\n');

}

return chunks;
}
// [END developerknowledge_search_document_chunks]

module.exports = {searchDocumentChunks};

if (require.main === module) {
searchDocumentChunks(...process.argv.slice(2)).catch(err => {
console.error(err);
process.exitCode = 1;
});
}
Loading
Loading