Skip to content

Commit 54d33fb

Browse files
chore(testing): setup initial directory structure for JS (#1193)
1 parent e929942 commit 54d33fb

File tree

5 files changed

+368
-361
lines changed

5 files changed

+368
-361
lines changed

docs/en/getting-started/local_quickstart_js.md

Lines changed: 7 additions & 361 deletions
Original file line numberDiff line numberDiff line change
@@ -64,380 +64,26 @@ npm install @google/genai
6464
{{< tabpane persist=header >}}
6565
{{< tab header="LangChain" lang="js" >}}
6666

67-
import { ChatGoogleGenerativeAI } from "@langchain/google-genai";
68-
import { ToolboxClient } from "@toolbox-sdk/core";
69-
import { tool } from "@langchain/core/tools";
70-
import { createReactAgent } from "@langchain/langgraph/prebuilt";
71-
import { MemorySaver } from "@langchain/langgraph";
72-
73-
// Replace it with your API key
74-
process.env.GOOGLE_API_KEY = 'your-api-key';
75-
76-
const prompt = `
77-
You're a helpful hotel assistant. You handle hotel searching, booking, and
78-
cancellations. When the user searches for a hotel, mention its name, id,
79-
location and price tier. Always mention hotel ids while performing any
80-
searches. This is very important for any operations. For any bookings or
81-
cancellations, please provide the appropriate confirmation. Be sure to
82-
update checkin or checkout dates if mentioned by the user.
83-
Don't ask for confirmations from the user.
84-
`;
85-
86-
const queries = [
87-
"Find hotels in Basel with Basel in its name.",
88-
"Can you book the Hilton Basel for me?",
89-
"Oh wait, this is too expensive. Please cancel it and book the Hyatt Regency instead.",
90-
"My check in dates would be from April 10, 2024 to April 19, 2024.",
91-
];
92-
93-
async function main() {
94-
const model = new ChatGoogleGenerativeAI({
95-
model: "gemini-2.0-flash",
96-
});
97-
98-
const client = new ToolboxClient("http://127.0.0.1:5000");
99-
const toolboxTools = await client.loadToolset("my-toolset");
100-
101-
// Define the basics of the tool: name, description, schema and core logic
102-
const getTool = (toolboxTool) => tool(toolboxTool, {
103-
name: toolboxTool.getName(),
104-
description: toolboxTool.getDescription(),
105-
schema: toolboxTool.getParamSchema()
106-
});
107-
const tools = toolboxTools.map(getTool);
108-
109-
const agent = createReactAgent({
110-
llm: model,
111-
tools: tools,
112-
checkpointer: new MemorySaver(),
113-
systemPrompt: prompt,
114-
});
115-
116-
const langGraphConfig = {
117-
configurable: {
118-
thread_id: "test-thread",
119-
},
120-
};
121-
122-
for (const query of queries) {
123-
const agentOutput = await agent.invoke(
124-
{
125-
messages: [
126-
{
127-
role: "user",
128-
content: query,
129-
},
130-
],
131-
verbose: true,
132-
},
133-
langGraphConfig
134-
);
135-
const response = agentOutput.messages[agentOutput.messages.length - 1].content;
136-
console.log(response);
137-
}
138-
}
139-
140-
main();
67+
{{< include "quickstart/js/langchain/quickstart.js" >}}
14168

14269
{{< /tab >}}
14370

14471
{{< tab header="GenkitJS" lang="js" >}}
14572

146-
import { ToolboxClient } from "@toolbox-sdk/core";
147-
import { genkit } from "genkit";
148-
import { googleAI } from '@genkit-ai/googleai';
149-
150-
// Replace it with your API key
151-
process.env.GOOGLE_API_KEY = 'your-api-key';
152-
153-
const systemPrompt = `
154-
You're a helpful hotel assistant. You handle hotel searching, booking, and
155-
cancellations. When the user searches for a hotel, mention its name, id,
156-
location and price tier. Always mention hotel ids while performing any
157-
searches. This is very important for any operations. For any bookings or
158-
cancellations, please provide the appropriate confirmation. Be sure to
159-
update checkin or checkout dates if mentioned by the user.
160-
Don't ask for confirmations from the user.
161-
`;
162-
163-
const queries = [
164-
"Find hotels in Basel with Basel in its name.",
165-
"Can you book the Hilton Basel for me?",
166-
"Oh wait, this is too expensive. Please cancel it and book the Hyatt Regency instead.",
167-
"My check in dates would be from April 10, 2024 to April 19, 2024.",
168-
];
169-
170-
async function main() {
171-
const toolboxClient = new ToolboxClient("http://127.0.0.1:5000");
172-
173-
const ai = genkit({
174-
plugins: [
175-
googleAI({
176-
apiKey: process.env.GEMINI_API_KEY || process.env.GOOGLE_API_KEY
177-
})
178-
],
179-
model: googleAI.model('gemini-2.0-flash'),
180-
});
181-
182-
const toolboxTools = await toolboxClient.loadToolset("my-toolset");
183-
const toolMap = Object.fromEntries(
184-
toolboxTools.map((tool) => {
185-
const definedTool = ai.defineTool(
186-
{
187-
name: tool.getName(),
188-
description: tool.getDescription(),
189-
inputSchema: tool.getParamSchema(),
190-
},
191-
tool
192-
);
193-
return [tool.getName(), definedTool];
194-
})
195-
);
196-
const tools = Object.values(toolMap);
197-
198-
let conversationHistory = [{ role: "system", content: [{ text: systemPrompt }] }];
199-
200-
for (const query of queries) {
201-
conversationHistory.push({ role: "user", content: [{ text: query }] });
202-
const response = await ai.generate({
203-
messages: conversationHistory,
204-
tools: tools,
205-
});
206-
conversationHistory.push(response.message);
207-
208-
const toolRequests = response.toolRequests;
209-
if (toolRequests?.length > 0) {
210-
// Execute tools concurrently and collect their responses.
211-
const toolResponses = await Promise.all(
212-
toolRequests.map(async (call) => {
213-
try {
214-
const toolOutput = await toolMap[call.name].invoke(call.input);
215-
return { role: "tool", content: [{ toolResponse: { name: call.name, output: toolOutput } }] };
216-
} catch (e) {
217-
console.error(`Error executing tool ${call.name}:`, e);
218-
return { role: "tool", content: [{ toolResponse: { name: call.name, output: { error: e.message } } }] };
219-
}
220-
})
221-
);
222-
223-
conversationHistory.push(...toolResponses);
224-
225-
// Call the AI again with the tool results.
226-
response = await ai.generate({ messages: conversationHistory, tools });
227-
conversationHistory.push(response.message);
228-
}
229-
230-
console.log(response.text);
231-
}
232-
}
233-
234-
main();
73+
{{< include "quickstart/js/genkit/quickstart.js" >}}
74+
23575
{{< /tab >}}
23676

23777
{{< tab header="LlamaIndex" lang="js" >}}
23878

239-
import { gemini, GEMINI_MODEL } from "@llamaindex/google";
240-
import { agent } from "@llamaindex/workflow";
241-
import { createMemory, staticBlock, tool } from "llamaindex";
242-
import { ToolboxClient } from "@toolbox-sdk/core";
243-
244-
const TOOLBOX_URL = "http://127.0.0.1:5000"; // Update if needed
245-
process.env.GOOGLE_API_KEY = 'your-api-key'; // Replace it with your API key
246-
247-
const prompt = `
248-
249-
You're a helpful hotel assistant. You handle hotel searching, booking and cancellations.
250-
When the user searches for a hotel, mention its name, id, location and price tier.
251-
Always mention hotel ids while performing any searches — this is very important for operations.
252-
For any bookings or cancellations, please provide the appropriate confirmation.
253-
Update check-in or check-out dates if mentioned by the user.
254-
Don't ask for confirmations from the user.
255-
256-
`;
257-
258-
const queries = [
259-
"Find hotels in Basel with Basel in its name.",
260-
"Can you book the Hilton Basel for me?",
261-
"Oh wait, this is too expensive. Please cancel it and book the Hyatt Regency instead.",
262-
"My check in dates would be from April 10, 2024 to April 19, 2024.",
263-
];
264-
265-
async function main() {
266-
// Connect to MCP Toolbox
267-
const client = new ToolboxClient(TOOLBOX_URL);
268-
const toolboxTools = await client.loadToolset("my-toolset");
269-
const tools = toolboxTools.map((toolboxTool) => {
270-
return tool({
271-
name: toolboxTool.getName(),
272-
description: toolboxTool.getDescription(),
273-
parameters: toolboxTool.getParamSchema(),
274-
execute: toolboxTool,
275-
});
276-
});
277-
278-
// Initialize LLM
279-
const llm = gemini({
280-
model: GEMINI_MODEL.GEMINI_2_0_FLASH,
281-
apiKey: process.env.GOOGLE_API_KEY,
282-
});
283-
284-
const memory = createMemory({
285-
memoryBlocks: [
286-
staticBlock({
287-
content: prompt,
288-
}),
289-
],
290-
});
291-
292-
// Create the Agent
293-
const myAgent = agent({
294-
tools: tools,
295-
llm,
296-
memory,
297-
systemPrompt: prompt,
298-
});
299-
300-
for (const query of queries) {
301-
const result = await myAgent.run(query);
302-
const output = result.data.result;
303-
304-
console.log(`\nUser: ${query}`);
305-
if (typeof output === "string") {
306-
console.log(output.trim());
307-
} else if (typeof output === "object" && "text" in output) {
308-
console.log(output.text.trim());
309-
} else {
310-
console.log(JSON.stringify(output));
311-
}
312-
}
313-
//You may observe some extra logs during execution due to the run method provided by Llama.
314-
console.log("Agent run finished.");
315-
}
316-
317-
main();
79+
{{< include "quickstart/js/llamaindex/quickstart.js" >}}
31880

31981
{{< /tab >}}
32082

32183
{{< tab header="GoogleGenAI" lang="js" >}}
322-
import { GoogleGenAI } from "@google/genai";
323-
import { ToolboxClient } from "@toolbox-sdk/core";
324-
325-
326-
const TOOLBOX_URL = "http://127.0.0.1:5000"; // Update if needed
327-
const GOOGLE_API_KEY = 'enter your api here'; // Replace it with your API key
328-
329-
const prompt = `
330-
You're a helpful hotel assistant. You handle hotel searching, booking, and
331-
cancellations. When the user searches for a hotel, you MUST use the available tools to find information. Mention its name, id,
332-
location and price tier. Always mention hotel id while performing any
333-
searches. This is very important for any operations. For any bookings or
334-
cancellations, please provide the appropriate confirmation. Be sure to
335-
update checkin or checkout dates if mentioned by the user.
336-
Don't ask for confirmations from the user.
337-
`;
338-
339-
const queries = [
340-
"Find hotels in Basel with Basel in its name.",
341-
"Can you book the Hilton Basel for me?",
342-
"Oh wait, this is too expensive. Please cancel it and book the Hyatt Regency instead.",
343-
"My check in dates would be from April 10, 2024 to April 19, 2024.",
344-
];
345-
346-
function mapZodTypeToOpenAPIType(zodTypeName) {
347-
348-
console.log(zodTypeName)
349-
const typeMap = {
350-
'ZodString': 'string',
351-
'ZodNumber': 'number',
352-
'ZodBoolean': 'boolean',
353-
'ZodArray': 'array',
354-
'ZodObject': 'object',
355-
};
356-
return typeMap[zodTypeName] || 'string';
357-
}
358-
359-
async function main() {
360-
361-
const toolboxClient = new ToolboxClient(TOOLBOX_URL);
362-
const toolboxTools = await toolboxClient.loadToolset("my-toolset");
363-
364-
const geminiTools = [{
365-
functionDeclarations: toolboxTools.map(tool => {
366-
367-
const schema = tool.getParamSchema();
368-
const properties = {};
369-
const required = [];
370-
371-
372-
for (const [key, param] of Object.entries(schema.shape)) {
373-
properties[key] = {
374-
type: mapZodTypeToOpenAPIType(param.constructor.name),
375-
description: param.description || '',
376-
};
377-
required.push(key)
378-
}
379-
380-
return {
381-
name: tool.getName(),
382-
description: tool.getDescription(),
383-
parameters: { type: 'object', properties, required },
384-
};
385-
})
386-
}];
387-
388-
389-
const genAI = new GoogleGenAI({ apiKey: GOOGLE_API_KEY });
390-
391-
const chat = genAI.chats.create({
392-
model: "gemini-2.5-flash",
393-
config: {
394-
systemInstruction: prompt,
395-
tools: geminiTools,
396-
}
397-
});
398-
399-
for (const query of queries) {
400-
401-
let currentResult = await chat.sendMessage({ message: query });
402-
403-
let finalResponseGiven = false
404-
while (!finalResponseGiven) {
405-
406-
const response = currentResult;
407-
const functionCalls = response.functionCalls || [];
408-
409-
if (functionCalls.length === 0) {
410-
console.log(response.text)
411-
finalResponseGiven = true;
412-
} else {
413-
const toolResponses = [];
414-
for (const call of functionCalls) {
415-
const toolName = call.name
416-
const toolToExecute = toolboxTools.find(t => t.getName() === toolName);
417-
418-
if (toolToExecute) {
419-
try {
420-
const functionResult = await toolToExecute(call.args);
421-
toolResponses.push({
422-
functionResponse: { name: call.name, response: { result: functionResult } }
423-
});
424-
} catch (e) {
425-
console.error(`Error executing tool '${toolName}':`, e);
426-
toolResponses.push({
427-
functionResponse: { name: call.name, response: { error: e.message } }
428-
});
429-
}
430-
}
431-
}
432-
433-
currentResult = await chat.sendMessage({ message: toolResponses });
434-
}
435-
}
436-
437-
}
438-
}
439-
440-
main();
84+
85+
{{< include "quickstart/js/genAI/quickstart.js" >}}
86+
44187
{{< /tab >}}
44288

44389
{{< /tabpane >}}

0 commit comments

Comments
 (0)