From c8258489b385ed04d6fadcc793788957330f901e Mon Sep 17 00:00:00 2001 From: Joshua Yu Date: Wed, 27 Nov 2024 19:34:56 -0500 Subject: [PATCH 01/12] chore: added initial files for google finance --- .../integrations/tools/google_finance.mdx | 0 examples/src/tools/google_finance.ts | 0 .../src/tools/google_finance.ts | 107 ++++++++++++++++++ .../tools/tests/google_finance.int.test.ts | 0 4 files changed, 107 insertions(+) create mode 100644 docs/core_docs/docs/integrations/tools/google_finance.mdx create mode 100644 examples/src/tools/google_finance.ts create mode 100644 libs/langchain-community/src/tools/google_finance.ts create mode 100644 libs/langchain-community/src/tools/tests/google_finance.int.test.ts diff --git a/docs/core_docs/docs/integrations/tools/google_finance.mdx b/docs/core_docs/docs/integrations/tools/google_finance.mdx new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/examples/src/tools/google_finance.ts b/examples/src/tools/google_finance.ts new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/libs/langchain-community/src/tools/google_finance.ts b/libs/langchain-community/src/tools/google_finance.ts new file mode 100644 index 000000000000..5926dd56a4ff --- /dev/null +++ b/libs/langchain-community/src/tools/google_finance.ts @@ -0,0 +1,107 @@ +import { Tool } from "@langchain/core/tools"; +import { getEnvironmentVariable } from "@langchain/core/utils/env"; +import fetch from "node-fetch"; + +/** + * Interface for parameters required by the GoogleFinanceAPI class. + */ +export interface GoogleFinanceAPIParams { + /** + * Optional API key for accessing the SerpApi service. + */ + apiKey?: string; +} + +/** + * Tool for querying Google Finance using the SerpApi service. + */ +export class GoogleFinanceAPI extends Tool { + static lc_name() { + return "GoogleFinanceAPI"; + } + + /** + * Returns a mapping of secret environment variable names to their usage in the tool. + * @returns {object} Mapping of secret names to their environment variable counterparts. + */ + get lc_secrets(): { [key: string]: string } | undefined { + return { + apiKey: "SERPAPI_API_KEY", + }; + } + + // Name of the tool, used for logging or identification within LangChain. + name = "google_finance"; + + // The API key used for making requests to SerpApi. + protected apiKey: string; + + /** + * Description of the tool for usage documentation. + */ + description = `A wrapper around Google Finance Search. + Useful for when you need to get information about + google search Finance from Google Finance. + Input should be a search query.`; + + /** + * Constructs a new instance of GoogleScholarAPI. + * @param fields - Optional parameters including an API key. + */ + constructor(fields?: GoogleFinanceAPIParams) { + super(...arguments); + + // Retrieve API key from fields or environment variables. + const apiKey = + fields?.apiKey ?? getEnvironmentVariable("SERPAPI_API_KEY"); + + // Throw an error if no API key is found. + if (!apiKey) { + throw new Error( + `SerpApi key not set. You can set it as "SERPAPI_API_KEY" in your environment variables.` + ); + } + this.apiKey = apiKey; + } + + /** + * Makes a request to SerpApi for Google Finance results. + * @param input - Search query string. + * @returns A JSON string containing the search results. + * @throws Error if the API request fails or returns an error. + */ + async _call(input: string): Promise { + // Construct the URL for the API request. + const url = `https://serpapi.com/search.json?q=${encodeURIComponent( + input + )}&engine=google_finance&api_key=${this.apiKey}`; + + // Make an HTTP GET request to the SerpApi service. + const response = await fetch(url); + + // Handle non-OK responses by extracting the error message. + if (!response.ok) { + let message; + try { + const json = await response.json(); + message = json.error; + } catch (error) { + message = + "Unable to parse error message: SerpApi did not return a JSON response."; + } + // Throw an error with detailed information about the failure. + throw new Error( + `Got ${response.status}: ${response.statusText} error from SerpApi: ${message}` + ); + } + + // Parse the JSON response from SerpApi. + const json = await response.json(); + + // Transform the raw response into a structured format. + const results = //TODO: Format response + + // Return the results as a formatted JSON string. + return JSON.stringify(results, null, 2); + } +} \ No newline at end of file diff --git a/libs/langchain-community/src/tools/tests/google_finance.int.test.ts b/libs/langchain-community/src/tools/tests/google_finance.int.test.ts new file mode 100644 index 000000000000..e69de29bb2d1 From 90c4cdaf8f5cd9c200db640a0b07d390f4979056 Mon Sep 17 00:00:00 2001 From: Mehrdad Ghannad Date: Wed, 27 Nov 2024 20:20:14 -0500 Subject: [PATCH 02/12] chore: added example for Google Finance tool --- examples/src/tools/google_finance.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/examples/src/tools/google_finance.ts b/examples/src/tools/google_finance.ts index e69de29bb2d1..e17958d8c505 100644 --- a/examples/src/tools/google_finance.ts +++ b/examples/src/tools/google_finance.ts @@ -0,0 +1,23 @@ +import { GoogleFinanceAPI } from "@langchain/community/tools/google_finance"; +import { OpenAI } from "@langchain/openai"; +import { initializeAgentExecutorWithOptions } from "langchain/agents"; + +export async function run() { + const model = new OpenAI({ + temperature: 0, + apiKey: process.env.OPENAI_API_KEY, + }); + + const tools = [new GoogleFinanceAPI()]; + + const financeAgent = await initializeAgentExecutorWithOptions(tools, model, { + agentType: "zero-shot-react-description", + verbose: true, + }); + + const result = await financeAgent.invoke({ + input: "What is the price of GOOG:NASDAQ?", + }); + + console.log(result.output); +} From 4b715ec45d0f7865a6369e70d22f1b789220e7b4 Mon Sep 17 00:00:00 2001 From: Joshua Yu Date: Wed, 27 Nov 2024 20:39:08 -0500 Subject: [PATCH 03/12] chore: added functionality to google finance tool --- .../src/tools/google_finance.ts | 23 ++++++++++--------- 1 file changed, 12 insertions(+), 11 deletions(-) diff --git a/libs/langchain-community/src/tools/google_finance.ts b/libs/langchain-community/src/tools/google_finance.ts index 5926dd56a4ff..613ef14d7281 100644 --- a/libs/langchain-community/src/tools/google_finance.ts +++ b/libs/langchain-community/src/tools/google_finance.ts @@ -45,7 +45,7 @@ export class GoogleFinanceAPI extends Tool { Input should be a search query.`; /** - * Constructs a new instance of GoogleScholarAPI. + * Constructs a new instance of GoogleFinanceAPI. * @param fields - Optional parameters including an API key. */ constructor(fields?: GoogleFinanceAPIParams) { @@ -73,12 +73,12 @@ export class GoogleFinanceAPI extends Tool { async _call(input: string): Promise { // Construct the URL for the API request. const url = `https://serpapi.com/search.json?q=${encodeURIComponent( - input - )}&engine=google_finance&api_key=${this.apiKey}`; - + input + )}&engine=google_finance&api_key=05f88ace01a07cc3ca26bd86664b5d2e579d2a5db45407f55a39d86ac7d47d1b`; + // Make an HTTP GET request to the SerpApi service. const response = await fetch(url); - + // Handle non-OK responses by extracting the error message. if (!response.ok) { let message; @@ -94,14 +94,15 @@ export class GoogleFinanceAPI extends Tool { `Got ${response.status}: ${response.statusText} error from SerpApi: ${message}` ); } - + // Parse the JSON response from SerpApi. const json = await response.json(); - - // Transform the raw response into a structured format. - const results = //TODO: Format response - + + // Remove metadata and search parameters from result. + if (json.search_metadata) delete json.search_metadata; + if (json.search_parameters) delete json.search_parameters; + // Return the results as a formatted JSON string. - return JSON.stringify(results, null, 2); + return JSON.stringify(json, null, 2); } } \ No newline at end of file From 421798541b8018166492204de8e940aeed869b17 Mon Sep 17 00:00:00 2001 From: KatH121 Date: Wed, 27 Nov 2024 20:51:46 -0500 Subject: [PATCH 04/12] description --- .../src/tools/google_finance.ts | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/libs/langchain-community/src/tools/google_finance.ts b/libs/langchain-community/src/tools/google_finance.ts index 613ef14d7281..692b32edd926 100644 --- a/libs/langchain-community/src/tools/google_finance.ts +++ b/libs/langchain-community/src/tools/google_finance.ts @@ -40,9 +40,17 @@ export class GoogleFinanceAPI extends Tool { * Description of the tool for usage documentation. */ description = `A wrapper around Google Finance Search. - Useful for when you need to get information about - google search Finance from Google Finance. - Input should be a search query.`; + Useful for when you need to get information about + google search Finance from Google Finance. + Input should be a search query that includes a stock ticker + (e.g. GOOG:NASDAQ). It provides detailed information on: + - Stock summary + - Markets + - Graph (price per minute) + - Knowledge graph + - News articles + - Financials + - Related searches that may be of interest `; /** * Constructs a new instance of GoogleFinanceAPI. From 66d535848eb0651e683ccaa542e0d692f2d28cfa Mon Sep 17 00:00:00 2001 From: Yuchuan Xue <114100120+JimXYC@users.noreply.github.com> Date: Wed, 27 Nov 2024 21:07:53 -0500 Subject: [PATCH 05/12] Update google_finance.mdx --- .../integrations/tools/google_finance.mdx | 36 +++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/docs/core_docs/docs/integrations/tools/google_finance.mdx b/docs/core_docs/docs/integrations/tools/google_finance.mdx index e69de29bb2d1..6c07b0c9025b 100644 --- a/docs/core_docs/docs/integrations/tools/google_finance.mdx +++ b/docs/core_docs/docs/integrations/tools/google_finance.mdx @@ -0,0 +1,36 @@ +--- +hide_table_of_contents: true +--- + +import CodeBlock from "@theme/CodeBlock"; + +# Google Finance Tool +The Google Finance Tool allows your agent to utilize the Google Finance API to retrieve financial data, such as stock prices, market trends, +exchange rates, and other investment-related information from Google Finance. + +## Setup +You should get the API key first before using the Tool. To get the key, first browse the website +(https://serpapi.com/users/sign_in) sign in with your github or google accountfrom () and follow the instruction to get the +free plan. (SerpAPI offers Google Finance API as part of its service) After you log in to your SerpApi account, you should +see your API key listed in "Your Account - Your Private API Key". After you get the key, set your API key as +`process.env.SERPAPI_API_KEY` or pass it in as an apiKey constructor argument. + + +## Usage + +import IntegrationInstallTooltip from "@mdx_components/integration_install_tooltip.mdx"; + + + +```bash npm2yarn +npm install @langchain/openai @langchain/community @langchain/core +``` + +import ToolExample from "@examples/tools/google_finance.ts"; + +{ToolExample} + +## Related + +- Tool [conceptual guide](/docs/concepts/tools) +- Tool [how-to guides](/docs/how_to/#tools) From 55be6d49160565121b44472e14f0041db1e9c463 Mon Sep 17 00:00:00 2001 From: Mehrdad Ghannad Date: Wed, 27 Nov 2024 21:28:47 -0500 Subject: [PATCH 06/12] chore: added integration tests for Google Finance tool --- .../tools/tests/google_finance.int.test.ts | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) diff --git a/libs/langchain-community/src/tools/tests/google_finance.int.test.ts b/libs/langchain-community/src/tools/tests/google_finance.int.test.ts index e69de29bb2d1..6f105a66f3fa 100644 --- a/libs/langchain-community/src/tools/tests/google_finance.int.test.ts +++ b/libs/langchain-community/src/tools/tests/google_finance.int.test.ts @@ -0,0 +1,27 @@ +import { expect, describe } from "@jest/globals"; +import { GoogleFinanceAPI } from "../google_finance.js"; + +describe("GoogleFinanceAPI", () => { + test("should be setup with correct parameters", async () => { + const instance = new GoogleFinanceAPI(); + expect(instance.name).toBe("google_finance"); + }); + + test("GoogleFinanceAPI returns expected result for valid query", async () => { + const tool = new GoogleFinanceAPI(); + + const result = await tool.invoke("GOOG:NASDAQ"); + + expect(result).toContain("Alphabet Inc."); + expect(result).toContain("GOOG"); + expect(result).toContain("NASDAQ"); + }); + + test("GoogleFinanceAPI returns '' for query on a non-existent ticker symbol", async () => { + const tool = new GoogleFinanceAPI(); + + const result = await tool.invoke("mkvdfmvkdmvkdovkam"); + + expect(result).toContain(""); + }); +}); From 810d964b24730da3a5487147f1708311f507b7a7 Mon Sep 17 00:00:00 2001 From: Mehrdad Ghannad Date: Wed, 27 Nov 2024 21:44:09 -0500 Subject: [PATCH 07/12] chore: update documentation setup section --- .../core_docs/docs/integrations/tools/google_finance.mdx | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/docs/core_docs/docs/integrations/tools/google_finance.mdx b/docs/core_docs/docs/integrations/tools/google_finance.mdx index 6c07b0c9025b..188f8824594d 100644 --- a/docs/core_docs/docs/integrations/tools/google_finance.mdx +++ b/docs/core_docs/docs/integrations/tools/google_finance.mdx @@ -9,12 +9,9 @@ The Google Finance Tool allows your agent to utilize the Google Finance API to r exchange rates, and other investment-related information from Google Finance. ## Setup -You should get the API key first before using the Tool. To get the key, first browse the website -(https://serpapi.com/users/sign_in) sign in with your github or google accountfrom () and follow the instruction to get the -free plan. (SerpAPI offers Google Finance API as part of its service) After you log in to your SerpApi account, you should -see your API key listed in "Your Account - Your Private API Key". After you get the key, set your API key as -`process.env.SERPAPI_API_KEY` or pass it in as an apiKey constructor argument. - +Before using the tool, ensure you have your API key. You can create an account on [SerpAPI](https://serpapi.com/users/sign_in) and obtain your API key +under **Your Private API Key** in your account dashboard. The Google Finance API is included in the free plan offered by SerpAPI. +Once you have the key, set it as `process.env.SERPAPI_API_KEY` or pass it as the `apiKey` argument when initializing the tool. ## Usage From 31d05b97190a55360152f84530f46e99170688b1 Mon Sep 17 00:00:00 2001 From: Joshua Yu Date: Wed, 27 Nov 2024 21:57:46 -0500 Subject: [PATCH 08/12] chore: update docs --- docs/core_docs/docs/integrations/tools/google_finance.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/core_docs/docs/integrations/tools/google_finance.mdx b/docs/core_docs/docs/integrations/tools/google_finance.mdx index 188f8824594d..ca0d8cfead41 100644 --- a/docs/core_docs/docs/integrations/tools/google_finance.mdx +++ b/docs/core_docs/docs/integrations/tools/google_finance.mdx @@ -11,7 +11,7 @@ exchange rates, and other investment-related information from Google Finance. ## Setup Before using the tool, ensure you have your API key. You can create an account on [SerpAPI](https://serpapi.com/users/sign_in) and obtain your API key under **Your Private API Key** in your account dashboard. The Google Finance API is included in the free plan offered by SerpAPI. -Once you have the key, set it as `process.env.SERPAPI_API_KEY` or pass it as the `apiKey` argument when initializing the tool. +Once you have the key, set it to the `SERPAPI_API_KEY` environment variable or pass it in as the `apiKey` argument when initializing the tool. ## Usage From 7884054b3e31beee581ab18de87edbdd4f9bebb7 Mon Sep 17 00:00:00 2001 From: Joshua Yu Date: Thu, 28 Nov 2024 16:49:57 -0500 Subject: [PATCH 09/12] chore: Passes linting and formatting --- .../src/tools/google_finance.ts | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/libs/langchain-community/src/tools/google_finance.ts b/libs/langchain-community/src/tools/google_finance.ts index 692b32edd926..37cded658a36 100644 --- a/libs/langchain-community/src/tools/google_finance.ts +++ b/libs/langchain-community/src/tools/google_finance.ts @@ -60,8 +60,7 @@ export class GoogleFinanceAPI extends Tool { super(...arguments); // Retrieve API key from fields or environment variables. - const apiKey = - fields?.apiKey ?? getEnvironmentVariable("SERPAPI_API_KEY"); + const apiKey = fields?.apiKey ?? getEnvironmentVariable("SERPAPI_API_KEY"); // Throw an error if no API key is found. if (!apiKey) { @@ -83,10 +82,10 @@ export class GoogleFinanceAPI extends Tool { const url = `https://serpapi.com/search.json?q=${encodeURIComponent( input )}&engine=google_finance&api_key=05f88ace01a07cc3ca26bd86664b5d2e579d2a5db45407f55a39d86ac7d47d1b`; - + // Make an HTTP GET request to the SerpApi service. const response = await fetch(url); - + // Handle non-OK responses by extracting the error message. if (!response.ok) { let message; @@ -102,15 +101,15 @@ export class GoogleFinanceAPI extends Tool { `Got ${response.status}: ${response.statusText} error from SerpApi: ${message}` ); } - + // Parse the JSON response from SerpApi. const json = await response.json(); - + // Remove metadata and search parameters from result. if (json.search_metadata) delete json.search_metadata; if (json.search_parameters) delete json.search_parameters; - + // Return the results as a formatted JSON string. return JSON.stringify(json, null, 2); } -} \ No newline at end of file +} From a2262d13e7c07c0004d96525e9b0cd2cfbbb580e Mon Sep 17 00:00:00 2001 From: Joshua Yu Date: Thu, 28 Nov 2024 17:13:13 -0500 Subject: [PATCH 10/12] chore: removed unneccessary import, added entrypoint --- libs/langchain-community/langchain.config.js | 1 + libs/langchain-community/src/tools/google_finance.ts | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/libs/langchain-community/langchain.config.js b/libs/langchain-community/langchain.config.js index 4a402c6941e8..b00648a66bb6 100644 --- a/libs/langchain-community/langchain.config.js +++ b/libs/langchain-community/langchain.config.js @@ -50,6 +50,7 @@ export const config = { "tools/gmail": "tools/gmail/index", "tools/google_calendar": "tools/google_calendar/index", "tools/google_custom_search": "tools/google_custom_search", + "tools/google_finance": "tools/google_finance", "tools/google_places": "tools/google_places", "tools/google_routes": "tools/google_routes", "tools/ifttt": "tools/ifttt", diff --git a/libs/langchain-community/src/tools/google_finance.ts b/libs/langchain-community/src/tools/google_finance.ts index 37cded658a36..32d459bc822b 100644 --- a/libs/langchain-community/src/tools/google_finance.ts +++ b/libs/langchain-community/src/tools/google_finance.ts @@ -1,6 +1,5 @@ import { Tool } from "@langchain/core/tools"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; -import fetch from "node-fetch"; /** * Interface for parameters required by the GoogleFinanceAPI class. From d63dde0120123b8bd0231f422a6b76ad6153c7f3 Mon Sep 17 00:00:00 2001 From: Joshua Yu Date: Tue, 3 Dec 2024 22:52:15 -0500 Subject: [PATCH 11/12] fix: update example/test, rename tool --- examples/src/tools/google_finance.ts | 26 ++++++++++++------- .../src/tools/google_finance.ts | 12 ++++----- .../tools/tests/google_finance.int.test.ts | 14 +++++----- 3 files changed, 29 insertions(+), 23 deletions(-) diff --git a/examples/src/tools/google_finance.ts b/examples/src/tools/google_finance.ts index e17958d8c505..8962c1bd85ab 100644 --- a/examples/src/tools/google_finance.ts +++ b/examples/src/tools/google_finance.ts @@ -1,6 +1,6 @@ -import { GoogleFinanceAPI } from "@langchain/community/tools/google_finance"; +import { SERPGoogleFinanceAPITool } from "@langchain/community/tools/google_finance"; import { OpenAI } from "@langchain/openai"; -import { initializeAgentExecutorWithOptions } from "langchain/agents"; +import { createReactAgent } from "@langchain/langgraph/prebuilt"; export async function run() { const model = new OpenAI({ @@ -8,16 +8,22 @@ export async function run() { apiKey: process.env.OPENAI_API_KEY, }); - const tools = [new GoogleFinanceAPI()]; + const tools = [ + new SERPGoogleFinanceAPITool({ apiKey: process.env.SERPAPI_API_KEY }), + ]; - const financeAgent = await initializeAgentExecutorWithOptions(tools, model, { - agentType: "zero-shot-react-description", - verbose: true, + const financeAgent = createReactAgent({ + llm: model, + tools: tools, }); - const result = await financeAgent.invoke({ - input: "What is the price of GOOG:NASDAQ?", - }); + const inputs = { + messages: [{ role: "user", content: "what is the price of GOOG:NASDAQ?" }], + }; + + const stream = await financeAgent.stream(inputs, { streamMode: "values" }); - console.log(result.output); + for await (const { messages } of stream) { + console.log(messages); + } } diff --git a/libs/langchain-community/src/tools/google_finance.ts b/libs/langchain-community/src/tools/google_finance.ts index 32d459bc822b..7216fcc20433 100644 --- a/libs/langchain-community/src/tools/google_finance.ts +++ b/libs/langchain-community/src/tools/google_finance.ts @@ -2,9 +2,9 @@ import { Tool } from "@langchain/core/tools"; import { getEnvironmentVariable } from "@langchain/core/utils/env"; /** - * Interface for parameters required by the GoogleFinanceAPI class. + * Interface for parameters required by the SERPGoogleFinanceAPITool class. */ -export interface GoogleFinanceAPIParams { +export interface SERPGoogleFinanceAPIToolParams { /** * Optional API key for accessing the SerpApi service. */ @@ -14,7 +14,7 @@ export interface GoogleFinanceAPIParams { /** * Tool for querying Google Finance using the SerpApi service. */ -export class GoogleFinanceAPI extends Tool { +export class SERPGoogleFinanceAPITool extends Tool { static lc_name() { return "GoogleFinanceAPI"; } @@ -52,10 +52,10 @@ export class GoogleFinanceAPI extends Tool { - Related searches that may be of interest `; /** - * Constructs a new instance of GoogleFinanceAPI. + * Constructs a new instance of SERPGoogleFinanceAPITool. * @param fields - Optional parameters including an API key. */ - constructor(fields?: GoogleFinanceAPIParams) { + constructor(fields?: SERPGoogleFinanceAPIToolParams) { super(...arguments); // Retrieve API key from fields or environment variables. @@ -80,7 +80,7 @@ export class GoogleFinanceAPI extends Tool { // Construct the URL for the API request. const url = `https://serpapi.com/search.json?q=${encodeURIComponent( input - )}&engine=google_finance&api_key=05f88ace01a07cc3ca26bd86664b5d2e579d2a5db45407f55a39d86ac7d47d1b`; + )}&engine=google_finance&api_key=${encodeURIComponent(this.apiKey)}`; // Make an HTTP GET request to the SerpApi service. const response = await fetch(url); diff --git a/libs/langchain-community/src/tools/tests/google_finance.int.test.ts b/libs/langchain-community/src/tools/tests/google_finance.int.test.ts index 6f105a66f3fa..60a67e440dbb 100644 --- a/libs/langchain-community/src/tools/tests/google_finance.int.test.ts +++ b/libs/langchain-community/src/tools/tests/google_finance.int.test.ts @@ -1,14 +1,14 @@ import { expect, describe } from "@jest/globals"; -import { GoogleFinanceAPI } from "../google_finance.js"; +import { SERPGoogleFinanceAPITool } from "../google_finance.js"; -describe("GoogleFinanceAPI", () => { +describe("SERPGoogleFinanceAPITool", () => { test("should be setup with correct parameters", async () => { - const instance = new GoogleFinanceAPI(); + const instance = new SERPGoogleFinanceAPITool(); expect(instance.name).toBe("google_finance"); }); - test("GoogleFinanceAPI returns expected result for valid query", async () => { - const tool = new GoogleFinanceAPI(); + test("SERPGoogleFinanceAPITool returns expected result for valid query", async () => { + const tool = new SERPGoogleFinanceAPITool(); const result = await tool.invoke("GOOG:NASDAQ"); @@ -17,8 +17,8 @@ describe("GoogleFinanceAPI", () => { expect(result).toContain("NASDAQ"); }); - test("GoogleFinanceAPI returns '' for query on a non-existent ticker symbol", async () => { - const tool = new GoogleFinanceAPI(); + test("SERPGoogleFinanceAPITool returns '' for query on a non-existent ticker symbol", async () => { + const tool = new SERPGoogleFinanceAPITool(); const result = await tool.invoke("mkvdfmvkdmvkdovkam"); From 68c6a38f16017d3370341ac1718df7351f6c15bc Mon Sep 17 00:00:00 2001 From: Joshua Yu Date: Wed, 4 Dec 2024 00:55:38 -0500 Subject: [PATCH 12/12] fix: update docs to match template --- .../integrations/tools/google_finance.ipynb | 265 ++++++++++++++++++ .../integrations/tools/google_finance.mdx | 235 +++++++++++++--- 2 files changed, 467 insertions(+), 33 deletions(-) create mode 100644 docs/core_docs/docs/integrations/tools/google_finance.ipynb diff --git a/docs/core_docs/docs/integrations/tools/google_finance.ipynb b/docs/core_docs/docs/integrations/tools/google_finance.ipynb new file mode 100644 index 000000000000..22027fbf945b --- /dev/null +++ b/docs/core_docs/docs/integrations/tools/google_finance.ipynb @@ -0,0 +1,265 @@ +{ + "cells": [ + { + "cell_type": "raw", + "id": "10238e62-3465-4973-9279-606cbb7ccf16", + "metadata": { + "vscode": { + "languageId": "raw" + } + }, + "source": [ + "---\n", + "sidebar_label: Google Finance Tool\n", + "---" + ] + }, + { + "cell_type": "markdown", + "id": "a6f91f20", + "metadata": {}, + "source": [ + "# Google Finance Tool\n", + "\n", + "This notebook provides a quick overview for getting started with [`Google Finance Tool`](/docs/integrations/tools/). For detailed documentation of all `Google Finance Tool` features and configurations head to the [API reference](https://v03.api.js.langchain.com/modules/_langchain_community.tools_google_finance.html).\n", + "\n", + "This tool uses the [SerpApi Google Finance API](https://serpapi.com/google-finance-api), so you will need a [SerpApi API key](https://serpapi.com/dashboard).\n", + "\n", + "## Overview\n", + "\n", + "### Integration details\n", + "\n", + "| Class | Package | [PY support](https://python.langchain.com/docs/integrations/tools/google_finance/) | Package latest |\n", + "| :--- | :--- | :---: | :---: |\n", + "| [`SERPGoogleFinanceAPITool`](https://v03.api.js.langchain.com/modules/_langchain_community.tools_google_finance.html) | [`@langchain/community`](https://www.npmjs.com/package/@langchain/community) | ✅ | ![NPM - Version](https://img.shields.io/npm/v/@langchain/community?style=flat-square&label=%20&) |\n", + "\n", + "## Setup\n", + "\n", + "The integration lives in the `@langchain/community` package.\n", + "\n", + "```{=mdx}\n", + "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n", + "import Npm2Yarn from \"@theme/Npm2Yarn\";\n", + "\n", + "\n", + "\n", + "\n", + " @langchain/community @langchain/core\n", + "\n", + "```\n", + "\n", + "### Credentials\n", + "\n", + "```typescript\n", + "process.env.SERPAPI_API_KEY=\"your-serpapi-api-key\"\n", + "```\n", + "\n", + "It's also helpful (but not needed) to set up [LangSmith](https://smith.langchain.com/) for best-in-class observability:\n", + "\n", + "```typescript\n", + "process.env.LANGCHAIN_TRACING_V2=\"true\"\n", + "process.env.LANGCHAIN_API_KEY=\"your-api-key\"\n", + "```" + ] + }, + { + "cell_type": "markdown", + "id": "1c97218f-f366-479d-8bf7-fe9f2f6df73f", + "metadata": {}, + "source": [ + "## Instantiation\n", + "\n", + "You can import and instantiate an instance of the `SERPGoogleFinanceAPITool` tool like this:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8b3ddfe9-ca79-494c-a7ab-1f56d9407a64", + "metadata": {}, + "outputs": [], + "source": [ + "import { SERPGoogleFinanceAPITool } from \"@langchain/community/tools/google_finance\";\n", + "\n", + "const tool = new SERPGoogleFinanceAPITool({\n", + " // optional, either pass in your api key here or set it as an environment variable\n", + " apiKey: \"your-serpapi-api-key\",\n", + "});" + ] + }, + { + "cell_type": "markdown", + "id": "74147a1a", + "metadata": {}, + "source": [ + "## Invocation\n", + "\n", + "### [Invoke directly with args](/docs/concepts/#invoke-with-just-the-arguments)\n", + "\n", + "The input is a query string for anything you might search for on Google Finance (e.g. GOOG:NASDAQ):" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "65310a8b-eb0c-4d9e-a618-4f4abe2414fc", + "metadata": {}, + "outputs": [], + "source": [ + "await tool.invoke(\"GOOG:NASDAQ\")" + ] + }, + { + "cell_type": "markdown", + "id": "d6e73897", + "metadata": {}, + "source": [ + "### [Invoke with ToolCall](/docs/concepts/#invoke-with-toolcall)\n", + "\n", + "We can also invoke the tool with a model-generated `ToolCall`, in which case a `ToolMessage` will be returned:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f90e33a7", + "metadata": {}, + "outputs": [], + "source": [ + "// This is usually generated by a model, but we'll create a tool call directly for demo purposes.\n", + "const modelGeneratedToolCall = {\n", + " args: {\n", + " input: \"What is the price of GOOG:NASDAQ?\"\n", + " },\n", + " id: \"1\",\n", + " name: tool.name,\n", + " type: \"tool_call\",\n", + "}\n", + "await tool.invoke(modelGeneratedToolCall)" + ] + }, + { + "cell_type": "markdown", + "id": "659f9fbd-6fcf-445f-aa8c-72d8e60154bd", + "metadata": {}, + "source": [ + "## Chaining\n", + "\n", + "We can use our tool in a chain by first binding it to a [tool-calling model](/docs/how_to/tool_calling/) and then calling it:\n", + "\n", + "```{=mdx}\n", + "import ChatModelTabs from \"@theme/ChatModelTabs\";\n", + "\n", + "\n", + "```\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "af3123ad-7a02-40e5-b58e-7d56e23e5830", + "metadata": {}, + "outputs": [], + "source": [ + "// @lc-docs-hide-cell\n", + "\n", + "import { ChatOpenAI } from \"@langchain/openai\"\n", + "\n", + "const llm = new ChatOpenAI({\n", + " model: \"gpt-4o-mini\",\n", + "})" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fdbf35b5-3aaf-4947-9ec6-48c21533fb95", + "metadata": {}, + "outputs": [], + "source": [ + "import { HumanMessage } from \"@langchain/core/messages\";\n", + "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n", + "import { RunnableLambda } from \"@langchain/core/runnables\";\n", + "\n", + "const prompt = ChatPromptTemplate.fromMessages(\n", + " [\n", + " [\"system\", \"You are a helpful assistant.\"],\n", + " [\"placeholder\", \"{messages}\"],\n", + " ]\n", + ")\n", + "\n", + "const llmWithTools = llm.bindTools([tool]);\n", + "\n", + "const chain = prompt.pipe(llmWithTools);\n", + "\n", + "const toolChain = RunnableLambda.from(\n", + " async (userInput: string, config) => {\n", + " const humanMessage = new HumanMessage(userInput,);\n", + " const aiMsg = await chain.invoke({\n", + " messages: [new HumanMessage(userInput)],\n", + " }, config);\n", + " const toolMsgs = await tool.batch(aiMsg.tool_calls, config);\n", + " return chain.invoke({\n", + " messages: [humanMessage, aiMsg, ...toolMsgs],\n", + " }, config);\n", + " }\n", + ");\n", + "\n", + "const toolChainResult = await toolChain.invoke(\"What is the price of GOOG:NASDAQ?\");" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9ac188a2", + "metadata": {}, + "outputs": [], + "source": [ + "const { tool_calls, content } = toolChainResult;\n", + "\n", + "console.log(\"AIMessage\", JSON.stringify({\n", + " tool_calls,\n", + " content,\n", + "}, null, 2));" + ] + }, + { + "cell_type": "markdown", + "id": "93848b02", + "metadata": {}, + "source": [ + "## Agents\n", + "\n", + "For guides on how to use LangChain tools in agents, see the [LangGraph.js](https://langchain-ai.github.io/langgraphjs/) docs." + ] + }, + { + "cell_type": "markdown", + "id": "4ac8146c", + "metadata": {}, + "source": [ + "## API reference\n", + "\n", + "For detailed documentation of all `Google Finance Tool` features and configurations, head to the [API reference](https://v03.api.js.langchain.com/modules/_langchain_community.tools_google_finance.html)." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Deno", + "language": "typescript", + "name": "deno" + }, + "language_info": { + "codemirror_mode": "typescript", + "file_extension": ".ts", + "mimetype": "text/x.typescript", + "name": "typescript", + "nbconvert_exporter": "script", + "pygments_lexer": "typescript", + "version": "5.6.2" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/docs/core_docs/docs/integrations/tools/google_finance.mdx b/docs/core_docs/docs/integrations/tools/google_finance.mdx index ca0d8cfead41..af47a7b48fb4 100644 --- a/docs/core_docs/docs/integrations/tools/google_finance.mdx +++ b/docs/core_docs/docs/integrations/tools/google_finance.mdx @@ -1,33 +1,202 @@ ---- -hide_table_of_contents: true ---- - -import CodeBlock from "@theme/CodeBlock"; - -# Google Finance Tool -The Google Finance Tool allows your agent to utilize the Google Finance API to retrieve financial data, such as stock prices, market trends, -exchange rates, and other investment-related information from Google Finance. - -## Setup -Before using the tool, ensure you have your API key. You can create an account on [SerpAPI](https://serpapi.com/users/sign_in) and obtain your API key -under **Your Private API Key** in your account dashboard. The Google Finance API is included in the free plan offered by SerpAPI. -Once you have the key, set it to the `SERPAPI_API_KEY` environment variable or pass it in as the `apiKey` argument when initializing the tool. - -## Usage - -import IntegrationInstallTooltip from "@mdx_components/integration_install_tooltip.mdx"; - - - -```bash npm2yarn -npm install @langchain/openai @langchain/community @langchain/core -``` - -import ToolExample from "@examples/tools/google_finance.ts"; - -{ToolExample} - -## Related - -- Tool [conceptual guide](/docs/concepts/tools) -- Tool [how-to guides](/docs/how_to/#tools) +--- +sidebar_label: Google Finance Tool +title: Google Finance Tool +--- + +export const quartoRawHtml = [ + ` + ++++++ + + + + + + + + + + + + + + + + +
ClassPackagePY supportPackage latest
SERPGoogleFinanceAPITool@langchain/communityNPM - Version
+`, +]; + +This notebook provides a quick overview for getting started with +[`Google Finance Tool`](../../../docs/integrations/tools/). For detailed +documentation of all `Google Finance Tool` features and configurations +head to the [API +reference](https://v03.api.js.langchain.com/modules/_langchain_community.tools_google_finance.html). + +This tool uses the [SerpApi Google Finance +API](https://serpapi.com/google-finance-api), so you will need a +[SerpApi API key](https://serpapi.com/dashboard). + +## Overview + +### Integration details + +
+ +## Setup + +The integration lives in the `@langchain/community` package. + +```mdx-code-block +import IntegrationInstallTooltip from "@mdx_components/integration_install_tooltip.mdx"; +import Npm2Yarn from "@theme/Npm2Yarn"; + + + + + @langchain/community @langchain/core + +``` + +### Credentials + +```typescript +process.env.SERPAPI_API_KEY = "your-serpapi-api-key"; +``` + +It’s also helpful (but not needed) to set up +[LangSmith](https://smith.langchain.com/) for best-in-class +observability: + +```typescript +process.env.LANGCHAIN_TRACING_V2 = "true"; +process.env.LANGCHAIN_API_KEY = "your-api-key"; +``` + +## Instantiation + +You can import and instantiate an instance of the +`SERPGoogleFinanceAPITool` tool like this: + +```typescript +import { SERPGoogleFinanceAPITool } from "@langchain/community/tools/google_finance"; + +const tool = new SERPGoogleFinanceAPITool({ + // optional, either pass in your api key here or set it as an environment variable + apiKey: "your-serpapi-api-key", +}); +``` + +## Invocation + +### [Invoke directly with args](../../../docs/concepts/#invoke-with-just-the-arguments) + +The input is a query string for anything you might search for on Google +Finance (e.g. GOOG:NASDAQ): + +```typescript +await tool.invoke("GOOG:NASDAQ"); +``` + +### [Invoke with ToolCall](../../../docs/concepts/#invoke-with-toolcall) + +We can also invoke the tool with a model-generated `ToolCall`, in which +case a `ToolMessage` will be returned: + +```typescript +// This is usually generated by a model, but we'll create a tool call directly for demo purposes. +const modelGeneratedToolCall = { + args: { + input: "What is the price of GOOG:NASDAQ?", + }, + id: "1", + name: tool.name, + type: "tool_call", +}; +await tool.invoke(modelGeneratedToolCall); +``` + +## Chaining + +We can use our tool in a chain by first binding it to a [tool-calling +model](../../../docs/how_to/tool_calling/) and then calling it: + +```mdx-code-block +import ChatModelTabs from "@theme/ChatModelTabs"; + + +``` + +```typescript +import { HumanMessage } from "@langchain/core/messages"; +import { ChatPromptTemplate } from "@langchain/core/prompts"; +import { RunnableLambda } from "@langchain/core/runnables"; + +const prompt = ChatPromptTemplate.fromMessages([ + ["system", "You are a helpful assistant."], + ["placeholder", "{messages}"], +]); + +const llmWithTools = llm.bindTools([tool]); + +const chain = prompt.pipe(llmWithTools); + +const toolChain = RunnableLambda.from(async (userInput: string, config) => { + const humanMessage = new HumanMessage(userInput); + const aiMsg = await chain.invoke( + { + messages: [new HumanMessage(userInput)], + }, + config + ); + const toolMsgs = await tool.batch(aiMsg.tool_calls, config); + return chain.invoke( + { + messages: [humanMessage, aiMsg, ...toolMsgs], + }, + config + ); +}); + +const toolChainResult = await toolChain.invoke( + "What is the price of GOOG:NASDAQ?" +); +``` + +```typescript +const { tool_calls, content } = toolChainResult; + +console.log( + "AIMessage", + JSON.stringify( + { + tool_calls, + content, + }, + null, + 2 + ) +); +``` + +## Agents + +For guides on how to use LangChain tools in agents, see the +[LangGraph.js](https://langchain-ai.github.io/langgraphjs/) docs. + +## API reference + +For detailed documentation of all `Google Finance Tool` features and +configurations, head to the [API +reference](https://v03.api.js.langchain.com/modules/_langchain_community.tools_google_finance.html). + + +## Related + +- Tool [conceptual guide](/docs/concepts/#tools) +- Tool [how-to guides](/docs/how_to/#tools)