index
int64 0
0
| repo_id
stringclasses 596
values | file_path
stringlengths 31
168
| content
stringlengths 1
6.2M
|
|---|---|---|---|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/connery.ts
|
import {
AsyncCaller,
AsyncCallerParams,
} from "@langchain/core/utils/async_caller";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { StructuredTool } from "@langchain/core/tools";
import { ZodOptional, ZodString, z } from "zod";
/**
* An object containing configuration parameters for the ConneryService class.
* @extends AsyncCallerParams
*/
export interface ConneryServiceParams extends AsyncCallerParams {
runnerUrl: string;
apiKey: string;
}
type ApiResponse<T> = {
status: "success";
data: T;
};
type ApiErrorResponse = {
status: "error";
error: {
message: string;
};
};
type Parameter = {
key: string;
title: string;
description: string;
type: string;
validation?: {
required?: boolean;
};
};
type Action = {
id: string;
key: string;
title: string;
description: string;
type: string;
inputParameters: Parameter[];
outputParameters: Parameter[];
pluginId: string;
};
type Input = Record<string, string | undefined>;
type Output = Record<string, string>;
type RunActionResult = {
output: Output;
used: {
actionId: string;
input: Input;
};
};
/**
* A LangChain Tool object wrapping a Connery action.
* ConneryAction is a structured tool that can be used only in the agents supporting structured tools.
* @extends StructuredTool
*/
export class ConneryAction extends StructuredTool {
name: string;
description: string;
schema: z.ZodObject<Record<string, ZodString | ZodOptional<ZodString>>>;
/**
* Creates a ConneryAction instance based on the provided Connery Action.
* @param _action The Connery Action.
* @param _service The ConneryService instance.
* @returns A ConneryAction instance.
*/
constructor(protected _action: Action, protected _service: ConneryService) {
super();
this.name = this._action.id;
this.description =
this._action.title +
(this._action.description ? `: ${this._action.description}` : "");
this.schema = this.createInputSchema();
}
/**
* Runs the Connery Action with the provided input.
* @param arg The input object expected by the action.
* @returns A promise that resolves to a JSON string containing the output of the action.
*/
protected _call(arg: z.output<typeof this.schema>): Promise<string> {
return this._service.runAction(this._action.id, arg);
}
/**
* Creates a Zod schema for the input object expected by the Connery action.
* @returns A Zod schema for the input object expected by the Connery action.
*/
protected createInputSchema(): z.ZodObject<
Record<string, ZodString | ZodOptional<ZodString>>
> {
const dynamicInputFields: Record<
string,
ZodString | ZodOptional<ZodString>
> = {};
this._action.inputParameters.forEach((param) => {
const isRequired = param.validation?.required ?? false;
let fieldSchema: ZodString | ZodOptional<ZodString> = z.string();
fieldSchema = isRequired ? fieldSchema : fieldSchema.optional();
const fieldDescription =
param.title + (param.description ? `: ${param.description}` : "");
fieldSchema = fieldSchema.describe(fieldDescription);
dynamicInputFields[param.key] = fieldSchema;
});
return z.object(dynamicInputFields);
}
}
/**
* A service for working with Connery Actions.
*/
export class ConneryService {
protected runnerUrl: string;
protected apiKey: string;
protected asyncCaller: AsyncCaller;
/**
* Creates a ConneryService instance.
* @param params A ConneryServiceParams object.
* If not provided, the values are retrieved from the CONNERY_RUNNER_URL
* and CONNERY_RUNNER_API_KEY environment variables.
* @returns A ConneryService instance.
*/
constructor(params?: ConneryServiceParams) {
const runnerUrl =
params?.runnerUrl ?? getEnvironmentVariable("CONNERY_RUNNER_URL");
const apiKey =
params?.apiKey ?? getEnvironmentVariable("CONNERY_RUNNER_API_KEY");
if (!runnerUrl || !apiKey) {
throw new Error(
"CONNERY_RUNNER_URL and CONNERY_RUNNER_API_KEY environment variables must be set."
);
}
this.runnerUrl = runnerUrl;
this.apiKey = apiKey;
this.asyncCaller = new AsyncCaller(params ?? {});
}
/**
* Returns the list of Connery Actions wrapped as a LangChain StructuredTool objects.
* @returns A promise that resolves to an array of ConneryAction objects.
*/
async listActions(): Promise<ConneryAction[]> {
const actions = await this._listActions();
return actions.map((action) => new ConneryAction(action, this));
}
/**
* Returns the specified Connery action wrapped as a LangChain StructuredTool object.
* @param actionId The ID of the action to return.
* @returns A promise that resolves to a ConneryAction object.
*/
async getAction(actionId: string): Promise<ConneryAction> {
const action = await this._getAction(actionId);
return new ConneryAction(action, this);
}
/**
* Runs the specified Connery action with the provided input.
* @param actionId The ID of the action to run.
* @param input The input object expected by the action.
* @returns A promise that resolves to a JSON string containing the output of the action.
*/
async runAction(actionId: string, input: Input = {}): Promise<string> {
const result = await this._runAction(actionId, input);
return JSON.stringify(result);
}
/**
* Returns the list of actions available in the Connery runner.
* @returns A promise that resolves to an array of Action objects.
*/
protected async _listActions(): Promise<Action[]> {
const response = await this.asyncCaller.call(
fetch,
`${this.runnerUrl}/v1/actions`,
{
method: "GET",
headers: this._getHeaders(),
}
);
await this._handleError(response, "Failed to list actions");
const apiResponse: ApiResponse<Action[]> = await response.json();
return apiResponse.data;
}
/**
* Returns the specified action available in the Connery runner.
* @param actionId The ID of the action to return.
* @returns A promise that resolves to an Action object.
* @throws An error if the action with the specified ID is not found.
*/
protected async _getAction(actionId: string): Promise<Action> {
const actions = await this._listActions();
const action = actions.find((a) => a.id === actionId);
if (!action) {
throw new Error(
`The action with ID "${actionId}" was not found in the list of available actions in the Connery runner.`
);
}
return action;
}
/**
* Runs the specified Connery action with the provided input.
* @param actionId The ID of the action to run.
* @param input The input object expected by the action.
* @returns A promise that resolves to a RunActionResult object.
*/
protected async _runAction(
actionId: string,
input: Input = {}
): Promise<Output> {
const response = await this.asyncCaller.call(
fetch,
`${this.runnerUrl}/v1/actions/${actionId}/run`,
{
method: "POST",
headers: this._getHeaders(),
body: JSON.stringify({
input,
}),
}
);
await this._handleError(response, "Failed to run action");
const apiResponse: ApiResponse<RunActionResult> = await response.json();
return apiResponse.data.output;
}
/**
* Returns a standard set of HTTP headers to be used in API calls to the Connery runner.
* @returns An object containing the standard set of HTTP headers.
*/
protected _getHeaders(): Record<string, string> {
return {
"Content-Type": "application/json",
"x-api-key": this.apiKey,
};
}
/**
* Shared error handler for API calls to the Connery runner.
* If the response is not ok, an error is thrown containing the error message returned by the Connery runner.
* Otherwise, the promise resolves to void.
* @param response The response object returned by the Connery runner.
* @param errorMessage The error message to be used in the error thrown if the response is not ok.
* @returns A promise that resolves to void.
* @throws An error containing the error message returned by the Connery runner.
*/
protected async _handleError(
response: Response,
errorMessage: string
): Promise<void> {
if (response.ok) return;
const apiErrorResponse: ApiErrorResponse = await response.json();
throw new Error(
`${errorMessage}. Status code: ${response.status}. Error message: ${apiErrorResponse.error.message}`
);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/brave_search.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Tool } from "@langchain/core/tools";
/**
* Interface for the parameters required to instantiate a BraveSearch
* instance.
*/
export interface BraveSearchParams {
apiKey?: string;
}
/**
* Class for interacting with the Brave Search engine. It extends the Tool
* class and requires an API key to function. The API key can be passed in
* during instantiation or set as an environment variable named
* 'BRAVE_SEARCH_API_KEY'.
*/
export class BraveSearch extends Tool {
static lc_name() {
return "BraveSearch";
}
name = "brave-search";
description =
"a search engine. useful for when you need to answer questions about current events. input should be a search query.";
apiKey: string;
constructor(
fields: BraveSearchParams = {
apiKey: getEnvironmentVariable("BRAVE_SEARCH_API_KEY"),
}
) {
super();
if (!fields.apiKey) {
throw new Error(
`Brave API key not set. Please pass it in or set it as an environment variable named "BRAVE_SEARCH_API_KEY".`
);
}
this.apiKey = fields.apiKey;
}
/** @ignore */
async _call(input: string): Promise<string> {
const headers = {
"X-Subscription-Token": this.apiKey,
Accept: "application/json",
};
const searchUrl = new URL(
`https://api.search.brave.com/res/v1/web/search?q=${encodeURIComponent(
input
)}`
);
const response = await fetch(searchUrl, { headers });
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
const parsedResponse = await response.json();
const webSearchResults = parsedResponse.web?.results;
const finalResults = Array.isArray(webSearchResults)
? webSearchResults.map(
(item: { title?: string; url?: string; description?: string }) => ({
title: item.title,
link: item.url,
snippet: item.description,
})
)
: [];
return JSON.stringify(finalResults);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/searchapi.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Tool } from "@langchain/core/tools";
type JSONPrimitive = string | number | boolean | null;
type JSONValue = JSONPrimitive | JSONObject | JSONArray;
interface JSONObject {
[key: string]: JSONValue;
}
interface JSONArray extends Array<JSONValue> {}
function isJSONObject(value: JSONValue): value is JSONObject {
return value !== null && typeof value === "object" && !Array.isArray(value);
}
/**
* SearchApiParameters Type Definition.
*
* For more parameters and supported search engines, refer specific engine documentation:
* Google - https://www.searchapi.io/docs/google
* Google News - https://www.searchapi.io/docs/google-news
* Google Scholar - https://www.searchapi.io/docs/google-scholar
* YouTube Transcripts - https://www.searchapi.io/docs/youtube-transcripts
* and others.
*
*/
export type SearchApiParameters = {
[key: string]: JSONValue;
};
/**
* SearchApi Class Definition.
*
* Provides a wrapper around the SearchApi.
*
* Ensure you've set the SEARCHAPI_API_KEY environment variable for authentication.
* You can obtain a free API key from https://www.searchapi.io/.
* @example
* ```typescript
* const searchApi = new SearchApi("your-api-key", {
* engine: "google_news",
* });
* const agent = RunnableSequence.from([
* ChatPromptTemplate.fromMessages([
* ["ai", "Answer the following questions using a bulleted list markdown format.""],
* ["human", "{input}"],
* ]),
* new ChatOpenAI({ temperature: 0 }),
* (input: BaseMessageChunk) => ({
* log: "test",
* returnValues: {
* output: input,
* },
* }),
* ]);
* const executor = AgentExecutor.fromAgentAndTools({
* agent,
* tools: [searchApi],
* });
* const res = await executor.invoke({
* input: "What's happening in Ukraine today?"",
* });
* console.log(res);
* ```
*/
export class SearchApi extends Tool {
static lc_name() {
return "SearchApi";
}
/**
* Converts the SearchApi instance to JSON. This method is not implemented
* and will throw an error if called.
* @returns Throws an error.
*/
toJSON() {
return this.toJSONNotImplemented();
}
protected apiKey: string;
protected params: Partial<SearchApiParameters>;
constructor(
apiKey: string | undefined = getEnvironmentVariable("SEARCHAPI_API_KEY"),
params: Partial<SearchApiParameters> = {}
) {
super(...arguments);
if (!apiKey) {
throw new Error(
"SearchApi requires an API key. Please set it as SEARCHAPI_API_KEY in your .env file, or pass it as a parameter to the SearchApi constructor."
);
}
this.apiKey = apiKey;
this.params = params;
}
name = "search";
/**
* Builds a URL for the SearchApi request.
* @param parameters The parameters for the request.
* @returns A string representing the built URL.
*/
protected buildUrl(searchQuery: string): string {
const preparedParams: [string, string][] = Object.entries({
engine: "google",
api_key: this.apiKey,
...this.params,
q: searchQuery,
})
.filter(
([key, value]) =>
value !== undefined && value !== null && key !== "apiKey"
)
.map(([key, value]) => [key, `${value}`]);
const searchParams = new URLSearchParams(preparedParams);
return `https://www.searchapi.io/api/v1/search?${searchParams}`;
}
/** @ignore */
/**
* Calls the SearchAPI.
*
* Accepts an input query and fetches the result from SearchApi.
*
* @param {string} input - Search query.
* @returns {string} - Formatted search results or an error message.
*
* NOTE: This method is the core search handler and processes various types
* of search results including Google organic results, videos, jobs, and images.
*/
async _call(input: string) {
const resp = await fetch(this.buildUrl(input));
const json = await resp.json();
if (json.error) {
throw new Error(
`Failed to load search results from SearchApi due to: ${json.error}`
);
}
// Google Search results
if (json.answer_box?.answer) {
return json.answer_box.answer;
}
if (json.answer_box?.snippet) {
return json.answer_box.snippet;
}
if (json.knowledge_graph?.description) {
return json.knowledge_graph.description;
}
// Organic results (Google, Google News)
if (json.organic_results) {
const snippets = json.organic_results
.filter((r: JSONObject) => r.snippet)
.map((r: JSONObject) => r.snippet);
return snippets.join("\n");
}
// Google Jobs results
if (json.jobs) {
const jobDescriptions = json.jobs
.slice(0, 1)
.filter((r: JSONObject) => r.description)
.map((r: JSONObject) => r.description);
return jobDescriptions.join("\n");
}
// Google Videos results
if (json.videos) {
const videoInfo = json.videos
.filter((r: JSONObject) => r.title && r.link)
.map((r: JSONObject) => `Title: "${r.title}" Link: ${r.link}`);
return videoInfo.join("\n");
}
// Google Images results
if (json.images) {
const image_results = json.images.slice(0, 15);
const imageInfo = image_results
.filter(
(r: JSONObject) =>
r.title && r.original && isJSONObject(r.original) && r.original.link
)
.map(
(r: JSONObject) =>
`Title: "${r.title}" Link: ${(r.original as JSONObject).link}`
);
return imageInfo.join("\n");
}
return "No good search result found";
}
description =
"a search engine. useful for when you need to answer questions about current events. input should be a search query.";
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/aiplugin.ts
|
import { Tool, type ToolParams } from "@langchain/core/tools";
/**
* Interface for parameters required to create an instance of
* AIPluginTool.
*/
export interface AIPluginToolParams extends ToolParams {
name: string;
description: string;
apiSpec: string;
}
/**
* Class for creating instances of AI tools from plugins. It extends the
* Tool class and implements the AIPluginToolParams interface.
*/
export class AIPluginTool extends Tool implements AIPluginToolParams {
static lc_name() {
return "AIPluginTool";
}
private _name: string;
private _description: string;
apiSpec: string;
get name() {
return this._name;
}
get description() {
return this._description;
}
constructor(params: AIPluginToolParams) {
super(params);
this._name = params.name;
this._description = params.description;
this.apiSpec = params.apiSpec;
}
/** @ignore */
async _call(_input: string) {
return this.apiSpec;
}
/**
* Static method that creates an instance of AIPluginTool from a given
* plugin URL. It fetches the plugin and its API specification from the
* provided URL and returns a new instance of AIPluginTool with the
* fetched data.
* @param url The URL of the AI plugin.
* @returns A new instance of AIPluginTool.
*/
static async fromPluginUrl(url: string) {
const aiPluginRes = await fetch(url);
if (!aiPluginRes.ok) {
throw new Error(
`Failed to fetch plugin from ${url} with status ${aiPluginRes.status}`
);
}
const aiPluginJson = await aiPluginRes.json();
const apiUrlRes = await fetch(aiPluginJson.api.url);
if (!apiUrlRes.ok) {
throw new Error(
`Failed to fetch API spec from ${aiPluginJson.api.url} with status ${apiUrlRes.status}`
);
}
const apiUrlJson = await apiUrlRes.text();
return new AIPluginTool({
name: aiPluginJson.name_for_model,
description: `Call this tool to get the OpenAPI spec (and usage guide) for interacting with the ${aiPluginJson.name_for_human} API. You should only call this ONCE! What is the ${aiPluginJson.name_for_human} API useful for? ${aiPluginJson.description_for_human}`,
apiSpec: `Usage Guide: ${aiPluginJson.description_for_model}
OpenAPI Spec in JSON or YAML format:\n${apiUrlJson}`,
});
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/wikipedia_query_run.ts
|
import { Tool } from "@langchain/core/tools";
/**
* Interface for the parameters that can be passed to the
* WikipediaQueryRun constructor.
*/
export interface WikipediaQueryRunParams {
topKResults?: number;
maxDocContentLength?: number;
baseUrl?: string;
}
/**
* Type alias for URL parameters. Represents a record where keys are
* strings and values can be string, number, boolean, undefined, or null.
*/
type UrlParameters = Record<
string,
string | number | boolean | undefined | null
>;
/**
* Interface for the structure of search results returned by the Wikipedia
* API.
*/
interface SearchResults {
query: {
search: Array<{
title: string;
}>;
};
}
/**
* Interface for the structure of a page returned by the Wikipedia API.
*/
interface Page {
pageid: number;
ns: number;
title: string;
extract: string;
}
/**
* Interface for the structure of a page result returned by the Wikipedia
* API.
*/
interface PageResult {
batchcomplete: string;
query: {
pages: Record<string, Page>;
};
}
/**
* Wikipedia query tool integration.
*
* Setup:
* Install `@langchain/community`. You'll also need an API key.
*
* ```bash
* npm install @langchain/community
* ```
*
* ## [Constructor args](https://api.js.langchain.com/classes/_langchain_community.tools_wikipedia_query_run.WikipediaQueryRun.html#constructor)
*
* <details open>
* <summary><strong>Instantiate</strong></summary>
*
* ```typescript
* import { WikipediaQueryRun } from "@langchain/community/tools/wikipedia_query_run";
*
* const tool = new WikipediaQueryRun({
* topKResults: 3,
* maxDocContentLength: 4000,
* });
* ```
* </details>
*
* <br />
*
* <details>
*
* <summary><strong>Invocation</strong></summary>
*
* ```typescript
* await tool.invoke("what is the current weather in sf?");
* ```
* </details>
*
* <br />
*
* <details>
*
* <summary><strong>Invocation with tool call</strong></summary>
*
* ```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 current weather in sf?",
* },
* id: "tool_call_id",
* name: tool.name,
* type: "tool_call",
* };
* await tool.invoke(modelGeneratedToolCall);
* ```
*
* ```text
* ToolMessage {
* "content": "...",
* "name": "wikipedia-api",
* "additional_kwargs": {},
* "response_metadata": {},
* "tool_call_id": "tool_call_id"
* }
* ```
* </details>
*/
export class WikipediaQueryRun extends Tool {
static lc_name() {
return "WikipediaQueryRun";
}
name = "wikipedia-api";
description =
"A tool for interacting with and fetching data from the Wikipedia API.";
protected topKResults = 3;
protected maxDocContentLength = 4000;
protected baseUrl = "https://en.wikipedia.org/w/api.php";
constructor(params: WikipediaQueryRunParams = {}) {
super();
this.topKResults = params.topKResults ?? this.topKResults;
this.maxDocContentLength =
params.maxDocContentLength ?? this.maxDocContentLength;
this.baseUrl = params.baseUrl ?? this.baseUrl;
}
async _call(query: string): Promise<string> {
const searchResults = await this._fetchSearchResults(query);
const summaries: string[] = [];
for (
let i = 0;
i < Math.min(this.topKResults, searchResults.query.search.length);
i += 1
) {
const page = searchResults.query.search[i].title;
const pageDetails = await this._fetchPage(page, true);
if (pageDetails) {
const summary = `Page: ${page}\nSummary: ${pageDetails.extract}`;
summaries.push(summary);
}
}
if (summaries.length === 0) {
return "No good Wikipedia Search Result was found";
} else {
return summaries.join("\n\n").slice(0, this.maxDocContentLength);
}
}
/**
* Fetches the content of a specific Wikipedia page. It returns the
* extracted content as a string.
* @param page The specific Wikipedia page to fetch its content.
* @param redirect A boolean value to indicate whether to redirect or not.
* @returns The extracted content of the specific Wikipedia page as a string.
*/
public async content(page: string, redirect = true): Promise<string> {
try {
const result = await this._fetchPage(page, redirect);
return result.extract;
} catch (error) {
throw new Error(`Failed to fetch content for page "${page}": ${error}`);
}
}
/**
* Builds a URL for the Wikipedia API using the provided parameters.
* @param parameters The parameters to be used in building the URL.
* @returns A string representing the built URL.
*/
protected buildUrl<P extends UrlParameters>(parameters: P): string {
const nonUndefinedParams: [string, string][] = Object.entries(parameters)
.filter(([_, value]) => value !== undefined)
.map(([key, value]) => [key, `${value}`]);
const searchParams = new URLSearchParams(nonUndefinedParams);
return `${this.baseUrl}?${searchParams}`;
}
private async _fetchSearchResults(query: string): Promise<SearchResults> {
const searchParams = new URLSearchParams({
action: "query",
list: "search",
srsearch: query,
format: "json",
});
const response = await fetch(`${this.baseUrl}?${searchParams.toString()}`);
if (!response.ok) throw new Error("Network response was not ok");
const data: SearchResults = await response.json();
return data;
}
private async _fetchPage(page: string, redirect: boolean): Promise<Page> {
const params = new URLSearchParams({
action: "query",
prop: "extracts",
explaintext: "true",
redirects: redirect ? "1" : "0",
format: "json",
titles: page,
});
const response = await fetch(`${this.baseUrl}?${params.toString()}`);
if (!response.ok) throw new Error("Network response was not ok");
const data: PageResult = await response.json();
const { pages } = data.query;
const pageId = Object.keys(pages)[0];
return pages[pageId];
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/serper.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Tool } from "@langchain/core/tools";
/**
* Defines the parameters that can be passed to the Serper class during
* instantiation. It includes `gl` and `hl` which are optional.
*/
export type SerperParameters = {
gl?: string;
hl?: string;
};
/**
* Wrapper around serper.
*
* You can create a free API key at https://serper.dev.
*
* To use, you should have the SERPER_API_KEY environment variable set.
*/
export class Serper extends Tool {
static lc_name() {
return "Serper";
}
/**
* Converts the Serper instance to JSON. This method is not implemented
* and will throw an error if called.
* @returns Throws an error.
*/
toJSON() {
return this.toJSONNotImplemented();
}
protected key: string;
protected params: Partial<SerperParameters>;
constructor(
apiKey: string | undefined = getEnvironmentVariable("SERPER_API_KEY"),
params: Partial<SerperParameters> = {}
) {
super();
if (!apiKey) {
throw new Error(
"Serper API key not set. You can set it as SERPER_API_KEY in your .env file, or pass it to Serper."
);
}
this.key = apiKey;
this.params = params;
}
name = "search";
/** @ignore */
async _call(input: string) {
const options = {
method: "POST",
headers: {
"X-API-KEY": this.key,
"Content-Type": "application/json",
},
body: JSON.stringify({
q: input,
...this.params,
}),
};
const res = await fetch("https://google.serper.dev/search", options);
if (!res.ok) {
throw new Error(`Got ${res.status} error from serper: ${res.statusText}`);
}
const json = await res.json();
if (json.answerBox?.answer) {
return json.answerBox.answer;
}
if (json.answerBox?.snippet) {
return json.answerBox.snippet;
}
if (json.answerBox?.snippet_highlighted_words) {
return json.answerBox.snippet_highlighted_words[0];
}
if (json.sportsResults?.game_spotlight) {
return json.sportsResults.game_spotlight;
}
if (json.knowledgeGraph?.description) {
return json.knowledgeGraph.description;
}
if (json.organic?.[0]?.snippet) {
return json.organic[0].snippet;
}
return "No good search result found";
}
description =
"a search engine. useful for when you need to answer questions about current events. input should be a search query.";
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/dadjokeapi.ts
|
import { Tool } from "@langchain/core/tools";
/**
* The DadJokeAPI class is a tool for generating dad jokes based on a
* specific topic. It fetches jokes from an external API and returns a
* random joke from the results. If no jokes are found for the given
* search term, it returns a message indicating that no jokes were found.
*/
class DadJokeAPI extends Tool {
static lc_name() {
return "DadJokeAPI";
}
name = "dadjoke";
description =
"a dad joke generator. get a dad joke about a specific topic. input should be a search term.";
/** @ignore */
async _call(input: string): Promise<string> {
const headers = { Accept: "application/json" };
const searchUrl = `https://icanhazdadjoke.com/search?term=${input}`;
const response = await fetch(searchUrl, { headers });
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
const data = await response.json();
const jokes = data.results;
if (jokes.length === 0) {
return `No dad jokes found about ${input}`;
}
const randomIndex = Math.floor(Math.random() * jokes.length);
const randomJoke = jokes[randomIndex].joke;
return randomJoke;
}
}
export { DadJokeAPI };
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/wolframalpha.ts
|
import { Tool, type ToolParams } from "@langchain/core/tools";
/**
* @example
* ```typescript
* const tool = new WolframAlphaTool({
* appid: "YOUR_APP_ID",
* });
* const res = await tool.invoke("What is 2 * 2?");
* ```
*/
export class WolframAlphaTool extends Tool {
appid: string;
name = "wolfram_alpha";
description = `A wrapper around Wolfram Alpha. Useful for when you need to answer questions about Math, Science, Technology, Culture, Society and Everyday Life. Input should be a search query.`;
constructor(fields: ToolParams & { appid: string }) {
super(fields);
this.appid = fields.appid;
}
static lc_name() {
return "WolframAlphaTool";
}
async _call(query: string): Promise<string> {
const url = `https://www.wolframalpha.com/api/v1/llm-api?appid=${
this.appid
}&input=${encodeURIComponent(query)}`;
const res = await fetch(url);
return res.text();
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/serpapi.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Tool } from "@langchain/core/tools";
/**
* This does not use the `serpapi` package because it appears to cause issues
* when used in `jest` tests. Part of the issue seems to be that the `serpapi`
* package imports a wasm module to use instead of native `fetch`, which we
* don't want anyway.
*
* NOTE: you must provide location, gl and hl or your region and language will
* may not match your location, and will not be deterministic.
*/
// Copied over from `serpapi` package
interface BaseParameters {
/**
* Parameter defines the device to use to get the results. It can be set to
* `desktop` (default) to use a regular browser, `tablet` to use a tablet browser
* (currently using iPads), or `mobile` to use a mobile browser (currently
* using iPhones).
*/
device?: "desktop" | "tablet" | "mobile";
/**
* Parameter will force SerpApi to fetch the Google results even if a cached
* version is already present. A cache is served only if the query and all
* parameters are exactly the same. Cache expires after 1h. Cached searches
* are free, and are not counted towards your searches per month. It can be set
* to `false` (default) to allow results from the cache, or `true` to disallow
* results from the cache. `no_cache` and `async` parameters should not be used together.
*/
no_cache?: boolean;
/**
* Specify the client-side timeout of the request. In milliseconds.
*/
timeout?: number;
}
export interface SerpAPIParameters extends BaseParameters {
/**
* Search Query
* Parameter defines the query you want to search. You can use anything that you
* would use in a regular Google search. e.g. `inurl:`, `site:`, `intitle:`. We
* also support advanced search query parameters such as as_dt and as_eq. See the
* [full list](https://serpapi.com/advanced-google-query-parameters) of supported
* advanced search query parameters.
*/
q: string;
/**
* Location
* Parameter defines from where you want the search to originate. If several
* locations match the location requested, we'll pick the most popular one. Head to
* [/locations.json API](https://serpapi.com/locations-api) if you need more
* precise control. location and uule parameters can't be used together. Avoid
* utilizing location when setting the location outside the U.S. when using Google
* Shopping and/or Google Product API.
*/
location?: string;
/**
* Encoded Location
* Parameter is the Google encoded location you want to use for the search. uule
* and location parameters can't be used together.
*/
uule?: string;
/**
* Google Place ID
* Parameter defines the id (`CID`) of the Google My Business listing you want to
* scrape. Also known as Google Place ID.
*/
ludocid?: string;
/**
* Additional Google Place ID
* Parameter that you might have to use to force the knowledge graph map view to
* show up. You can find the lsig ID by using our [Local Pack
* API](https://serpapi.com/local-pack) or [Local Places Results
* API](https://serpapi.com/local-results).
* lsig ID is also available via a redirect Google uses within [Google My
* Business](https://www.google.com/business/).
*/
lsig?: string;
/**
* Google Knowledge Graph ID
* Parameter defines the id (`KGMID`) of the Google Knowledge Graph listing you
* want to scrape. Also known as Google Knowledge Graph ID. Searches with kgmid
* parameter will return results for the originally encrypted search parameters.
* For some searches, kgmid may override all other parameters except start, and num
* parameters.
*/
kgmid?: string;
/**
* Google Cached Search Parameters ID
* Parameter defines the cached search parameters of the Google Search you want to
* scrape. Searches with si parameter will return results for the originally
* encrypted search parameters. For some searches, si may override all other
* parameters except start, and num parameters. si can be used to scrape Google
* Knowledge Graph Tabs.
*/
si?: string;
/**
* Domain
* Parameter defines the Google domain to use. It defaults to `google.com`. Head to
* the [Google domains page](https://serpapi.com/google-domains) for a full list of
* supported Google domains.
*/
google_domain?: string;
/**
* Country
* Parameter defines the country to use for the Google search. It's a two-letter
* country code. (e.g., `us` for the United States, `uk` for United Kingdom, or
* `fr` for France). Head to the [Google countries
* page](https://serpapi.com/google-countries) for a full list of supported Google
* countries.
*/
gl?: string;
/**
* Language
* Parameter defines the language to use for the Google search. It's a two-letter
* language code. (e.g., `en` for English, `es` for Spanish, or `fr` for French).
* Head to the [Google languages page](https://serpapi.com/google-languages) for a
* full list of supported Google languages.
*/
hl?: string;
/**
* Set Multiple Languages
* Parameter defines one or multiple languages to limit the search to. It uses
* `lang_{two-letter language code}` to specify languages and `|` as a delimiter.
* (e.g., `lang_fr|lang_de` will only search French and German pages). Head to the
* [Google lr languages page](https://serpapi.com/google-lr-languages) for a full
* list of supported languages.
*/
lr?: string;
/**
* as_dt
* Parameter controls whether to include or exclude results from the site named in
* the as_sitesearch parameter.
*/
as_dt?: string;
/**
* as_epq
* Parameter identifies a phrase that all documents in the search results must
* contain. You can also use the [phrase
* search](https://developers.google.com/custom-search/docs/xml_results#PhraseSearchqt)
* query term to search for a phrase.
*/
as_epq?: string;
/**
* as_eq
* Parameter identifies a word or phrase that should not appear in any documents in
* the search results. You can also use the [exclude
* query](https://developers.google.com/custom-search/docs/xml_results#Excludeqt)
* term to ensure that a particular word or phrase will not appear in the documents
* in a set of search results.
*/
as_eq?: string;
/**
* as_lq
* Parameter specifies that all search results should contain a link to a
* particular URL. You can also use the
* [link:](https://developers.google.com/custom-search/docs/xml_results#BackLinksqt)
* query term for this type of query.
*/
as_lq?: string;
/**
* as_nlo
* Parameter specifies the starting value for a search range. Use as_nlo and as_nhi
* to append an inclusive search range.
*/
as_nlo?: string;
/**
* as_nhi
* Parameter specifies the ending value for a search range. Use as_nlo and as_nhi
* to append an inclusive search range.
*/
as_nhi?: string;
/**
* as_oq
* Parameter provides additional search terms to check for in a document, where
* each document in the search results must contain at least one of the additional
* search terms. You can also use the [Boolean
* OR](https://developers.google.com/custom-search/docs/xml_results#BooleanOrqt)
* query term for this type of query.
*/
as_oq?: string;
/**
* as_q
* Parameter provides search terms to check for in a document. This parameter is
* also commonly used to allow users to specify additional terms to search for
* within a set of search results.
*/
as_q?: string;
/**
* as_qdr
* Parameter requests search results from a specified time period (quick date
* range). The following values are supported:
* `d[number]`: requests results from the specified number of past days. Example
* for the past 10 days: `as_qdr=d10`
* `w[number]`: requests results from the specified number of past weeks.
* `m[number]`: requests results from the specified number of past months.
* `y[number]`: requests results from the specified number of past years. Example
* for the past year: `as_qdr=y`
*/
as_qdr?: string;
/**
* as_rq
* Parameter specifies that all search results should be pages that are related to
* the specified URL. The parameter value should be a URL. You can also use the
* [related:](https://developers.google.com/custom-search/docs/xml_results#RelatedLinksqt)
* query term for this type of query.
*/
as_rq?: string;
/**
* as_sitesearch
* Parameter allows you to specify that all search results should be pages from a
* given site. By setting the as_dt parameter, you can also use it to exclude pages
* from a given site from your search resutls.
*/
as_sitesearch?: string;
/**
* Advanced Search Parameters
* (to be searched) parameter defines advanced search parameters that aren't
* possible in the regular query field. (e.g., advanced search for patents, dates,
* news, videos, images, apps, or text contents).
*/
tbs?: string;
/**
* Adult Content Filtering
* Parameter defines the level of filtering for adult content. It can be set to
* `active`, or `off` (default).
*/
safe?: string;
/**
* Exclude Auto-corrected Results
* Parameter defines the exclusion of results from an auto-corrected query that is
* spelled wrong. It can be set to `1` to exclude these results, or `0` to include
* them (default).
*/
nfpr?: string;
/**
* Results Filtering
* Parameter defines if the filters for 'Similar Results' and 'Omitted Results' are
* on or off. It can be set to `1` (default) to enable these filters, or `0` to
* disable these filters.
*/
filter?: string;
/**
* Search Type
* (to be matched) parameter defines the type of search you want to do.
* It can be set to:
* `(no tbm parameter)`: regular Google Search,
* `isch`: [Google Images API](https://serpapi.com/images-results),
* `lcl` - [Google Local API](https://serpapi.com/local-results)
* `vid`: [Google Videos API](https://serpapi.com/videos-results),
* `nws`: [Google News API](https://serpapi.com/news-results),
* `shop`: [Google Shopping API](https://serpapi.com/shopping-results),
* or any other Google service.
*/
tbm?: string;
/**
* Result Offset
* Parameter defines the result offset. It skips the given number of results. It's
* used for pagination. (e.g., `0` (default) is the first page of results, `10` is
* the 2nd page of results, `20` is the 3rd page of results, etc.).
* Google Local Results only accepts multiples of `20`(e.g. `20` for the second
* page results, `40` for the third page results, etc.) as the start value.
*/
start?: number;
/**
* Number of Results
* Parameter defines the maximum number of results to return. (e.g., `10` (default)
* returns 10 results, `40` returns 40 results, and `100` returns 100 results).
*/
num?: string;
/**
* Page Number (images)
* Parameter defines the page number for [Google
* Images](https://serpapi.com/images-results). There are 100 images per page. This
* parameter is equivalent to start (offset) = ijn * 100. This parameter works only
* for [Google Images](https://serpapi.com/images-results) (set tbm to `isch`).
*/
ijn?: string;
}
type UrlParameters = Record<
string,
string | number | boolean | undefined | null
>;
/**
* Wrapper around SerpAPI.
*
* To use, you should have the `serpapi` package installed and the SERPAPI_API_KEY environment variable set.
*/
export class SerpAPI extends Tool {
static lc_name() {
return "SerpAPI";
}
toJSON() {
return this.toJSONNotImplemented();
}
protected key: string;
protected params: Partial<SerpAPIParameters>;
protected baseUrl: string;
constructor(
apiKey: string | undefined = getEnvironmentVariable("SERPAPI_API_KEY"),
params: Partial<SerpAPIParameters> = {},
baseUrl = "https://serpapi.com"
) {
super(...arguments);
if (!apiKey) {
throw new Error(
"SerpAPI API key not set. You can set it as SERPAPI_API_KEY in your .env file, or pass it to SerpAPI."
);
}
this.key = apiKey;
this.params = params;
this.baseUrl = baseUrl;
}
name = "search";
/**
* Builds a URL for the SerpAPI request.
* @param path The path for the request.
* @param parameters The parameters for the request.
* @param baseUrl The base URL for the request.
* @returns A string representing the built URL.
*/
protected buildUrl<P extends UrlParameters>(
path: string,
parameters: P,
baseUrl: string
): string {
const nonUndefinedParams: [string, string][] = Object.entries(parameters)
.filter(([_, value]) => value !== undefined)
.map(([key, value]) => [key, `${value}`]);
const searchParams = new URLSearchParams(nonUndefinedParams);
return `${baseUrl}/${path}?${searchParams}`;
}
/** @ignore */
async _call(input: string) {
const { timeout, ...params } = this.params;
const resp = await fetch(
this.buildUrl(
"search",
{
...params,
api_key: this.key,
q: input,
},
this.baseUrl
),
{
signal: timeout ? AbortSignal.timeout(timeout) : undefined,
}
);
const res = await resp.json();
if (res.error) {
throw new Error(`Got error from serpAPI: ${res.error}`);
}
const answer_box = res.answer_box_list
? res.answer_box_list[0]
: res.answer_box;
if (answer_box) {
if (answer_box.result) {
return answer_box.result;
} else if (answer_box.answer) {
return answer_box.answer;
} else if (answer_box.snippet) {
return answer_box.snippet;
} else if (answer_box.snippet_highlighted_words) {
return answer_box.snippet_highlighted_words.toString();
} else {
const answer: { [key: string]: string } = {};
Object.keys(answer_box)
.filter(
(k) =>
!Array.isArray(answer_box[k]) &&
typeof answer_box[k] !== "object" &&
!(
typeof answer_box[k] === "string" &&
answer_box[k].startsWith("http")
)
)
.forEach((k) => {
answer[k] = answer_box[k];
});
return JSON.stringify(answer);
}
}
if (res.events_results) {
return JSON.stringify(res.events_results);
}
if (res.sports_results) {
return JSON.stringify(res.sports_results);
}
if (res.top_stories) {
return JSON.stringify(res.top_stories);
}
if (res.news_results) {
return JSON.stringify(res.news_results);
}
if (res.jobs_results?.jobs) {
return JSON.stringify(res.jobs_results.jobs);
}
if (res.questions_and_answers) {
return JSON.stringify(res.questions_and_answers);
}
if (res.popular_destinations?.destinations) {
return JSON.stringify(res.popular_destinations.destinations);
}
if (res.top_sights?.sights) {
const sights: Array<{ [key: string]: string }> = res.top_sights.sights
.map((s: { [key: string]: string }) => ({
title: s.title,
description: s.description,
price: s.price,
}))
.slice(0, 8);
return JSON.stringify(sights);
}
if (res.shopping_results && res.shopping_results[0]?.title) {
return JSON.stringify(res.shopping_results.slice(0, 3));
}
if (res.images_results && res.images_results[0]?.thumbnail) {
return res.images_results
.map((ir: { thumbnail: string }) => ir.thumbnail)
.slice(0, 10)
.toString();
}
const snippets = [];
if (res.knowledge_graph) {
if (res.knowledge_graph.description) {
snippets.push(res.knowledge_graph.description);
}
const title = res.knowledge_graph.title || "";
Object.keys(res.knowledge_graph)
.filter(
(k) =>
typeof res.knowledge_graph[k] === "string" &&
k !== "title" &&
k !== "description" &&
!k.endsWith("_stick") &&
!k.endsWith("_link") &&
!k.startsWith("http")
)
.forEach((k) =>
snippets.push(`${title} ${k}: ${res.knowledge_graph[k]}`)
);
}
const first_organic_result = res.organic_results?.[0];
if (first_organic_result) {
if (first_organic_result.snippet) {
snippets.push(first_organic_result.snippet);
} else if (first_organic_result.snippet_highlighted_words) {
snippets.push(first_organic_result.snippet_highlighted_words);
} else if (first_organic_result.rich_snippet) {
snippets.push(first_organic_result.rich_snippet);
} else if (first_organic_result.rich_snippet_table) {
snippets.push(first_organic_result.rich_snippet_table);
} else if (first_organic_result.link) {
snippets.push(first_organic_result.link);
}
}
if (res.buying_guide) {
snippets.push(res.buying_guide);
}
if (res.local_results?.places) {
snippets.push(res.local_results.places);
}
if (snippets.length > 0) {
return JSON.stringify(snippets);
} else {
return "No good search result found";
}
}
description =
"a search engine. useful for when you need to answer questions about current events. input should be a search query.";
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/discord.ts
|
import {
Client,
TextChannel,
GatewayIntentBits,
Message,
ChannelType,
} from "discord.js";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Tool } from "@langchain/core/tools";
/**
* Base tool parameters for the Discord tools
*/
interface DiscordToolParams {
botToken?: string;
client?: Client;
}
/**
* Tool parameters for the DiscordGetMessagesTool
*/
interface DiscordGetMessagesToolParams extends DiscordToolParams {
messageLimit?: number;
}
/**
* Tool parameters for the DiscordSendMessageTool
*/
interface DiscordSendMessageToolParams extends DiscordToolParams {
channelId?: string;
}
/**
* Tool parameters for the DiscordChannelSearch
*/
interface DiscordChannelSearchParams extends DiscordToolParams {
channelId?: string;
}
/**
* A tool for retrieving messages from a discord channel using a bot.
* It extends the base Tool class and implements the _call method to
* perform the retrieve operation. Requires an bot token which can be set
* in the environment variables, and a limit on how many messages to retrieve.
* The _call method takes the discord channel ID as the input argument.
* The bot must have read permissions to the given channel. It returns the
* message content, author, and time the message was created for each message.
*/
export class DiscordGetMessagesTool extends Tool {
static lc_name() {
return "DiscordGetMessagesTool";
}
name = "discord-get-messages";
description = `A discord tool. useful for reading messages from a discord channel.
Input should be the discord channel ID. The bot should have read
permissions for the channel.`;
protected botToken: string;
protected messageLimit: number;
protected client: Client;
constructor(fields?: DiscordGetMessagesToolParams) {
super();
const {
botToken = getEnvironmentVariable("DISCORD_BOT_TOKEN"),
messageLimit = 10,
client,
} = fields ?? {};
if (!botToken) {
throw new Error(
"Environment variable DISCORD_BOT_TOKEN missing, but is required for DiscordGetMessagesTool."
);
}
this.client =
client ??
new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
});
this.botToken = botToken;
this.messageLimit = messageLimit;
}
/** @ignore */
async _call(input: string): Promise<string> {
try {
await this.client.login(this.botToken);
const channel = (await this.client.channels.fetch(input)) as TextChannel;
if (!channel) {
return "Channel not found.";
}
const messages = await channel.messages.fetch({
limit: this.messageLimit,
});
await this.client.destroy();
const results =
messages.map((message: Message) => ({
author: message.author.tag,
content: message.content,
timestamp: message.createdAt,
})) ?? [];
return JSON.stringify(results);
} catch (err) {
await this.client.destroy();
return "Error getting messages.";
}
}
}
/**
* A tool for retrieving all servers a bot is a member of. It extends the
* base `Tool` class and implements the `_call` method to perform the retrieve
* operation. Requires a bot token which can be set in the environment
* variables.
*/
export class DiscordGetGuildsTool extends Tool {
static lc_name() {
return "DiscordGetGuildsTool";
}
name = "discord-get-guilds";
description = `A discord tool. Useful for getting a list of all servers/guilds the bot is a member of. No input required.`;
protected botToken: string;
protected client: Client;
constructor(fields?: DiscordToolParams) {
super();
const { botToken = getEnvironmentVariable("DISCORD_BOT_TOKEN"), client } =
fields ?? {};
if (!botToken) {
throw new Error(
"Environment variable DISCORD_BOT_TOKEN missing, but is required for DiscordGetGuildsTool."
);
}
this.client =
client ??
new Client({
intents: [GatewayIntentBits.Guilds],
});
this.botToken = botToken;
}
/** @ignore */
async _call(_input: string): Promise<string> {
try {
await this.client.login(this.botToken);
const guilds = await this.client.guilds.fetch();
await this.client.destroy();
const results =
guilds.map((guild) => ({
id: guild.id,
name: guild.name,
createdAt: guild.createdAt,
})) ?? [];
return JSON.stringify(results);
} catch (err) {
await this.client.destroy();
return "Error getting guilds.";
}
}
}
/**
* A tool for retrieving text channels within a server/guild a bot is a member
* of. It extends the base `Tool` class and implements the `_call` method to
* perform the retrieve operation. Requires a bot token which can be set in
* the environment variables. The `_call` method takes a server/guild ID
* to get its text channels.
*/
export class DiscordGetTextChannelsTool extends Tool {
static lc_name() {
return "DiscordGetTextChannelsTool";
}
name = "discord-get-text-channels";
description = `A discord tool. Useful for getting a list of all text channels in a server/guild. Input should be a discord server/guild ID.`;
protected botToken: string;
protected client: Client;
constructor(fields?: DiscordToolParams) {
super();
const { botToken = getEnvironmentVariable("DISCORD_BOT_TOKEN"), client } =
fields ?? {};
if (!botToken) {
throw new Error(
"Environment variable DISCORD_BOT_TOKEN missing, but is required for DiscordGetTextChannelsTool."
);
}
this.client =
client ??
new Client({
intents: [GatewayIntentBits.Guilds],
});
this.botToken = botToken;
}
/** @ignore */
async _call(input: string): Promise<string> {
try {
await this.client.login(this.botToken);
const guild = await this.client.guilds.fetch(input);
const channels = await guild.channels.fetch();
await this.client.destroy();
const results =
channels
.filter((channel) => channel?.type === ChannelType.GuildText)
.map((channel) => ({
id: channel?.id,
name: channel?.name,
createdAt: channel?.createdAt,
})) ?? [];
return JSON.stringify(results);
} catch (err) {
await this.client.destroy();
return "Error getting text channels.";
}
}
}
/**
* A tool for sending messages to a discord channel using a bot.
* It extends the base Tool class and implements the _call method to
* perform the retrieve operation. Requires a bot token and channelId which can be set
* in the environment variables. The _call method takes the message to be
* sent as the input argument.
*/
export class DiscordSendMessagesTool extends Tool {
static lc_name() {
return "DiscordSendMessagesTool";
}
name = "discord-send-messages";
description = `A discord tool useful for sending messages to a discod channel.
Input should be the discord channel message, since we will already have the channel ID.`;
protected botToken: string;
protected channelId: string;
protected client: Client;
constructor(fields?: DiscordSendMessageToolParams) {
super();
const {
botToken = getEnvironmentVariable("DISCORD_BOT_TOKEN"),
channelId = getEnvironmentVariable("DISCORD_CHANNEL_ID"),
client,
} = fields ?? {};
if (!botToken) {
throw new Error(
"Environment variable DISCORD_BOT_TOKEN missing, but is required for DiscordSendMessagesTool."
);
}
if (!channelId) {
throw new Error(
"Environment variable DISCORD_CHANNEL_ID missing, but is required for DiscordSendMessagesTool."
);
}
this.client =
client ??
new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
});
this.botToken = botToken;
this.channelId = channelId;
}
/** @ignore */
async _call(message: string): Promise<string> {
try {
await this.client.login(this.botToken);
const channel = (await this.client.channels.fetch(
this.channelId
)) as TextChannel;
if (!channel) {
throw new Error("Channel not found");
}
if (!(channel.constructor === TextChannel)) {
throw new Error("Channel is not text channel, cannot send message");
}
await channel.send(message);
await this.client.destroy();
return "Message sent successfully.";
} catch (err) {
await this.client.destroy();
return "Error sending message.";
}
}
}
/**
* A tool for searching for messages within a discord channel using a bot.
* It extends the base Tool class and implements the _call method to
* perform the retrieve operation. Requires an bot token which can be set
* in the environment variables, and the discord channel ID of the channel.
* The _call method takes the search term as the input argument.
* The bot must have read permissions to the given channel. It returns the
* message content, author, and time the message was created for each message.
*/
export class DiscordChannelSearchTool extends Tool {
static lc_name() {
return "DiscordChannelSearchTool";
}
name = "discord_channel_search_tool";
description = `A discord toolkit. Useful for searching for messages
within a discord channel. Input should be the search term. The bot
should have read permissions for the channel.`;
protected botToken: string;
protected channelId: string;
protected client: Client;
constructor(fields?: DiscordChannelSearchParams) {
super();
const {
botToken = getEnvironmentVariable("DISCORD_BOT_TOKEN"),
channelId = getEnvironmentVariable("DISCORD_CHANNEL_ID"),
client,
} = fields ?? {};
if (!botToken) {
throw new Error(
"Environment variable DISCORD_BOT_TOKEN missing, but is required for DiscordChannelSearchTool."
);
}
if (!channelId) {
throw new Error(
"Environment variable DISCORD_CHANNEL_ID missing, but is required for DiscordChannelSearchTool."
);
}
this.client =
client ??
new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages],
});
this.botToken = botToken;
this.channelId = channelId;
}
/** @ignore */
async _call(searchTerm: string): Promise<string> {
try {
await this.client.login(this.botToken);
const channel = (await this.client.channels.fetch(
this.channelId
)) as TextChannel;
if (!channel) {
return "Channel not found";
}
const messages = await channel.messages.fetch();
await this.client.destroy();
const filtered = messages.filter((message) =>
message.content.toLowerCase().includes(searchTerm.toLowerCase())
);
const results =
filtered.map((message) => ({
author: message.author.tag,
content: message.content,
timestamp: message.createdAt,
})) ?? [];
return JSON.stringify(results);
} catch (err) {
await this.client.destroy();
return "Error searching through channel.";
}
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_places.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Tool } from "@langchain/core/tools";
/**
* Interface for parameters required by GooglePlacesAPI class.
*/
export interface GooglePlacesAPIParams {
apiKey?: string;
}
/**
* Tool that queries the Google Places API
*/
export class GooglePlacesAPI extends Tool {
static lc_name() {
return "GooglePlacesAPI";
}
get lc_secrets(): { [key: string]: string } | undefined {
return {
apiKey: "GOOGLE_PLACES_API_KEY",
};
}
name = "google_places";
protected apiKey: string;
description = `A wrapper around Google Places API. Useful for when you need to validate or
discover addresses from ambiguous text. Input should be a search query.`;
constructor(fields?: GooglePlacesAPIParams) {
super(...arguments);
const apiKey =
fields?.apiKey ?? getEnvironmentVariable("GOOGLE_PLACES_API_KEY");
if (apiKey === undefined) {
throw new Error(
`Google Places API key not set. You can set it as "GOOGLE_PLACES_API_KEY" in your environment variables.`
);
}
this.apiKey = apiKey;
}
async _call(input: string) {
const res = await fetch(
`https://places.googleapis.com/v1/places:searchText`,
{
method: "POST",
body: JSON.stringify({
textQuery: input,
languageCode: "en",
}),
headers: {
"X-Goog-Api-Key": this.apiKey,
"X-Goog-FieldMask":
"places.displayName,places.formattedAddress,places.id,places.internationalPhoneNumber,places.websiteUri",
"Content-Type": "application/json",
},
}
);
if (!res.ok) {
let message;
try {
const json = await res.json();
message = json.error.message;
} catch (e) {
message =
"Unable to parse error message: Google did not return a JSON response.";
}
throw new Error(
`Got ${res.status}: ${res.statusText} error from Google Places API: ${message}`
);
}
const json = await res.json();
const results =
json?.places?.map(
(place: {
id?: string;
internationalPhoneNumber?: string;
formattedAddress?: string;
websiteUri?: string;
displayName?: { text?: string };
}) => ({
name: place.displayName?.text,
id: place.id,
address: place.formattedAddress,
phoneNumber: place.internationalPhoneNumber,
website: place.websiteUri,
})
) ?? [];
return JSON.stringify(results);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/stackexchange.ts
|
import { Tool } from "@langchain/core/tools";
export interface StackExchangeAnswer {
items: StackExchangeItem[];
has_more: boolean;
quota_max: number;
quota_remaining: number;
}
export interface StackExchangeItem {
tags: string[];
question_score: number;
is_accepted: boolean;
has_accepted_answer?: boolean;
answer_count?: number;
is_answered: boolean;
question_id: number;
item_type: string;
score: number;
last_activity_date: number;
creation_date: number;
body: string;
excerpt: string;
title: string;
answer_id?: number;
}
type StackExchangeOptions = Record<string, string | number | boolean>;
export interface StackExchangeAPIParams {
/**
* The maximum number of results to return from the search.
* Limiting to 10 to avoid context overload.
* @default 3
*/
maxResult?: number;
/**
* Which part of StackOverflows items to match against. One of 'all', 'title',
* 'body'.
* @default "all"
*/
queryType?: "all" | "title" | "body";
/**
* Additional params to pass to the StackExchange API
*/
options?: StackExchangeOptions;
/**
* Separator between question,answer pairs.
* @default "\n\n"
*/
resultSeparator?: string;
}
/**
* Class for interacting with the StackExchange API
* It extends the base Tool class to perform retrieval.
*/
export class StackExchangeAPI extends Tool {
name = "stackexchange";
description = "Stack Exchange API Implementation";
private pageSize: number;
private maxResult = 3;
private key: string | null;
private accessToken: string | null;
private site = "stackoverflow";
private version = "2.3";
private baseUrl = "https://api.stackexchange.com";
private queryType = "all";
private options?: StackExchangeOptions = {};
private resultSeparator?: string = "\n\n";
constructor(params: StackExchangeAPIParams = {}) {
const { maxResult, queryType = "all", options, resultSeparator } = params;
super();
this.maxResult = maxResult || this.maxResult;
this.pageSize = 100;
this.baseUrl = `${this.baseUrl}/${this.version}/`;
this.queryType = queryType === "all" ? "q" : queryType;
this.options = options || this.options;
this.resultSeparator = resultSeparator || this.resultSeparator;
}
async _call(query: string): Promise<string> {
const params = {
[this.queryType]: query,
site: this.site,
...this.options,
};
const output = await this._fetch<StackExchangeAnswer>(
"search/excerpts",
params
);
if (output.items.length < 1) {
return `No relevant results found for '${query}' on Stack Overflow.`;
}
const questions = output.items
.filter((item) => item.item_type === "question")
.slice(0, this.maxResult);
const answers = output.items.filter((item) => item.item_type === "answer");
const results: string[] = [];
for (const question of questions) {
let res_text = `Question: ${question.title}\n${question.excerpt}`;
const relevant_answers = answers.filter(
(answer) => answer.question_id === question.question_id
);
const accepted_answers = relevant_answers.filter(
(answer) => answer.is_accepted
);
if (relevant_answers.length > 0) {
const top_answer =
accepted_answers.length > 0
? accepted_answers[0]
: relevant_answers[0];
const { excerpt } = top_answer;
res_text += `\nAnswer: ${excerpt}`;
}
results.push(res_text);
}
return results.join(this.resultSeparator);
}
/**
* Call the StackExchange API
* @param endpoint Name of the endpoint from StackExchange API
* @param params Additional parameters passed to the endpoint
* @param page Number of the page to retrieve
* @param filter Filtering properties
*/
private async _fetch<T>(
endpoint: string,
params: StackExchangeOptions = {},
page = 1,
filter = "default"
): Promise<T> {
try {
if (!endpoint) {
throw new Error("No end point provided.");
}
const queryParams = new URLSearchParams({
pagesize: this.pageSize.toString(),
page: page.toString(),
filter,
...params,
});
if (this.key) {
queryParams.append("key", this.key);
}
if (this.accessToken) {
queryParams.append("access_token", this.accessToken);
}
const queryParamsString = queryParams.toString();
const endpointUrl = `${this.baseUrl}${endpoint}?${queryParamsString}`;
return await this._makeRequest(endpointUrl);
} catch (e) {
throw new Error("Error while calling Stack Exchange API");
}
}
/**
* Fetch the result of a specific endpoint
* @param endpointUrl Endpoint to call
*/
private async _makeRequest<T>(endpointUrl: string): Promise<T> {
try {
const response = await fetch(endpointUrl);
if (response.status !== 200) {
throw new Error(`HTTP Error: ${response.statusText}`);
}
return await response.json();
} catch (e) {
throw new Error(`Error while calling Stack Exchange API: ${endpointUrl}`);
}
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/aws_lambda.ts
|
import { DynamicTool, DynamicToolInput } from "./dynamic.js";
/**
* Interface for the configuration of the AWS Lambda function.
*/
interface LambdaConfig {
functionName: string;
region?: string;
accessKeyId?: string;
secretAccessKey?: string;
}
/**
* Interface for the arguments to the LambdaClient constructor.
*/
interface LambdaClientConstructorArgs {
region?: string;
credentials?: {
accessKeyId: string;
secretAccessKey: string;
};
}
/**
* Class for invoking AWS Lambda functions within the LangChain framework.
* Extends the DynamicTool class.
*/
class AWSLambda extends DynamicTool {
get lc_namespace(): string[] {
return [...super.lc_namespace, "aws_lambda"];
}
get lc_secrets(): { [key: string]: string } | undefined {
return {
accessKeyId: "AWS_ACCESS_KEY_ID",
secretAccessKey: "AWS_SECRET_ACCESS_KEY",
};
}
private lambdaConfig: LambdaConfig;
constructor({
name,
description,
...rest
}: LambdaConfig & Omit<DynamicToolInput, "func">) {
super({
name,
description,
func: async (input: string) => this._func(input),
});
this.lambdaConfig = rest;
}
/** @ignore */
async _func(input: string): Promise<string> {
const { Client, Invoker } = await LambdaImports();
const clientConstructorArgs: LambdaClientConstructorArgs = {};
if (this.lambdaConfig.region) {
clientConstructorArgs.region = this.lambdaConfig.region;
}
if (this.lambdaConfig.accessKeyId && this.lambdaConfig.secretAccessKey) {
clientConstructorArgs.credentials = {
accessKeyId: this.lambdaConfig.accessKeyId,
secretAccessKey: this.lambdaConfig.secretAccessKey,
};
}
const lambdaClient = new Client(clientConstructorArgs);
return new Promise((resolve) => {
const payloadUint8Array = new TextEncoder().encode(JSON.stringify(input));
const command = new Invoker({
FunctionName: this.lambdaConfig.functionName,
InvocationType: "RequestResponse",
Payload: payloadUint8Array,
});
lambdaClient
.send(command)
.then((response) => {
const responseData = JSON.parse(
new TextDecoder().decode(response.Payload)
);
resolve(responseData.body ? responseData.body : "request completed.");
})
.catch((error: Error) => {
console.error("Error invoking Lambda function:", error);
resolve("failed to complete request");
});
});
}
}
/**
* Helper function that imports the necessary AWS SDK modules for invoking
* the Lambda function. Returns an object that includes the LambdaClient
* and InvokeCommand classes from the AWS SDK.
*/
async function LambdaImports() {
try {
const { LambdaClient, InvokeCommand } = await import(
"@aws-sdk/client-lambda"
);
return {
Client: LambdaClient as typeof LambdaClient,
Invoker: InvokeCommand as typeof InvokeCommand,
};
} catch (e) {
console.error(e);
throw new Error(
"Failed to load @aws-sdk/client-lambda'. Please install it eg. `yarn add @aws-sdk/client-lambda`."
);
}
}
export { AWSLambda };
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/calculator.ts
|
import { Parser } from "expr-eval";
import { Tool } from "@langchain/core/tools";
/**
* The Calculator class is a tool used to evaluate mathematical
* expressions. It extends the base Tool class.
* @example
* ```typescript
* import { Calculator } from "@langchain/community/tools/calculator";
*
* const calculator = new Calculator();
* const sum = await calculator.invoke("99 + 99");
* console.log("The sum of 99 and 99 is:", sum);
* // The sum of 99 and 99 is: 198
* ```
*/
export class Calculator extends Tool {
static lc_name() {
return "Calculator";
}
get lc_namespace() {
return [...super.lc_namespace, "calculator"];
}
name = "calculator";
/** @ignore */
async _call(input: string) {
try {
return Parser.evaluate(input).toString();
} catch (error) {
return "I don't know how to do that.";
}
}
description = `Useful for getting the result of a math expression. The input to this tool should be a valid mathematical expression that could be executed by a simple calculator.`;
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_routes.ts
|
import { StructuredTool } from "@langchain/core/tools";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { z } from "zod";
/**
* Interfaces for the response from the Google Routes API.
*/
interface Arrival {
arrivalTime: string;
localizedTime: string;
localizedTimezone: string;
arrivalAddress: string;
}
interface Departure {
departureTime: string;
localizedTime: string;
localizedTimezone: string;
departureAddress: string;
}
interface transitDetails {
transitName?: string;
transitNameCode?: string;
transitVehicleType: string;
}
interface travelInstructions {
navigationInstruction: string;
travelMode: string;
}
interface localizedValues {
distance: string;
duration: string;
transitFare?: string;
}
interface TollInfo {
currencyCode: string;
value: string;
}
/**
* Interface for the output of the tool for a transit route.
*/
interface FilteredTransitRoute {
departure: Departure;
arrival: Arrival;
travelInstructions: travelInstructions[];
localizedValues: localizedValues;
transitDetails: transitDetails;
routeLabels: string[];
warnings?: string[];
}
/**
* Interface for the output of the tool for a non-transit route.
* This includes driving, walking, bicycling, and two-wheeler routes.
*/
interface FilteredRoute {
description: string;
distance: string;
duration: string;
routeLabels: string[];
warnings?: string[];
tollInfo?: TollInfo;
}
/**
* Interface for the body of the request to the Google Routes API.
*/
interface Body {
origin: {
address: string;
};
destination: {
address: string;
};
travel_mode: string;
routing_preference?: string;
computeAlternativeRoutes: boolean;
departureTime?: string;
arrivalTime?: string;
transitPreferences?: {
routingPreference: string;
};
extraComputations?: string[];
}
const getTimezoneOffsetInHours = () => {
const offsetInMinutes = new Date().getTimezoneOffset();
const offsetInHours = -offsetInMinutes / 60;
return offsetInHours;
};
/**
* Helper functions to create the response objects for the Google Routes API.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createDeparture(transitDetails: any): Departure {
const { stopDetails, localizedValues } = transitDetails;
return {
departureTime: stopDetails.departureTime,
localizedTime: localizedValues.departureTime.time.text,
localizedTimezone: localizedValues.departureTime.timeZone,
departureAddress: stopDetails.departureStop.name,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createArrival(transitDetails: any): Arrival {
const { stopDetails, localizedValues } = transitDetails;
return {
arrivalTime: stopDetails.arrivalTime,
localizedTime: localizedValues.arrivalTime.time.text,
localizedTimezone: localizedValues.arrivalTime.timeZone,
arrivalAddress: stopDetails.arrivalStop.name,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createTravelInstructions(stepsOverview: any): travelInstructions[] {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return stepsOverview.multiModalSegments.map((segment: any) => ({
...(segment.navigationInstruction
? {
navigationInstruction: segment.navigationInstruction.instructions,
}
: {}),
travelMode: segment.travelMode,
}));
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createLocalizedValues(route: any): localizedValues {
const { distance, duration, transitFare } = route.localizedValues;
return {
distance: distance.text,
duration: duration.text,
...(transitFare?.text ? { transitFare: transitFare.text } : {}),
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createTransitDetails(transitDetails: any): transitDetails {
const { name, nameShort, vehicle } = transitDetails.transitLine;
return {
...(name ? { transitName: name } : {}),
...(nameShort ? { transitNameCode: nameShort } : {}),
transitVehicleType: vehicle.type,
};
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function createRouteLabel(route: any): string[] {
return route.routeLabels;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function filterRoutes(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
route: any,
travel_mode: string
): FilteredTransitRoute | FilteredRoute {
if (travel_mode === "TRANSIT") {
const transitStep = route.legs[0].steps.find(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(step: any) => step.transitDetails
);
const filteredRoute: FilteredTransitRoute = {
departure: createDeparture(transitStep.transitDetails),
arrival: createArrival(transitStep.transitDetails),
travelInstructions: createTravelInstructions(route.legs[0].stepsOverview),
localizedValues: createLocalizedValues(route),
transitDetails: createTransitDetails(transitStep.transitDetails),
routeLabels: createRouteLabel(route),
};
if (route.warnings && route.warnings.length > 0) {
filteredRoute.warnings = route.warnings;
}
return filteredRoute;
} else {
const filteredRoute: FilteredRoute = {
description: route.description,
routeLabels: createRouteLabel(route),
...createLocalizedValues(route),
};
if (route.warnings && route.warnings.length > 0) {
filteredRoute.warnings = route.warnings;
}
if (route.travelAdvisory && route.travelAdvisory.tollInfo) {
filteredRoute.tollInfo = {
currencyCode:
route.travelAdvisory.tollInfo.estimatedPrice[0].currencyCode,
value: route.travelAdvisory.tollInfo.estimatedPrice[0].units,
};
}
return filteredRoute;
}
}
/**
* Interface for parameter s required by GoogleRoutesAPI class.
*/
export interface GoogleRoutesAPIParams {
apiKey?: string;
}
/**
* Class for interacting with the Google Routes API
* It extends the StructuredTool class to perform retrieval.
*/
export class GoogleRoutesAPI extends StructuredTool {
static lc_name() {
return "GoogleRoutesAPI";
}
get lc_secrets(): { [key: string]: string } | undefined {
return {
apiKey: "GOOGLE_ROUTES_API_KEY",
};
}
name: string;
description: string;
protected apiKey: string;
schema: z.ZodObject<{
origin: z.ZodString;
destination: z.ZodString;
travel_mode: z.ZodEnum<
["DRIVE", "WALK", "BICYCLE", "TRANSIT", "TWO_WHEELER"]
>;
computeAlternativeRoutes: z.ZodBoolean;
departureTime: z.ZodOptional<z.ZodString>;
arrivalTime: z.ZodOptional<z.ZodString>;
transitPreferences: z.ZodOptional<
z.ZodObject<{
routingPreference: z.ZodEnum<["LESS_WALKING", "FEWER_TRANSFERS"]>;
}>
>;
extraComputations: z.ZodOptional<z.ZodArray<z.ZodEnum<["TOLLS"]>>>;
}>;
constructor(fields?: GoogleRoutesAPIParams) {
super(...arguments);
const apiKey =
fields?.apiKey ?? getEnvironmentVariable("GOOGLE_ROUTES_API_KEY");
if (apiKey === undefined) {
throw new Error(
`Google Routes API key not set. You can set it as "GOOGLE_ROUTES_API_KEY" in your environment variables.`
);
}
this.apiKey = apiKey;
this.name = "google_routes";
this.description = `
This tool retrieves routing info using the Google Routes API for driving, walking, biking, transit, and two-wheeler routes. Get departure/arrival times, travel instructions, transit fare, warnings, alternative routes, tolls prices, and routing preferences like less walking or fewer transfers.
Output:
- "TRANSIT" mode: Departure/arrival details, transit name/code, fare, details, warnings, alternative routes, and expected departure/arrival times.
- Other modes: Route description, distance, duration, warnings, alternative routes, tolls prices, and expected departure/arrival times.
Current time in user's timezone: ${new Date().toLocaleString()}.
`;
this.schema = z.object({
origin: z
.string()
.describe(`Origin address, can be either a place or an address.`),
destination: z
.string()
.describe(`Destination address, can be either a place or an address.`),
travel_mode: z
.enum(["DRIVE", "WALK", "BICYCLE", "TRANSIT", "TWO_WHEELER"])
.describe(`The mode of transport`),
computeAlternativeRoutes: z
.boolean()
.describe(
`Compute alternative routes, set to true if user wants multiple routes, false otherwise.`
),
departureTime: z
.string()
.optional()
.describe(
`Time that the user wants to depart.
There cannot be a departure time if an arrival time is specified.
Expected departure time should be provided as a timestamp in RFC3339 format: YYYY-MM-DDThh:mm:ss+00:00. The date should be in UTC time and the +00:00 represents the UTC offset.
For instance, if the the user's timezone is -5, the offset would be -05:00 meaning YYYY-MM-DDThh:mm:ss-05:00 with YYYY-MM-DDThh:mm:ss being in UTC.
For reference, here is the current time in UTC: ${new Date().toISOString()} and the user's timezone offset is ${getTimezoneOffsetInHours()}.
If the departure time is not specified it should not be included.
`
),
arrivalTime: z
.string()
.optional()
.describe(
`Time that the user wants to arrive.
There cannot be an arrival time if a departure time is specified.
Expected arrival time should be provided as a timestamp in RFC3339 format: YYYY-MM-DDThh:mm:ss+00:00. The date should be in UTC time and the +00:00 represents the UTC offset.
For instance, if the the user's timezone is -5, the offset would be -05:00 meaning YYYY-MM-DDThh:mm:ss-05:00 with YYYY-MM-DDThh:mm:ss being in UTC.
For reference, here is the current time in UTC: ${new Date().toISOString()} and the user's timezone offset is ${getTimezoneOffsetInHours()}.
Reminder that the arrival time must be in the future, if the user asks for a arrival time in the past instead of processing the request, warn them that it is not possible to calculate a route for a past time.
If the user asks for a arrival time in a passed hour today, calculate it for the next day.
If the arrival time is not specified it should not be included. `
),
transitPreferences: z
.object({
routingPreference: z.enum(["LESS_WALKING", "FEWER_TRANSFERS"])
.describe(`Transit routing preference.
By default, it should not be included.`),
})
.optional()
.describe(
`Transit routing preference.
By default, it should not be included.`
),
extraComputations: z
.array(z.enum(["TOLLS"]))
.optional()
.describe(`Calculate tolls for the route.`),
});
}
async _call(input: z.infer<typeof GoogleRoutesAPI.prototype.schema>) {
const {
origin,
destination,
travel_mode,
computeAlternativeRoutes,
departureTime,
arrivalTime,
transitPreferences,
extraComputations,
} = input;
const now = new Date();
if (departureTime && new Date(departureTime) < now) {
return "It is not possible to calculate a route with a past departure time. Warn the user that it is not possible to calculate a route with a past departure time.";
}
if (arrivalTime && new Date(arrivalTime) < now) {
return "It is not possible to calculate a route with a past arrival time. Warn the user that it is not possible to calculate a route with a past arrival time.";
}
if (travel_mode !== "TRANSIT" && arrivalTime) {
return "It is not possible to calculate an arrival time for modes other than transit. Warn the user that it is not possible to calculate an arrival time for the selected mode of transport.";
}
if (travel_mode === "TRANSIT" && extraComputations) {
return "It is not possible to calculate tolls for transit mode. Warn the user that it is not possible to calculate tolls for transit mode.";
}
const body: Body = {
origin: {
address: origin,
},
destination: {
address: destination,
},
travel_mode,
computeAlternativeRoutes: computeAlternativeRoutes ?? false,
departureTime,
arrivalTime,
transitPreferences,
extraComputations: (extraComputations as string[]) ?? [],
};
let fieldMask =
"routes.description,routes.localizedValues,routes.travelAdvisory,routes.legs.steps.transitDetails,routes.routeLabels,routes.warnings";
if (travel_mode === "TRANSIT") {
fieldMask += ",routes.legs.stepsOverview";
}
if (travel_mode === "DRIVE" || travel_mode === "TWO_WHEELER") {
body.routing_preference = "TRAFFIC_AWARE";
}
const res = await fetch(
`https://routes.googleapis.com/directions/v2:computeRoutes`,
{
method: "POST",
body: JSON.stringify(body),
headers: {
"X-Goog-Api-Key": this.apiKey,
"X-Goog-FieldMask": fieldMask,
"Content-Type": "application/json",
},
}
);
if (!res.ok) {
let message;
try {
const json = await res.json();
message = json.error.message;
} catch (e) {
message = `Unable to parse error message: Google did not return a JSON response. Error: ${e}`;
}
throw new Error(
`Got ${res.status}: ${res.statusText} error from Google Routes API: ${message}`
);
}
const json = await res.json();
if (Object.keys(json).length === 0) {
return "Invalid route. The route may be too long or impossible to travel by the selected mode of transport.";
}
const routes: FilteredTransitRoute[] | FilteredRoute[] = json.routes.map(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(route: any) => filterRoutes(route, travel_mode)
);
return JSON.stringify(routes);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/duckduckgo_search.ts
|
import { Tool, ToolParams } from "@langchain/core/tools";
import { search, SearchOptions } from "duck-duck-scrape";
export {
SafeSearchType,
SearchOptions,
SearchTimeType,
} from "duck-duck-scrape";
export interface DuckDuckGoSearchParameters extends ToolParams {
/**
* The search options for the search using the SearchOptions interface
* from the duck-duck-scrape package.
*/
searchOptions?: SearchOptions;
/**
* The maximum number of results to return from the search.
* Limiting to 10 to avoid context overload.
* @default 10
*/
maxResults?: number;
}
const DEFAULT_MAX_RESULTS = 10;
/**
* DuckDuckGo tool integration.
*
* Setup:
* Install `@langchain/community` and `duck-duck-scrape`.
*
* ```bash
* npm install @langchain/community duck-duck-scrape
* ```
*
* ## [Constructor args](https://api.js.langchain.com/classes/_langchain_community.tools_duckduckgo_search.DuckDuckGoSearch.html#constructor)
*
* <details open>
* <summary><strong>Instantiate</strong></summary>
*
* ```typescript
* import { DuckDuckGoSearch } from "@langchain/community/tools/duckduckgo_search";
*
* const tool = new DuckDuckGoSearch({ maxResults: 1 });
* ```
* </details>
*
* <br />
*
* <details>
*
* <summary><strong>Invocation</strong></summary>
*
* ```typescript
* await tool.invoke("what is the current weather in sf?");
*
* // output: [{"title":"San Francisco, CA Current Weather | AccuWeather","link":"https://www.accuweather.com/en/us/san-francisco/94103/current-weather/347629","snippet":"<b>Current</b> <b>weather</b> <b>in</b> San Francisco, CA. Check <b>current</b> conditions in San Francisco, CA with radar, hourly, and more."}]
* ```
* </details>
*
* <br />
*
* <details>
*
* <summary><strong>Invocation with tool call</strong></summary>
*
* ```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 current weather in sf?",
* },
* id: "tool_call_id",
* name: tool.name,
* type: "tool_call",
* };
* await tool.invoke(modelGeneratedToolCall);
* ```
*
* ```text
* ToolMessage {
* "content": "[{\"title\":\"San Francisco, CA Weather Conditions | Weather Underground\",\"link\":\"https://www.wunderground.com/weather/us/ca/san-francisco\",\"snippet\":\"San Francisco <b>Weather</b> Forecasts. <b>Weather</b> Underground provides local & long-range <b>weather</b> forecasts, weatherreports, maps & tropical <b>weather</b> conditions for the San Francisco area.\"}]",
* "name": "duckduckgo-search",
* "additional_kwargs": {},
* "response_metadata": {},
* "tool_call_id": "tool_call_id"
* }
* ```
* </details>
*/
export class DuckDuckGoSearch extends Tool {
private searchOptions?: SearchOptions;
private maxResults = DEFAULT_MAX_RESULTS;
constructor(params?: DuckDuckGoSearchParameters) {
super(params ?? {});
const { searchOptions, maxResults } = params ?? {};
this.searchOptions = searchOptions;
this.maxResults = maxResults || this.maxResults;
}
static lc_name() {
return "DuckDuckGoSearch";
}
name = "duckduckgo-search";
description =
"A search engine. Useful for when you need to answer questions about current events. Input should be a search query.";
async _call(input: string): Promise<string> {
const { results } = await search(input, this.searchOptions);
return JSON.stringify(
results
.map((result) => ({
title: result.title,
link: result.url,
snippet: result.description,
}))
.slice(0, this.maxResults)
);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/ifttt.ts
|
/** From https://github.com/SidU/teams-langchain-js/wiki/Connecting-IFTTT-Services.
# Creating a webhook
- Go to https://ifttt.com/create
# Configuring the "If This"
- Click on the "If This" button in the IFTTT interface.
- Search for "Webhooks" in the search bar.
- Choose the first option for "Receive a web request with a JSON payload."
- Choose an Event Name that is specific to the service you plan to connect to.
This will make it easier for you to manage the webhook URL.
For example, if you're connecting to Spotify, you could use "Spotify" as your
Event Name.
- Click the "Create Trigger" button to save your settings and create your webhook.
# Configuring the "Then That"
- Tap on the "Then That" button in the IFTTT interface.
- Search for the service you want to connect, such as Spotify.
- Choose an action from the service, such as "Add track to a playlist".
- Configure the action by specifying the necessary details, such as the playlist name,
e.g., "Songs from AI".
- Reference the JSON Payload received by the Webhook in your action. For the Spotify
scenario, choose "{{JsonPayload}}" as your search query.
- Tap the "Create Action" button to save your action settings.
- Once you have finished configuring your action, click the "Finish" button to
complete the setup.
- Congratulations! You have successfully connected the Webhook to the desired
service, and you're ready to start receiving data and triggering actions 🎉
# Finishing up
- To get your webhook URL go to https://ifttt.com/maker_webhooks/settings
- Copy the IFTTT key value from there. The URL is of the form
https://maker.ifttt.com/use/YOUR_IFTTT_KEY. Grab the YOUR_IFTTT_KEY value.
*/
import { Tool } from "@langchain/core/tools";
/**
* Represents a tool for creating and managing webhooks with the IFTTT (If
* This Then That) service. The IFTTT service allows users to create
* chains of simple conditional statements, called applets, which are
* triggered based on changes to other web services.
*/
export class IFTTTWebhook extends Tool {
static lc_name() {
return "IFTTTWebhook";
}
private url: string;
name: string;
description: string;
constructor(url: string, name: string, description: string) {
super(...arguments);
this.url = url;
this.name = name;
this.description = description;
}
/** @ignore */
async _call(input: string): Promise<string> {
const headers = { "Content-Type": "application/json" };
const body = JSON.stringify({ this: input });
const response = await fetch(this.url, {
method: "POST",
headers,
body,
});
if (!response.ok) {
throw new Error(`HTTP error ${response.status}`);
}
const result = await response.text();
return result;
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/gmail/create_draft.ts
|
import { z } from "zod";
import { GmailBaseTool, GmailBaseToolParams } from "./base.js";
import { CREATE_DRAFT_DESCRIPTION } from "./descriptions.js";
export class GmailCreateDraft extends GmailBaseTool {
name = "create_gmail_draft";
schema = z.object({
message: z.string(),
to: z.array(z.string()),
subject: z.string(),
cc: z.array(z.string()).optional(),
bcc: z.array(z.string()).optional(),
});
description = CREATE_DRAFT_DESCRIPTION;
constructor(fields?: GmailBaseToolParams) {
super(fields);
}
private prepareDraftMessage(
message: string,
to: string[],
subject: string,
cc?: string[],
bcc?: string[]
) {
const draftMessage = {
message: {
raw: "",
},
};
const email = [
`To: ${to.join(", ")}`,
`Subject: ${subject}`,
cc ? `Cc: ${cc.join(", ")}` : "",
bcc ? `Bcc: ${bcc.join(", ")}` : "",
"",
message,
].join("\n");
draftMessage.message.raw = Buffer.from(email).toString("base64url");
return draftMessage;
}
async _call(arg: z.output<typeof this.schema>) {
const { message, to, subject, cc, bcc } = arg;
const create_message = this.prepareDraftMessage(
message,
to,
subject,
cc,
bcc
);
const response = await this.gmail.users.drafts.create({
userId: "me",
requestBody: create_message,
});
return `Draft created. Draft Id: ${response.data.id}`;
}
}
export type CreateDraftSchema = {
message: string;
to: string[];
subject: string;
cc?: string[];
bcc?: string[];
};
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/gmail/get_message.ts
|
import { z } from "zod";
import { GmailBaseToolParams, GmailBaseTool } from "./base.js";
import { GET_MESSAGE_DESCRIPTION } from "./descriptions.js";
export class GmailGetMessage extends GmailBaseTool {
name = "gmail_get_message";
schema = z.object({
messageId: z.string(),
});
description = GET_MESSAGE_DESCRIPTION;
constructor(fields?: GmailBaseToolParams) {
super(fields);
}
async _call(arg: z.output<typeof this.schema>) {
const { messageId } = arg;
const message = await this.gmail.users.messages.get({
userId: "me",
id: messageId,
});
const { data } = message;
if (!data) {
throw new Error("No data returned from Gmail");
}
const { payload } = data;
if (!payload) {
throw new Error("No payload returned from Gmail");
}
const { headers } = payload;
if (!headers) {
throw new Error("No headers returned from Gmail");
}
const subject = headers.find((header) => header.name === "Subject");
if (!subject) {
throw new Error("No subject returned from Gmail");
}
const body = headers.find((header) => header.name === "Body");
if (!body) {
throw new Error("No body returned from Gmail");
}
const from = headers.find((header) => header.name === "From");
if (!from) {
throw new Error("No from returned from Gmail");
}
const to = headers.find((header) => header.name === "To");
if (!to) {
throw new Error("No to returned from Gmail");
}
const date = headers.find((header) => header.name === "Date");
if (!date) {
throw new Error("No date returned from Gmail");
}
const messageIdHeader = headers.find(
(header) => header.name === "Message-ID"
);
if (!messageIdHeader) {
throw new Error("No message id returned from Gmail");
}
return `Result for the prompt ${messageId} \n${JSON.stringify({
subject: subject.value,
body: body.value,
from: from.value,
to: to.value,
date: date.value,
messageId: messageIdHeader.value,
})}`;
}
}
export type GetMessageSchema = {
messageId: string;
};
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/gmail/send_message.ts
|
import { z } from "zod";
import { GmailBaseTool, GmailBaseToolParams } from "./base.js";
import { GET_MESSAGE_DESCRIPTION } from "./descriptions.js";
export class GmailSendMessage extends GmailBaseTool {
name = "gmail_send_message";
schema = z.object({
message: z.string(),
to: z.array(z.string()),
subject: z.string(),
cc: z.array(z.string()).optional(),
bcc: z.array(z.string()).optional(),
});
description = GET_MESSAGE_DESCRIPTION;
constructor(fields?: GmailBaseToolParams) {
super(fields);
}
private createEmailMessage({
message,
to,
subject,
cc,
bcc,
}: z.infer<typeof this.schema>): string {
const emailLines: string[] = [];
// Format the recipient(s)
const formatEmailList = (emails: string | string[]): string =>
Array.isArray(emails) ? emails.join(",") : emails;
emailLines.push(`To: ${formatEmailList(to)}`);
if (cc) emailLines.push(`Cc: ${formatEmailList(cc)}`);
if (bcc) emailLines.push(`Bcc: ${formatEmailList(bcc)}`);
emailLines.push(`Subject: ${subject}`);
emailLines.push("");
emailLines.push(message);
// Convert the email message to base64url string
const email = emailLines.join("\r\n").trim();
// this encode may be an issue
return Buffer.from(email).toString("base64url");
}
async _call({
message,
to,
subject,
cc,
bcc,
}: z.output<typeof this.schema>): Promise<string> {
const rawMessage = this.createEmailMessage({
message,
to,
subject,
cc,
bcc,
});
try {
const response = await this.gmail.users.messages.send({
userId: "me",
requestBody: {
raw: rawMessage,
},
});
return `Message sent. Message Id: ${response.data.id}`;
} catch (error) {
throw new Error(`An error occurred while sending the message: ${error}`);
}
}
}
export type SendMessageSchema = {
message: string;
to: string[];
subject: string;
cc?: string[];
bcc?: string[];
};
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/gmail/descriptions.ts
|
export const CREATE_DRAFT_DESCRIPTION = `A tool for creating draft emails in Gmail.
INPUT example:
{
"message": "Hello, this is a test draft",
"to": ["example1@email.com", "example2@email.com"],
"subject": "Test Draft",
"cc": ["cc1@email.com"],
"bcc": ["bcc1@email.com"]
}
OUTPUT:
The output is a confirmation message with the draft ID.
`;
export const GET_MESSAGE_DESCRIPTION = `A tool for retrieving a specific email message from Gmail using its message ID.
INPUT example:
{
"messageId": "unique_message_id_string"
}
OUTPUT:
The output includes detailed information about the retrieved email message. This includes the subject, body, sender (from), recipients (to), date of the email, and the message ID. If any of these details are not available in the email, the tool will throw an error indicating the missing information.
Example Output:
"Result for the prompt unique_message_id_string
{
'subject': 'Email Subject',
'body': 'Email Body Content',
'from': 'sender@email.com',
'to': 'recipient@email.com',
'date': 'Email Date',
'messageId': 'unique_message_id_string'
}"
`;
export const GET_THREAD_DESCRIPTION = `A tool for retrieving an entire email thread from Gmail using the thread ID.
INPUT example:
{
"threadId": "unique_thread_id_string"
}
OUTPUT:
The output includes an array of all the messages in the specified thread. Each message in the array contains detailed information including the subject, body, sender (from), recipients (to), date of the email, and the message ID. If any of these details are not available in a message, the tool will throw an error indicating the missing information.
Example Output:
"Result for the prompt unique_thread_id_string
[
{
'subject': 'Email Subject',
'body': 'Email Body Content',
'from': 'sender@email.com',
'to': 'recipient@email.com',
'date': 'Email Date',
'messageId': 'unique_message_id_string'
},
... (other messages in the thread)
]"
`;
export const SEND_MESSAGE_DESCRIPTION = `A tool for sending an email message using Gmail. It allows users to specify recipients, subject, and the content of the message, along with optional cc and bcc fields.
INPUT example:
{
"message": "Hello, this is a test email",
"to": ["recipient1@email.com", "recipient2@email.com"],
"subject": "Test Email",
"cc": ["cc1@email.com"],
"bcc": ["bcc1@email.com"]
}
OUTPUT:
The output is a confirmation message with the ID of the sent email. If there is an error during the sending process, the tool will throw an error with a description of the problem.
Example Output:
"Message sent. Message Id: unique_message_id_string"
`;
export const SEARCH_DESCRIPTION = `A tool for searching email messages or threads in Gmail using a specific query. It offers the flexibility to choose between messages and threads as the search resource.
INPUT example:
{
"query": "specific search query",
"maxResults": 10, // Optional: number of results to return
"resource": "messages" // Optional: can be "messages" or "threads"
}
OUTPUT:
The output is a JSON list of either email messages or threads, depending on the specified resource, that matches the search query. For 'messages', the output includes details like the message ID, thread ID, snippet, body, subject, and sender of each message. For 'threads', it includes the thread ID, snippet, body, subject, and sender of the first message in each thread. If no data is returned, or if the specified resource is invalid, the tool throws an error with a relevant message.
Example Output for 'messages':
"Result for the query 'specific search query':
[
{
'id': 'message_id',
'threadId': 'thread_id',
'snippet': 'message snippet',
'body': 'message body',
'subject': 'message subject',
'sender': 'sender's email'
},
... (other messages matching the query)
]"
Example Output for 'threads':
"Result for the query 'specific search query':
[
{
'id': 'thread_id',
'snippet': 'thread snippet',
'body': 'first message body',
'subject': 'first message subject',
'sender': 'first message sender'
},
... (other threads matching the query)
]"
`;
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/gmail/index.ts
|
export { GmailCreateDraft } from "./create_draft.js";
export { GmailGetMessage } from "./get_message.js";
export { GmailGetThread } from "./get_thread.js";
export { GmailSearch } from "./search.js";
export { GmailSendMessage } from "./send_message.js";
export type { GmailBaseToolParams } from "./base.js";
export type { CreateDraftSchema } from "./create_draft.js";
export type { GetMessageSchema } from "./get_message.js";
export type { GetThreadSchema } from "./get_thread.js";
export type { SearchSchema } from "./search.js";
export type { SendMessageSchema } from "./send_message.js";
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/gmail/get_thread.ts
|
import { z } from "zod";
import { GmailBaseTool, GmailBaseToolParams } from "./base.js";
import { GET_THREAD_DESCRIPTION } from "./descriptions.js";
export class GmailGetThread extends GmailBaseTool {
name = "gmail_get_thread";
schema = z.object({
threadId: z.string(),
});
description = GET_THREAD_DESCRIPTION;
constructor(fields?: GmailBaseToolParams) {
super(fields);
}
async _call(arg: z.output<typeof this.schema>) {
const { threadId } = arg;
const thread = await this.gmail.users.threads.get({
userId: "me",
id: threadId,
});
const { data } = thread;
if (!data) {
throw new Error("No data returned from Gmail");
}
const { messages } = data;
if (!messages) {
throw new Error("No messages returned from Gmail");
}
return `Result for the prompt ${threadId} \n${JSON.stringify(
messages.map((message) => {
const { payload } = message;
if (!payload) {
throw new Error("No payload returned from Gmail");
}
const { headers } = payload;
if (!headers) {
throw new Error("No headers returned from Gmail");
}
const subject = headers.find((header) => header.name === "Subject");
if (!subject) {
throw new Error("No subject returned from Gmail");
}
const body = headers.find((header) => header.name === "Body");
if (!body) {
throw new Error("No body returned from Gmail");
}
const from = headers.find((header) => header.name === "From");
if (!from) {
throw new Error("No from returned from Gmail");
}
const to = headers.find((header) => header.name === "To");
if (!to) {
throw new Error("No to returned from Gmail");
}
const date = headers.find((header) => header.name === "Date");
if (!date) {
throw new Error("No date returned from Gmail");
}
const messageIdHeader = headers.find(
(header) => header.name === "Message-ID"
);
if (!messageIdHeader) {
throw new Error("No message id returned from Gmail");
}
return {
subject: subject.value,
body: body.value,
from: from.value,
to: to.value,
date: date.value,
messageId: messageIdHeader.value,
};
})
)}`;
}
}
export type GetThreadSchema = {
threadId: string;
};
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/gmail/base.ts
|
import { gmail_v1, google } from "googleapis";
import { z } from "zod";
import { StructuredTool } from "@langchain/core/tools";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
export interface GmailBaseToolParams {
credentials?: {
clientEmail?: string;
privateKey?: string;
keyfile?: string;
subject?: string;
};
scopes?: string[];
}
export abstract class GmailBaseTool extends StructuredTool {
private CredentialsSchema = z
.object({
clientEmail: z
.string()
.min(1)
.default(getEnvironmentVariable("GMAIL_CLIENT_EMAIL") ?? ""),
privateKey: z
.string()
.default(getEnvironmentVariable("GMAIL_PRIVATE_KEY") ?? ""),
keyfile: z
.string()
.default(getEnvironmentVariable("GMAIL_KEYFILE") ?? ""),
subject: z
.string()
.default(getEnvironmentVariable("GMAIL_SUBJECT") ?? ""),
})
.refine(
(credentials) =>
credentials.privateKey !== "" || credentials.keyfile !== "",
{
message:
"Missing GMAIL_PRIVATE_KEY or GMAIL_KEYFILE to interact with Gmail",
}
);
private GmailBaseToolParamsSchema = z
.object({
credentials: this.CredentialsSchema.default({}),
scopes: z.array(z.string()).default(["https://mail.google.com/"]),
})
.default({});
name = "Gmail";
description = "A tool to send and view emails through Gmail";
protected gmail: gmail_v1.Gmail;
constructor(fields?: Partial<GmailBaseToolParams>) {
super(...arguments);
const { credentials, scopes } =
this.GmailBaseToolParamsSchema.parse(fields);
this.gmail = this.getGmail(
scopes,
credentials.clientEmail,
credentials.privateKey,
credentials.keyfile,
credentials.subject
);
}
private getGmail(
scopes: string[],
email: string,
key?: string,
keyfile?: string,
subject?: string
) {
const auth = new google.auth.JWT(email, keyfile, key, scopes, subject);
return google.gmail({ version: "v1", auth });
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/gmail/search.ts
|
import { gmail_v1 } from "googleapis";
import { z } from "zod";
import { GmailBaseTool, GmailBaseToolParams } from "./base.js";
import { SEARCH_DESCRIPTION } from "./descriptions.js";
export class GmailSearch extends GmailBaseTool {
name = "search_gmail";
schema = z.object({
query: z.string(),
maxResults: z.number().optional(),
resource: z.enum(["messages", "threads"]).optional(),
});
description = SEARCH_DESCRIPTION;
constructor(fields?: GmailBaseToolParams) {
super(fields);
}
async _call(arg: z.output<typeof this.schema>) {
const { query, maxResults = 10, resource = "messages" } = arg;
const response = await this.gmail.users.messages.list({
userId: "me",
q: query,
maxResults,
});
const { data } = response;
if (!data) {
throw new Error("No data returned from Gmail");
}
const { messages } = data;
if (!messages) {
throw new Error("No messages returned from Gmail");
}
if (resource === "messages") {
const parsedMessages = await this.parseMessages(messages);
return `Result for the query ${query}:\n${JSON.stringify(
parsedMessages
)}`;
} else if (resource === "threads") {
const parsedThreads = await this.parseThreads(messages);
return `Result for the query ${query}:\n${JSON.stringify(parsedThreads)}`;
}
throw new Error(`Invalid resource: ${resource}`);
}
async parseMessages(
messages: gmail_v1.Schema$Message[]
): Promise<gmail_v1.Schema$Message[]> {
const parsedMessages = await Promise.all(
messages.map(async (message) => {
const messageData = await this.gmail.users.messages.get({
userId: "me",
format: "raw",
id: message.id ?? "",
});
const headers = messageData.data.payload?.headers || [];
const subject = headers.find((header) => header.name === "Subject");
const sender = headers.find((header) => header.name === "From");
let body = "";
if (messageData.data.payload?.parts) {
body = messageData.data.payload.parts
.map((part) => part.body?.data ?? "")
.join("");
} else if (messageData.data.payload?.body?.data) {
body = messageData.data.payload.body.data;
}
return {
id: message.id,
threadId: message.threadId,
snippet: message.snippet,
body,
subject,
sender,
};
})
);
return parsedMessages;
}
async parseThreads(
threads: gmail_v1.Schema$Thread[]
): Promise<gmail_v1.Schema$Thread[]> {
const parsedThreads = await Promise.all(
threads.map(async (thread) => {
const threadData = await this.gmail.users.threads.get({
userId: "me",
format: "raw",
id: thread.id ?? "",
});
const headers = threadData.data.messages?.[0]?.payload?.headers || [];
const subject = headers.find((header) => header.name === "Subject");
const sender = headers.find((header) => header.name === "From");
let body = "";
if (threadData.data.messages?.[0]?.payload?.parts) {
body = threadData.data.messages[0].payload.parts
.map((part) => part.body?.data ?? "")
.join("");
} else if (threadData.data.messages?.[0]?.payload?.body?.data) {
body = threadData.data.messages[0].payload.body.data;
}
return {
id: thread.id,
snippet: thread.snippet,
body,
subject,
sender,
};
})
);
return parsedThreads;
}
}
export type SearchSchema = {
query: string;
maxResults?: number;
resource?: "messages" | "threads";
};
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar/view.ts
|
import { CallbackManagerForToolRun } from "@langchain/core/callbacks/manager";
import { GoogleCalendarBase, GoogleCalendarAgentParams } from "./base.js";
import { VIEW_TOOL_DESCRIPTION } from "./descriptions.js";
import { runViewEvents } from "./commands/run-view-events.js";
/**
* @example
* ```typescript
* const googleCalendarViewTool = new GoogleCalendarViewTool({
* credentials: {
* clientEmail: process.env.GOOGLE_CALENDAR_CLIENT_EMAIL,
* privateKey: process.env.GOOGLE_CALENDAR_PRIVATE_KEY,
* calendarId: process.env.GOOGLE_CALENDAR_CALENDAR_ID,
* },
* scopes: [
* "https:
* "https:
* ],
* model: new ChatOpenAI({}),
* });
* const viewInput = `What meetings do I have this week?`;
* const viewResult = await googleCalendarViewTool.invoke({ input: viewInput });
* console.log("View Result", viewResult);
* ```
*/
export class GoogleCalendarViewTool extends GoogleCalendarBase {
name = "google_calendar_view";
description = VIEW_TOOL_DESCRIPTION;
constructor(fields: GoogleCalendarAgentParams) {
super(fields);
}
async _call(query: string, runManager?: CallbackManagerForToolRun) {
const auth = await this.getAuth();
const model = this.getModel();
return runViewEvents(
query,
{
auth,
model,
calendarId: this.calendarId,
},
runManager
);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar/create.ts
|
import { CallbackManagerForToolRun } from "@langchain/core/callbacks/manager";
import { GoogleCalendarBase, GoogleCalendarAgentParams } from "./base.js";
import { runCreateEvent } from "./commands/run-create-events.js";
import { CREATE_TOOL_DESCRIPTION } from "./descriptions.js";
/**
* @example
* ```typescript
* const googleCalendarCreateTool = new GoogleCalendarCreateTool({
* credentials: {
* clientEmail: process.env.GOOGLE_CALENDAR_CLIENT_EMAIL,
* privateKey: process.env.GOOGLE_CALENDAR_PRIVATE_KEY,
* calendarId: process.env.GOOGLE_CALENDAR_CALENDAR_ID,
* },
* scopes: [
* "https:
* "https:
* ],
* model: new ChatOpenAI({}),
* });
* const createInput = `Create a meeting with John Doe next Friday at 4pm - adding to the agenda of it the result of 99 + 99`;
* const createResult = await googleCalendarCreateTool.invoke({
* input: createInput,
* });
* console.log("Create Result", createResult);
* ```
*/
export class GoogleCalendarCreateTool extends GoogleCalendarBase {
name = "google_calendar_create";
description = CREATE_TOOL_DESCRIPTION;
constructor(fields: GoogleCalendarAgentParams) {
super(fields);
}
async _call(query: string, runManager?: CallbackManagerForToolRun) {
const auth = await this.getAuth();
const model = this.getModel();
return runCreateEvent(
query,
{
auth,
model,
calendarId: this.calendarId,
},
runManager
);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar/descriptions.ts
|
export const CREATE_TOOL_DESCRIPTION = `A tool for creating Google Calendar events and meetings.
INPUT example:
"action": "google_calendar_create",
"action_input": "create a new meeting with John Doe tomorrow at 4pm"
OUTPUT:
Output is a confirmation of a created event.
`;
export const VIEW_TOOL_DESCRIPTION = `A tool for retrieving Google Calendar events and meetings.
INPUT examples:
"action": "google_calendar_view",
"action_input": "display meetings for today"
"action": "google_calendar_view",
"action_input": "show events for tomorrow"
"action": "google_calendar_view",
"action_input": "display meetings for tomorrow between 4pm and 8pm"
OUTPUT:
- title, start time, end time, attendees, description (if available)
`;
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar/index.ts
|
export { GoogleCalendarCreateTool } from "./create.js";
export { GoogleCalendarViewTool } from "./view.js";
export type { GoogleCalendarAgentParams } from "./base.js";
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar/base.ts
|
import { google } from "googleapis";
import { Tool } from "@langchain/core/tools";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { BaseLLM } from "@langchain/core/language_models/llms";
export interface GoogleCalendarAgentParams {
credentials?: {
clientEmail?: string;
privateKey?: string;
calendarId?: string;
};
scopes?: string[];
model?: BaseLLM;
}
export class GoogleCalendarBase extends Tool {
name = "Google Calendar";
description =
"A tool to lookup Google Calendar events and create events in Google Calendar";
protected clientEmail: string;
protected privateKey: string;
protected calendarId: string;
protected scopes: string[];
protected llm: BaseLLM;
constructor(
fields: GoogleCalendarAgentParams = {
credentials: {
clientEmail: getEnvironmentVariable("GOOGLE_CALENDAR_CLIENT_EMAIL"),
privateKey: getEnvironmentVariable("GOOGLE_CALENDAR_PRIVATE_KEY"),
calendarId: getEnvironmentVariable("GOOGLE_CALENDAR_CALENDAR_ID"),
},
scopes: [
"https://www.googleapis.com/auth/calendar",
"https://www.googleapis.com/auth/calendar.events",
],
}
) {
super(...arguments);
if (!fields.model) {
throw new Error("Missing llm instance to interact with Google Calendar");
}
if (!fields.credentials) {
throw new Error("Missing credentials to authenticate to Google Calendar");
}
if (!fields.credentials.clientEmail) {
throw new Error(
"Missing GOOGLE_CALENDAR_CLIENT_EMAIL to interact with Google Calendar"
);
}
if (!fields.credentials.privateKey) {
throw new Error(
"Missing GOOGLE_CALENDAR_PRIVATE_KEY to interact with Google Calendar"
);
}
if (!fields.credentials.calendarId) {
throw new Error(
"Missing GOOGLE_CALENDAR_CALENDAR_ID to interact with Google Calendar"
);
}
this.clientEmail = fields.credentials.clientEmail;
this.privateKey = fields.credentials.privateKey;
this.calendarId = fields.credentials.calendarId;
this.scopes = fields.scopes || [];
this.llm = fields.model;
}
getModel() {
return this.llm;
}
async getAuth() {
const auth = new google.auth.JWT(
this.clientEmail,
undefined,
this.privateKey,
this.scopes
);
return auth;
}
async _call(input: string) {
return input;
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar/prompts/view-events-prompt.ts
|
export const VIEW_EVENTS_PROMPT = `
Date format: YYYY-MM-DDThh:mm:ss+00:00
Based on this event description: 'View my events on Thursday',
output a json of the following parameters:
Today's datetime on UTC time 2023-05-02T10:00:00+00:00, it's Tuesday and timezone
of the user is -5, take into account the timezone of the user and today's date.
If the user is searching for events with a specific title, person or location, put it into the search_query parameter.
1. time_min
2. time_max
3. user_timezone
4. max_results
5. search_query
event_summary:
{{
"time_min": "2023-05-04T00:00:00-05:00",
"time_max": "2023-05-04T23:59:59-05:00",
"user_timezone": "America/New_York",
"max_results": 10,
"search_query": ""
}}
Date format: YYYY-MM-DDThh:mm:ss+00:00
Based on this event description: '{query}', output a json of the
following parameters:
Today's datetime on UTC time {date}, today it's {dayName} and timezone of the user {u_timezone},
take into account the timezone of the user and today's date.
If the user is searching for events with a specific title, person or location, put it into the search_query parameter.
1. time_min
2. time_max
3. user_timezone
4. max_results
5. search_query
event_summary:
`;
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar/prompts/create-event-prompt.ts
|
export const CREATE_EVENT_PROMPT = `
Date format: YYYY-MM-DDThh:mm:ss+00:00
Based on this event description: "Joey birthday tomorrow at 7 pm",
output a json of the following parameters:
Today's datetime on UTC time 2023-05-02T10:00:00+00:00, it's Tuesday and timezone
of the user is -5, take into account the timezone of the user and today's date.
1. event_summary
2. event_start_time
3. event_end_time
4. event_location
5. event_description
6. user_timezone
event_summary:
{{
"event_summary": "Joey birthday",
"event_start_time": "2023-05-03T19:00:00-05:00",
"event_end_time": "2023-05-03T20:00:00-05:00",
"event_location": "",
"event_description": "",
"user_timezone": "America/New_York"
}}
Date format: YYYY-MM-DDThh:mm:ss+00:00
Based on this event description: "Create a meeting for 5 pm on Saturday with Joey",
output a json of the following parameters:
Today's datetime on UTC time 2023-05-04T10:00:00+00:00, it's Thursday and timezone
of the user is -5, take into account the timezone of the user and today's date.
1. event_summary
2. event_start_time
3. event_end_time
4. event_location
5. event_description
6. user_timezone
event_summary:
{{
"event_summary": "Meeting with Joey",
"event_start_time": "2023-05-06T17:00:00-05:00",
"event_end_time": "2023-05-06T18:00:00-05:00",
"event_location": "",
"event_description": "",
"user_timezone": "America/New_York"
}}
Date format: YYYY-MM-DDThh:mm:ss+00:00
Based on this event description: "{query}", output a json of the
following parameters:
Today's datetime on UTC time {date}, it's {dayName} and timezone of the user {u_timezone},
take into account the timezone of the user and today's date.
1. event_summary
2. event_start_time
3. event_end_time
4. event_location
5. event_description
6. user_timezone
event_summary:
`;
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar/prompts/index.ts
|
export { CREATE_EVENT_PROMPT } from "./create-event-prompt.js";
export { VIEW_EVENTS_PROMPT } from "./view-events-prompt.js";
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar/utils/get-timezone-offset-in-hours.ts
|
const getTimezoneOffsetInHours = () => {
const offsetInMinutes = new Date().getTimezoneOffset();
const offsetInHours = -offsetInMinutes / 60;
return offsetInHours;
};
export { getTimezoneOffsetInHours };
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar/commands/run-create-events.ts
|
import { google, calendar_v3 } from "googleapis";
import type { JWT, GaxiosResponse } from "googleapis-common";
import { PromptTemplate } from "@langchain/core/prompts";
import { CallbackManagerForToolRun } from "@langchain/core/callbacks/manager";
import { BaseLLM } from "@langchain/core/language_models/llms";
import { StringOutputParser } from "@langchain/core/output_parsers";
import { CREATE_EVENT_PROMPT } from "../prompts/index.js";
import { getTimezoneOffsetInHours } from "../utils/get-timezone-offset-in-hours.js";
type CreateEventParams = {
eventSummary: string;
eventStartTime: string;
eventEndTime: string;
userTimezone: string;
eventLocation?: string;
eventDescription?: string;
};
const createEvent = async (
{
eventSummary,
eventStartTime,
eventEndTime,
userTimezone,
eventLocation = "",
eventDescription = "",
}: CreateEventParams,
calendarId: string,
auth: JWT
) => {
const calendar = google.calendar("v3");
const event = {
summary: eventSummary,
location: eventLocation,
description: eventDescription,
start: {
dateTime: eventStartTime,
timeZone: userTimezone,
},
end: {
dateTime: eventEndTime,
timeZone: userTimezone,
},
};
try {
const createdEvent = await calendar.events.insert({
auth,
calendarId,
requestBody: event,
});
return createdEvent;
} catch (error) {
return {
error: `An error occurred: ${error}`,
};
}
};
type RunCreateEventParams = {
calendarId: string;
auth: JWT;
model: BaseLLM;
};
const runCreateEvent = async (
query: string,
{ calendarId, auth, model }: RunCreateEventParams,
runManager?: CallbackManagerForToolRun
) => {
const prompt = new PromptTemplate({
template: CREATE_EVENT_PROMPT,
inputVariables: ["date", "query", "u_timezone", "dayName"],
});
const createEventChain = prompt.pipe(model).pipe(new StringOutputParser());
const date = new Date().toISOString();
const u_timezone = getTimezoneOffsetInHours();
const dayName = new Date().toLocaleString("en-us", { weekday: "long" });
const output = await createEventChain.invoke(
{
query,
date,
u_timezone,
dayName,
},
runManager?.getChild()
);
const loaded = JSON.parse(output);
const [
eventSummary,
eventStartTime,
eventEndTime,
eventLocation,
eventDescription,
userTimezone,
] = Object.values(loaded);
const event = await createEvent(
{
eventSummary,
eventStartTime,
eventEndTime,
userTimezone,
eventLocation,
eventDescription,
} as CreateEventParams,
calendarId,
auth
);
if (!(event as { error: string }).error) {
return `Event created successfully, details: event ${
(event as GaxiosResponse<calendar_v3.Schema$Event>).data.htmlLink
}`;
}
return `An error occurred creating the event: ${
(event as { error: string }).error
}`;
};
export { runCreateEvent };
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/google_calendar/commands/run-view-events.ts
|
import { calendar_v3 } from "googleapis";
import type { JWT } from "googleapis-common";
import { PromptTemplate } from "@langchain/core/prompts";
import { BaseLLM } from "@langchain/core/language_models/llms";
import { CallbackManagerForToolRun } from "@langchain/core/callbacks/manager";
import { StringOutputParser } from "@langchain/core/output_parsers";
import { VIEW_EVENTS_PROMPT } from "../prompts/index.js";
import { getTimezoneOffsetInHours } from "../utils/get-timezone-offset-in-hours.js";
type RunViewEventParams = {
calendarId: string;
auth: JWT;
model: BaseLLM;
};
const runViewEvents = async (
query: string,
{ model, auth, calendarId }: RunViewEventParams,
runManager?: CallbackManagerForToolRun
) => {
const calendar = new calendar_v3.Calendar({});
const prompt = new PromptTemplate({
template: VIEW_EVENTS_PROMPT,
inputVariables: ["date", "query", "u_timezone", "dayName"],
});
const viewEventsChain = prompt.pipe(model).pipe(new StringOutputParser());
const date = new Date().toISOString();
const u_timezone = getTimezoneOffsetInHours();
const dayName = new Date().toLocaleString("en-us", { weekday: "long" });
const output = await viewEventsChain.invoke(
{
query,
date,
u_timezone,
dayName,
},
runManager?.getChild()
);
const loaded = JSON.parse(output);
try {
const response = await calendar.events.list({
auth,
calendarId,
...loaded,
});
const curatedItems =
response.data && response.data.items
? response.data.items.map(
({
status,
summary,
description,
start,
end,
}: // eslint-disable-next-line @typescript-eslint/no-explicit-any
any) => ({
status,
summary,
description,
start,
end,
})
)
: [];
return `Result for the prompt "${query}": \n${JSON.stringify(
curatedItems,
null,
2
)}`;
} catch (error) {
return `An error occurred: ${error}`;
}
};
export { runViewEvents };
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/google_custom_search.int.test.ts
|
import { test } from "@jest/globals";
import { GoogleCustomSearch } from "../google_custom_search.js";
test.skip("GoogleCustomSearchTool", async () => {
const tool = new GoogleCustomSearch();
// @eslint-disable-next-line/@typescript-eslint/ban-ts-comment
// @ts-expect-error unused var
const result = await tool.invoke("What is Langchain?");
// console.log({ result });
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/google_calendar.test.ts
|
import { jest, expect, describe } from "@jest/globals";
import { LLM } from "@langchain/core/language_models/llms";
import {
GoogleCalendarCreateTool,
GoogleCalendarViewTool,
} from "../google_calendar/index.js";
jest.mock("googleapis", () => ({
google: {
auth: {
JWT: jest.fn().mockImplementation(() => ({})),
},
},
}));
jest.mock("@langchain/core/utils/env", () => ({
getEnvironmentVariable: () => "key",
}));
// jest.mock("../google_calendar/commands/run-create-events.js", () => ({
// runCreateEvent: jest.fn(),
// }));
// jest.mock("../google_calendar/commands/run-view-events.js", () => ({
// runViewEvents: jest.fn(),
// }));
class FakeLLM extends LLM {
_llmType() {
return "fake";
}
async _call(prompt: string): Promise<string> {
return prompt;
}
}
describe("GoogleCalendarCreateTool", () => {
it("should be setup with correct parameters", async () => {
const params = {
credentials: {
clientEmail: "test@email.com",
privateKey: "privateKey",
calendarId: "calendarId",
},
model: new FakeLLM({}),
};
const instance = new GoogleCalendarCreateTool(params);
expect(instance.name).toBe("google_calendar_create");
});
it("should throw an error if missing credentials", async () => {
const params = {
credentials: {},
model: new FakeLLM({}),
};
expect(() => new GoogleCalendarCreateTool(params)).toThrow(
"Missing GOOGLE_CALENDAR_CLIENT_EMAIL to interact with Google Calendar"
);
});
it("should throw an error if missing model", async () => {
const params = {
credentials: {
clientEmail: "test",
},
};
expect(() => new GoogleCalendarCreateTool(params)).toThrow(
"Missing llm instance to interact with Google Calendar"
);
});
});
describe("GoogleCalendarViewTool", () => {
it("should be setup with correct parameters", async () => {
const params = {
credentials: {
clientEmail: "test@email.com",
privateKey: "privateKey",
calendarId: "calendarId",
},
model: new FakeLLM({}),
};
const instance = new GoogleCalendarViewTool(params);
expect(instance.name).toBe("google_calendar_view");
});
it("should throw an error if missing credentials", async () => {
const params = {
credentials: {},
model: new FakeLLM({}),
};
expect(() => new GoogleCalendarViewTool(params)).toThrow(
"Missing GOOGLE_CALENDAR_CLIENT_EMAIL to interact with Google Calendar"
);
});
it("should throw an error if missing model", async () => {
const params = {
credentials: {
clientEmail: "test",
},
};
expect(() => new GoogleCalendarViewTool(params)).toThrow(
"Missing llm instance to interact with Google Calendar"
);
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/discord.int.test.ts
|
import { test } from "@jest/globals";
import {
DiscordGetMessagesTool,
DiscordChannelSearchTool,
DiscordSendMessagesTool,
DiscordGetGuildsTool,
DiscordGetTextChannelsTool,
} from "../discord.js";
test.skip("DiscordGetMessagesTool", async () => {
const tool = new DiscordGetMessagesTool();
const result = await tool.invoke("1153400523718938780");
// console.log(result);
expect(result).toBeTruthy();
expect(result).not.toEqual("Channel not found.");
expect(result).not.toEqual("Error getting messages.");
});
test.skip("DiscordGetGuildsTool", async () => {
const tool = new DiscordGetGuildsTool();
const result = await tool.invoke("");
// console.log(result);
expect(result).toBeTruthy();
expect(result).not.toEqual("Error getting guilds.");
});
test.skip("DiscordChannelSearchTool", async () => {
const tool = new DiscordChannelSearchTool();
const result = await tool.invoke("Test");
// console.log(result);
expect(result).toBeTruthy();
expect(result).not.toEqual("Error searching through channel.");
});
test.skip("DiscordGetTextChannelsTool", async () => {
const tool = new DiscordGetTextChannelsTool();
const result = await tool.invoke("1153400523718938775");
// console.log(result);
expect(result).toBeTruthy();
expect(result).not.toEqual("Error getting text channels.");
});
test.skip("DiscordSendMessagesTool", async () => {
const tool = new DiscordSendMessagesTool();
const result = await tool.invoke("test message from new code");
// console.log(result);
expect(result).toEqual("Message sent successfully.");
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/wolframalpha.test.ts
|
import { jest, afterEach, beforeEach, describe, expect } from "@jest/globals";
import { WolframAlphaTool } from "../wolframalpha.js";
const MOCK_APP_ID = "[MOCK_APP_ID]";
const QUERY_1 = "What is 2 + 2?";
const MOCK_ANSWER = "[MOCK_ANSWER]";
describe("wolfram alpha test suite", () => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let fetchMock: any;
beforeEach(() => {
fetchMock = jest.spyOn(global, "fetch").mockImplementation(
async () =>
({
text: () => Promise.resolve(MOCK_ANSWER),
} as Response)
);
});
afterEach(() => {
fetchMock.mockRestore();
});
test("test query parameters passed correctly", async () => {
const wolframAlpha = new WolframAlphaTool({
appid: MOCK_APP_ID,
});
await wolframAlpha._call(QUERY_1);
const [url] = fetchMock.mock.calls[0];
const parsedUrl = new URL(url);
const params = new URLSearchParams(parsedUrl.search);
expect(fetchMock).toBeCalledTimes(1);
expect(params.get("appid")).toBe(MOCK_APP_ID);
expect(params.get("input")).toBe(QUERY_1);
});
test("test answer retrieved", async () => {
const wolframAlpha = new WolframAlphaTool({
appid: MOCK_APP_ID,
});
const answer = await wolframAlpha._call(QUERY_1);
expect(answer).toBe(MOCK_ANSWER);
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/aiplugin.int.test.ts
|
import { test, expect } from "@jest/globals";
import { AIPluginTool } from "../aiplugin.js";
test("AIPluginTool", async () => {
const tool = await AIPluginTool.fromPluginUrl(
"https://www.klarna.com/.well-known/ai-plugin.json"
);
expect(await tool.invoke({})).toMatchInlineSnapshot(`
"Usage Guide: Assistant uses the Klarna plugin to get relevant product suggestions for any shopping or product discovery purpose. Assistant will reply with the following 3 paragraphs 1) Search Results 2) Product Comparison of the Search Results 3) Followup Questions. The first paragraph contains a list of the products with their attributes listed clearly and concisely as bullet points under the product, together with a link to the product and an explanation. Links will always be returned and should be shown to the user. The second paragraph compares the results returned in a summary sentence starting with "In summary". Assistant comparisons consider only the most important features of the products that will help them fit the users request, and each product mention is brief, short and concise. In the third paragraph assistant always asks helpful follow-up questions and end with a question mark. When assistant is asking a follow-up question, it uses it's product expertise to provide information pertaining to the subject of the user's request that may guide them in their search for the right product.
OpenAPI Spec in JSON or YAML format:
{"openapi":"3.0.1","info":{"version":"v0","title":"Open AI Klarna product Api"},"servers":[{"url":"https://www.klarna.com/us/shopping"}],"tags":[{"name":"open-ai-product-endpoint","description":"Open AI Product Endpoint. Query for products."}],"paths":{"/public/openai/v0/products":{"get":{"tags":["open-ai-product-endpoint"],"summary":"API for fetching Klarna product information","operationId":"productsUsingGET","parameters":[{"name":"countryCode","in":"query","description":"ISO 3166 country code with 2 characters based on the user location. Currently, only US, GB, DE, SE and DK are supported.","required":true,"schema":{"type":"string"}},{"name":"q","in":"query","description":"A precise query that matches one very small category or product that needs to be searched for to find the products the user is looking for. If the user explicitly stated what they want, use that as a query. The query is as specific as possible to the product name or category mentioned by the user in its singular form, and don't contain any clarifiers like latest, newest, cheapest, budget, premium, expensive or similar. The query is always taken from the latest topic, if there is a new topic a new query is started. If the user speaks another language than English, translate their request into English (example: translate fia med knuff to ludo board game)!","required":true,"schema":{"type":"string"}},{"name":"size","in":"query","description":"number of products returned","required":false,"schema":{"type":"integer"}},{"name":"min_price","in":"query","description":"(Optional) Minimum price in local currency for the product searched for. Either explicitly stated by the user or implicitly inferred from a combination of the user's request and the kind of product searched for.","required":false,"schema":{"type":"integer"}},{"name":"max_price","in":"query","description":"(Optional) Maximum price in local currency for the product searched for. Either explicitly stated by the user or implicitly inferred from a combination of the user's request and the kind of product searched for.","required":false,"schema":{"type":"integer"}}],"responses":{"200":{"description":"Products found","content":{"application/json":{"schema":{"$ref":"#/components/schemas/ProductResponse"}}}},"503":{"description":"one or more services are unavailable"}},"deprecated":false}}},"components":{"schemas":{"Product":{"type":"object","properties":{"attributes":{"type":"array","items":{"type":"string"}},"name":{"type":"string"},"price":{"type":"string"},"url":{"type":"string"}},"title":"Product"},"ProductResponse":{"type":"object","properties":{"products":{"type":"array","items":{"$ref":"#/components/schemas/Product"}}},"title":"ProductResponse"}}}}"
`);
expect(await tool.invoke({})).toMatch(/Usage Guide/);
expect(await tool.invoke("")).toMatch(/OpenAPI Spec/);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/searchapi.test.ts
|
import { test, expect } from "@jest/globals";
import { SearchApi } from "../searchapi.js";
describe("SearchApi test suite", () => {
class SearchApiUrlTester extends SearchApi {
testThisUrl(): string {
return this.buildUrl("Query");
}
}
test("Test default url", async () => {
const searchApi = new SearchApiUrlTester("ApiKey", {
hl: "en",
gl: "us",
});
expect(searchApi.testThisUrl()).toEqual(
"https://www.searchapi.io/api/v1/search?engine=google&api_key=ApiKey&hl=en&gl=us&q=Query"
);
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/brave_search.int.test.ts
|
import { test } from "@jest/globals";
import { BraveSearch } from "../brave_search.js";
test.skip("BraveSearchTool", async () => {
const tool = new BraveSearch();
// @eslint-disable-next-line/@typescript-eslint/ban-ts-comment
// @ts-expect-error unused var
const result = await tool.invoke("What is Langchain?");
// console.log({ result });
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/google_places.int.test.ts
|
import { expect, describe } from "@jest/globals";
import { GooglePlacesAPI } from "../google_places.js";
describe("GooglePlacesAPI", () => {
test("should be setup with correct parameters", async () => {
const instance = new GooglePlacesAPI();
expect(instance.name).toBe("google_places");
});
test("GooglePlacesAPI returns expected result for valid query", async () => {
const tool = new GooglePlacesAPI();
const result = await tool.invoke("EatonCenter");
expect(result).toContain("220 Yonge St");
expect(result).toContain("CF Toronto Eaton Centre");
});
test("GooglePlacesAPI returns '' for query on an non-existent place", async () => {
const tool = new GooglePlacesAPI();
const result = await tool.invoke("ihfwehnwfi");
expect(result).toContain("");
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/serpapi.test.ts
|
import { test, expect } from "@jest/globals";
import { SerpAPI } from "../serpapi.js";
describe("serp api test suite", () => {
class SerpApiUrlTester extends SerpAPI {
testThisUrl(): string {
return this.buildUrl("search", this.params, this.baseUrl);
}
}
test("Test default url", async () => {
const serpApi = new SerpApiUrlTester(
"Not a real key but constructor error if not set",
{
hl: "en",
gl: "us",
}
);
expect(serpApi.testThisUrl()).toEqual(
"https://serpapi.com/search?hl=en&gl=us"
);
});
test("Test override url", async () => {
const serpApiProxied = new SerpApiUrlTester(
"Not a real key but constructor error if not set",
{
gl: "us",
},
"https://totallyProxied.com"
);
expect(
serpApiProxied.testThisUrl() === "https://totallyProxied.com/search?gl=us"
);
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/wikipedia.int.test.ts
|
import { test, expect } from "@jest/globals";
import { WikipediaQueryRun } from "../wikipedia_query_run.js";
test.skip("WikipediaQueryRunTool returns a string for valid query", async () => {
const tool = new WikipediaQueryRun();
const result = await tool.invoke("Langchain");
expect(typeof result).toBe("string");
});
test.skip("WikipediaQueryRunTool returns non-empty string for valid query", async () => {
const tool = new WikipediaQueryRun();
const result = await tool.invoke("Langchain");
// console.log(result);
expect(result).not.toBe("");
});
test.skip("WikipediaQueryRunTool returns 'No good Wikipedia Search Result was found' for bad query", async () => {
const tool = new WikipediaQueryRun();
const result = await tool.invoke("kjdsfklfjskladjflkdsajflkadsjf");
// console.log(result);
expect(result).toBe("No good Wikipedia Search Result was found");
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/gmail.test.ts
|
import { jest, expect, describe } from "@jest/globals";
import { GmailGetMessage } from "../gmail/index.js";
jest.mock("googleapis", () => ({
google: {
auth: {
JWT: jest.fn().mockImplementation(() => ({})),
},
},
}));
describe("GmailBaseTool using GmailGetMessage", () => {
it("should be setup with correct parameters", async () => {
const params = {
credentials: {
clientEmail: "test@email.com",
privateKey: "privateKey",
},
scopes: ["gmail_scope1"],
};
const instance = new GmailGetMessage(params);
expect(instance.name).toBe("gmail_get_message");
});
it("should throw an error if both privateKey and keyfile are missing", async () => {
const params = {
credentials: {},
scopes: ["gmail_scope1"],
};
expect(() => new GmailGetMessage(params)).toThrow();
});
it("should throw error with only client_email", async () => {
const params = {
credentials: {
clientEmail: "client_email",
},
};
expect(() => new GmailGetMessage(params)).toThrow();
});
it("should throw error with only private_key", async () => {
const params = {
credentials: {
privateKey: "privateKey",
},
};
expect(() => new GmailGetMessage(params)).toThrow();
});
it("should throw error with only keyfile", async () => {
const params = {
credentials: {
keyfile: "keyfile",
},
};
expect(() => new GmailGetMessage(params)).toThrow();
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/google_routes.int.test.ts
|
import { describe, expect } from "@jest/globals";
import { GoogleRoutesAPI } from "../google_routes.js";
describe.skip("GooglePlacesAPI", () => {
test("should be setup with correct parameters", async () => {
const instance = new GoogleRoutesAPI();
expect(instance.name).toBe("google_routes");
});
test("GooglePlacesAPI returns expected result for valid query", async () => {
const tool = new GoogleRoutesAPI();
const result = await tool.invoke({
origin: "Big Ben, London, UK",
destination: "Buckingham Palace, London, UK",
travel_mode: "WALK",
computeAlternativeRoutes: false,
});
expect(result).toContain("Birdcage Walk");
});
test("GoogleRoutesAPI returns 'Invalid route. The route may be too long or impossible to travel by the selected mode of transport.' for route on an non-existent place or one that is too far", async () => {
const tool = new GoogleRoutesAPI();
const result = await tool.invoke({
origin: "Sao Paulo, Brazil",
destination: "New York, USA",
travel_mode: "DRIVE",
computeAlternativeRoutes: false,
});
expect(result).toContain(
"Invalid route. The route may be too long or impossible to travel by the selected mode of transport."
);
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/aws_lambda.test.ts
|
import { test, jest, expect } from "@jest/globals";
import LambdaClient from "@aws-sdk/client-lambda";
import { AWSLambda } from "../aws_lambda.js";
jest.mock("@aws-sdk/client-lambda", () => ({
LambdaClient: jest.fn().mockImplementation(() => ({
send: jest.fn().mockImplementation(() =>
Promise.resolve({
Payload: new TextEncoder().encode(
JSON.stringify({ body: "email sent." })
),
})
),
})),
InvokeCommand: jest.fn().mockImplementation(() => ({})),
}));
test("AWSLambda invokes the correct lambda function and returns the response.body contents", async () => {
if (!LambdaClient) {
// this is to avoid a linting error. S3Client is mocked above.
}
const lambda = new AWSLambda({
name: "email-sender",
description:
"Sends an email with the specified content to holtkam2@gmail.com",
region: "us-east-1",
accessKeyId: "abc123",
secretAccessKey: "xyz456/1T+PzUZ2fd",
functionName: "testFunction1",
});
const result = await lambda.invoke("Hello world! This is an email.");
expect(result).toBe("email sent.");
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/tests/stackexchange.int.test.ts
|
import { test, expect } from "@jest/globals";
import { StackExchangeAPI } from "../stackexchange.js";
test("StackAPITool returns a string for valid query", async () => {
const tool = new StackExchangeAPI();
const result = await tool.invoke("zsh: command not found: python");
expect(typeof result).not.toBe("hello");
});
test("StackAPITool returns non-empty string for valid query", async () => {
const tool = new StackExchangeAPI({
queryType: "title",
});
const result = await tool.invoke("zsh: command not found: python");
expect(result).toContain("zsh: command not found: python");
});
test("StackAPITool returns 'No relevant results found for 'sjefbsmnazdkhbazkbdoaencopebfoubaef' on Stack Overflow for bad query", async () => {
const tool = new StackExchangeAPI();
const result = await tool.invoke("sjefbsmnazdkhbazkbdoaencopebfoubaef");
expect(result).toBe(
"No relevant results found for 'sjefbsmnazdkhbazkbdoaencopebfoubaef' on Stack Overflow."
);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools
|
lc_public_repos/langchainjs/libs/langchain-community/src/tools/fixtures/wordoftheday.html
|
<!DOCTYPE html>
<html lang="en">
<!--<!
[endif]--><head>
<script type="text/javascript" src="https://ats.rlcdn.com/ats.js"></script>
<script
type="text/javascript"
async=""
src="https://d9.flashtalking.com/d9core"
></script>
<script
type="text/javascript"
async=""
src="https://collector.brandmetrics.com/c.js?siteid=f9816ecc-b51b-4747-bc3e-1ea86a0677a2&toploc=www.merriam-webster.com&rnd=3183516"
></script>
<script
async=""
src="//cdn.confiant-integrations.net/gptprebidnative/202210130953/wrap.js"
></script>
<script
type="text/javascript"
src="https://cdn.brandmetrics.com/tag/aa466d868b2742ffa2cc31bb6341dc12/cafemedia.js"
></script>
<script
type="text/javascript"
src="https://cdn.confiant-integrations.net/mOinGM9MTu5v-Lto835XLhlrSPY/gpt_and_prebid/config.js"
></script>
<script
type="text/javascript"
src="https://sb.scorecardresearch.com/beacon.js"
></script>
<script
async=""
src="https://www.clarity.ms/eus-c/s/0.7.6/clarity.js"
></script>
<script
type="text/javascript"
async=""
src="https://www.google-analytics.com/analytics.js"
></script>
<script
type="text/javascript"
async=""
src="https://www.googletagmanager.com/gtag/js?id=G-M7RZHNRRPK&l=dataLayer&cx=c"
></script>
<script
type="text/javascript"
async=""
src="https://www.googletagmanager.com/gtag/js?id=UA-296234-25&l=dataLayer&cx=c"
></script>
<script
async=""
src="https://www.clarity.ms/tag/fq2f5zdaqe?ref=gtm2"
></script>
<script src="https://ads.adthrive.com/builds/customizations/61575e8e934c48ea554b3caa.js"></script>
<script src="https://ads.adthrive.com/builds/core/16dfc7b/es2018/js/adthrive.min.js?deployment=2023-04-10-5:16dfc7b:con&experiments=rubiconFloors,recencyFrequency,ttdSync&siteid=61575e8e934c48ea554b3caa"></script>
<script src="https://ads.adthrive.com/builds/core/16dfc7b/vendor/prebid/es2018/prebid.min.js"></script>
<script src="https://securepubads.g.doubleclick.net/tag/js/gpt.js"></script>
<script src="https://c.amazon-adsystem.com/aax2/apstag.js"></script>
<script
async=""
src="https://www.googletagmanager.com/gtm.js?id=GTM-WW4KHXF"
></script>
<script
async=""
src="https://ads.adthrive.com/sites/61575e8e934c48ea554b3caa/ads.min.js?referrer=https%3A%2F%2Fwww.merriam-webster.com%2Fword-of-the-day&threshold=26"
></script>
<script>
(function (w, d) {
w.adthrive = w.adthrive || {};
w.adthrive.cmd = w.adthrive.cmd || [];
w.adthrive.plugin = "adthrive-ads-1.0.40-manual";
w.adthrive.host = "ads.adthrive.com";
w.adthrive.threshold = Math.floor(Math.random() * 100 + 1);
var s = d.createElement("script");
s.async = true;
s.referrerpolicy = "no-referrer-when-downgrade";
s.src =
"https://" +
w.adthrive.host +
"/sites/61575e8e934c48ea554b3caa/ads.min.js?referrer=" +
w.encodeURIComponent(w.location.href) +
"&threshold=" +
w.adthrive.threshold;
var n = d.getElementsByTagName("script")[0];
n.parentNode.insertBefore(s, n);
})(window, document);
</script>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="referrer" content="unsafe-url" />
<meta property="fb:app_id" content="178450008855735" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Word of the Day: Foible | Merriam-Webster</title>
<meta
name="description"
content="Build your vocabulary: get a new word every day from Merriam-Webster dictionary. Learn the meaning, history, and fun facts about Foible. Also available as podcast, newsletter, and on the finest social networks."
/>
<link
rel="canonical"
href="https://www.merriam-webster.com/word-of-the-day"
/>
<link
rel="search"
type="application/opensearchdescription+xml"
href="/opensearch/dictionary.xml"
title="Merriam-Webster Dictionary"
/>
<meta property="og:title" content="Word of the Day: Foible" />
<meta
property="og:image"
content="https://merriam-webster.com/assets/mw/word-of-the-day/social/471a560aab5d63a4f7a330e3bc6175cc.jpg"
/>
<meta
property="og:url"
content="https://www.merriam-webster.com/word-of-the-day/foible-2023-04-10"
/>
<meta
property="og:description"
content="Many word lovers agree that the pen is mightier than the sword. But be they honed in wit or form, even the sharpest tools in the shed have their flaws. That’s where foible comes in handy. Borrowed"
/>
<meta property="og:type" content="article" />
<meta name="twitter:title" content="Word of the Day: Foible" />
<meta
name="twitter:image"
content="https://merriam-webster.com/assets/mw/word-of-the-day/social/471a560aab5d63a4f7a330e3bc6175cc.jpg"
/>
<meta
name="twitter:url"
content="https://www.merriam-webster.com/word-of-the-day/foible-2023-04-10"
/>
<meta
name="twitter:description"
content="Many word lovers agree that the pen is mightier than the sword. But be they honed in wit or form, even the sharpest tools in the shed have their flaws. That’s where foible comes in handy. Borrowed"
/>
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:site" content="@MerriamWebster" />
<link rel="icon" href="/favicon.svg" />
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#305f7a" />
<link rel="apple-touch-icon" sizes="144x144" href="/apple-touch-icon.png" />
<link rel="manifest" href="/site.webmanifest" />
<meta name="msapplication-TileColor" content="#2b5797" />
<meta name="theme-color" content="#ffffff" />
<script type="text/javascript">
window.mwdata = {};
window.mwdata.importModules = [];
window.mwdata.assetsDomain1 = "https://merriam-webster.com/assets";
window.mwdata.assetsDomain2 = "https://merriam-webster.com/assets";
window.mwdata.assetsDomain3 = "https://media2.merriam-webster.com";
window.mwdata.pronsDomain = "https://media.merriam-webster.com";
window.mwdata.ssoDomainFront = "https://sso.merriam-webster.com";
window.mwdata.svgPath =
"/dist-cross-dungarees/2023-04-05_15-17-24-b38e9d74";
window.mwdata.env = "production";
window.mwdata.jwkey = "zw1JPzyqv2DcY1xJTZncAt9HKaUKLEztLQFMqw==";
window.mwdata.isHome = false;
window.disableAllAds = true;
window.mwdata.statusRefreshTime = 600;
window.mwdata.fbAppId = "178450008855735";
window.mwdata.fbSdkReady = false;
window.mwdata.fbSdkQueue = [];
window.mwdata.gaSiteId = "UA-296234-25";
window.mwdata.gaNoTrackOnLoad = false;
window.mwdata.gaSpecialTracking = null;
window.mwdata.gaSpecialTrackingWord = null;
window.mwdata.gatReady = false;
window.mwdata.gatQueue = [];
window.mwdata.gaExperimentId = "";
window.mwdata.tagsPrepped = [];
window.mwdata.dfpSvcUp = false;
window.mwdata.search = "";
window.mwdata.cat = "";
window.mwdata.contentType1 = null;
window.mwdata.contentType2 = null;
window.mwdata.contentType3 = null;
window.mwdata.taxon = null;
window.mwdata.userSearch = "";
window.mwdata.partialMatch = false;
window.mwdata.partialURL = location.pathname;
window.mwdata.jwPlayerPath =
window.mwdata.assetsDomain2 + "/mw/jwplayer-8.10.3/";
// No variables?
window.mwdata.canonicalURL =
"https://www.merriam-webster.com/word-of-the-day";
</script>
<!-- Google Tag Manager -->
<script>
(function (w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({ "gtm.start": new Date().getTime(), event: "gtm.js" });
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != "dataLayer" ? "&l=" + l : "";
j.async = true;
j.src = "https://www.googletagmanager.com/gtm.js?id=" + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, "script", "dataLayer", "GTM-WW4KHXF");
</script>
<!-- End Google Tag Manager -->
<script
async=""
src="https://www.googletagmanager.com/gtag/js?id=UA-296234-25"
></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag() {
dataLayer.push(arguments);
}
gtag("js", new Date());
// Caution: If you send manual pageviews without disabling pageview measurement, you may end up with pageviews counted twice.
// source: https://developers.google.com/analytics/devguides/collection/gtagjs/pages
gtag("config", "UA-296234-25", {
send_page_view: false,
});
</script>
<script>
(function (i, r) {
i["GoogleAnalyticsObject"] = r;
(i[r] =
i[r] ||
function () {
(i[r].q = i[r].q || []).push(arguments);
}),
(i[r].l = 1 * new Date());
})(window, "ga");
</script>
<script type="text/javascript">
window.googletag = window.googletag || { cmd: [] };
googletag.cmd.push(function () {
googletag.pubads().setTagForChildDirectedTreatment(0);
googletag.pubads().setTagForUnderAgeOfConsent(0);
});
</script>
<link
rel="stylesheet"
as="style"
onload="this.onload=null;this.rel='stylesheet'"
href="https://fonts.googleapis.com/css?family=Lato:300,300i,400,700,900|Open+Sans:300,300i,400,400i,600,600i,700,700i|Playfair+Display:400,700"
/>
<script>
!(function (t) {
"use strict";
t.loadCSS || (t.loadCSS = function () {});
var e = (loadCSS.relpreload = {});
if (
((e.support = (function () {
var e;
try {
e = t.document.createElement("link").relList.supports("preload");
} catch (t) {
e = !1;
}
return function () {
return e;
};
})()),
(e.bindMediaToggle = function (t) {
var e = t.media || "all";
function a() {
t.media = e;
}
t.addEventListener
? t.addEventListener("load", a)
: t.attachEvent && t.attachEvent("onload", a),
setTimeout(function () {
(t.rel = "stylesheet"), (t.media = "only x");
}),
setTimeout(a, 3e3);
}),
(e.poly = function () {
if (!e.support())
for (
var a = t.document.getElementsByTagName("link"), n = 0;
n < a.length;
n++
) {
var o = a[n];
"preload" !== o.rel ||
"style" !== o.getAttribute("as") ||
o.getAttribute("data-loadcss") ||
(o.setAttribute("data-loadcss", !0), e.bindMediaToggle(o));
}
}),
!e.support())
) {
e.poly();
var a = t.setInterval(e.poly, 500);
t.addEventListener
? t.addEventListener("load", function () {
e.poly(), t.clearInterval(a);
})
: t.attachEvent &&
t.attachEvent("onload", function () {
e.poly(), t.clearInterval(a);
});
}
"undefined" != typeof exports
? (exports.loadCSS = loadCSS)
: (t.loadCSS = loadCSS);
})("undefined" != typeof global ? global : this);
</script>
<link
rel="stylesheet"
href="/dist-cross-dungarees/2023-04-05_15-17-24-b38e9d74/compiled/css/style-word-of-the-day.3ca2a9f1d50c2f5d303f.css"
media="screen"
/>
<link
rel="alternate"
type="application/rss+xml"
title="Word of the Day"
href="https://www.merriam-webster.com/wotd/feed/rss2"
/>
<script
async=""
src="https://www.googleoptimize.com/optimize.js?id=OPT-N8CP5K8"
></script>
<style type="text/css">
img[onload^="SVGInject("] {
visibility: hidden;
}
</style>
<style type="text/css">
.adthrive-ad {
margin-top: 10px;
margin-bottom: 10px;
text-align: center;
overflow-x: visible;
clear: both;
line-height: 0;
}
</style>
<script
id="funnel-relay-installer"
data-customer-id="merriamwebster_6e5b0_merriamwebster"
data-property-id="PROPERTY_ID"
data-autorun="true"
async="true"
src="https://cdn-magiclinks.trackonomics.net/client/static/v2/merriamwebster_6e5b0_merriamwebster.js"
></script>
<meta
http-equiv="origin-trial"
content="A0VQgOQvA+kwCj319NCwgf8+syUgEQ8/LLpB8RxxlRC3AkJ9xx8IAvVuQ/dcwy0ok7sGKufLLu6WhsXbQR9/UwwAAACFeyJvcmlnaW4iOiJodHRwczovL2RvdWJsZWNsaWNrLm5ldDo0NDMiLCJmZWF0dXJlIjoiUHJpdmFjeVNhbmRib3hBZHNBUElzIiwiZXhwaXJ5IjoxNjg4MDgzMTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ=="
/>
<meta
http-equiv="origin-trial"
content="A6kRo9zXJhOvsR4D/VeZ9CiApPAxnOGzBkW88d8eIt9ex2oOzlX+AoUk/BS50Y9Ysy2jwyHR49Mb7XwP+l9yygIAAACLeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXN5bmRpY2F0aW9uLmNvbTo0NDMiLCJmZWF0dXJlIjoiUHJpdmFjeVNhbmRib3hBZHNBUElzIiwiZXhwaXJ5IjoxNjg4MDgzMTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ=="
/>
<meta
http-equiv="origin-trial"
content="A3mbHZoS4VJtJ8j1aE8+Z9vaGf/oMV1eTNIWMrvGqWgNnOmvaxnRGliqKIZU2eiTzCj5Qpz8B1/UTTLuony5bAAAAACLeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXRhZ3NlcnZpY2VzLmNvbTo0NDMiLCJmZWF0dXJlIjoiUHJpdmFjeVNhbmRib3hBZHNBUElzIiwiZXhwaXJ5IjoxNjg4MDgzMTk5LCJpc1N1YmRvbWFpbiI6dHJ1ZSwiaXNUaGlyZFBhcnR5Ijp0cnVlfQ=="
/>
<meta
http-equiv="origin-trial"
content="As0hBNJ8h++fNYlkq8cTye2qDLyom8NddByiVytXGGD0YVE+2CEuTCpqXMDxdhOMILKoaiaYifwEvCRlJ/9GcQ8AAAB8eyJvcmlnaW4iOiJodHRwczovL2RvdWJsZWNsaWNrLm5ldDo0NDMiLCJmZWF0dXJlIjoiV2ViVmlld1hSZXF1ZXN0ZWRXaXRoRGVwcmVjYXRpb24iLCJleHBpcnkiOjE3MTk1MzI3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="
/>
<meta
http-equiv="origin-trial"
content="AgRYsXo24ypxC89CJanC+JgEmraCCBebKl8ZmG7Tj5oJNx0cmH0NtNRZs3NB5ubhpbX/bIt7l2zJOSyO64NGmwMAAACCeyJvcmlnaW4iOiJodHRwczovL2dvb2dsZXN5bmRpY2F0aW9uLmNvbTo0NDMiLCJmZWF0dXJlIjoiV2ViVmlld1hSZXF1ZXN0ZWRXaXRoRGVwcmVjYXRpb24iLCJleHBpcnkiOjE3MTk1MzI3OTksImlzU3ViZG9tYWluIjp0cnVlfQ=="
/>
<script
src="https://securepubads.g.doubleclick.net/pagead/managed/js/gpt/m202304050101/pubads_impl.js?cb=31073646"
async=""
></script>
<style type="text/css">
.adthrive-ccpa-modal {
background-color: #000;
background-color: rgba(0, 0, 0, 0.4);
display: none;
height: 100%;
left: 0;
overflow: auto;
position: fixed;
top: 0;
width: 100%;
z-index: 2147483647;
}
.adthrive-ccpa-modal-content {
background-color: #fefefe;
border: 1px solid #888;
border-radius: 10px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
font-family: Verdana, Geneva, Tahoma, sans-serif;
margin: 0 auto;
max-width: 592px;
padding: 20px 24px 24px;
position: relative;
top: 50%;
transform: translateY(-50%);
width: 80%;
}
#adthrive-ccpa-modal-title {
color: rgba(0, 0, 0, 0.87);
font-size: 20px;
line-height: 26px;
}
.adthrive-ccpa-modal-btn:focus,
.adthrive-ccpa-modal-btn:hover {
color: #000;
cursor: pointer;
text-decoration: none;
}
#adthrive-ccpa-modal-language {
color: rgba(0, 0, 0, 0.87);
display: block;
font-size: 14px;
line-height: 20px;
margin: 16px 0 32px;
}
#adthrive-ccpa-modal-cancel-btn:focus,
#adthrive-ccpa-modal-cancel-btn:hover,
#adthrive-ccpa-modal-close-btn-container:focus,
#adthrive-ccpa-modal-close-btn-container:hover {
color: rgba(0, 0, 0, 0.8);
cursor: pointer;
text-decoration: none;
}
#adthrive-ccpa-modal-continue-btn:focus,
#adthrive-ccpa-modal-continue-btn:hover {
color: hsla(0, 0%, 100%, 0.8);
cursor: pointer;
text-decoration: none;
}
#adthrive-ccpa-modal-close-btn-container {
color: #000;
font-size: 20px;
font-weight: 700;
line-height: 20px;
position: absolute;
right: 8px;
top: 8px;
}
.adthrive-ccpa-lower-buttons-container {
color: #000;
font-size: 18px;
}
#adthrive-ccpa-modal-cancel-btn {
display: inline-block;
text-align: left;
width: calc(100% - 150px);
}
#adthrive-ccpa-modal-continue-btn {
background-color: #010044;
border-radius: 10px;
color: #fff;
display: inline-block;
height: 44px;
line-height: 44px;
text-align: center;
width: 150px;
}
@media screen and (max-width: 896px) {
.adthrive-ccpa-modal-content {
margin: 0 auto;
position: relative;
width: calc(100% - 80px);
}
#adthrive-ccpa-modal-title {
font-size: 16px;
line-height: 24px;
}
#adthrive-ccpa-modal-language {
font-size: 12px;
line-height: 16px;
text-align: left;
}
.adthrive-ccpa-lower-buttons-container {
font-size: 14px;
}
#adthrive-ccpa-modal-close-btn-container {
font-size: 14px;
line-height: 14px;
}
}
@media screen and (max-width: 350px) {
#adthrive-ccpa-modal-title {
font-size: 14px;
line-height: 24px;
}
#adthrive-ccpa-modal-language {
font-size: 10px;
line-height: 14px;
text-align: left;
}
.adthrive-ccpa-lower-buttons-container {
display: block;
font-size: 12px;
text-align: center;
width: 100%;
}
#adthrive-ccpa-modal-close-btn-container {
display: block;
font-size: 12px;
line-height: 12px;
}
#adthrive-ccpa-modal-cancel-btn,
#adthrive-ccpa-modal-continue-btn {
display: block;
text-align: center;
width: 100%;
}
#adthrive-ccpa-modal-cancel-btn {
margin-bottom: 10px;
}
}
</style>
<style type="text/css">
.adthrive-ad {
clear: both;
line-height: 0;
margin-bottom: 10px;
margin-top: 10px;
overflow-x: visible;
text-align: center;
}
.adthrive-ad-cls {
align-items: center;
display: flex;
flex-wrap: wrap;
justify-content: center;
}
.adthrive-ad-cls > div,
.adthrive-ad-cls > iframe {
flex-basis: 100%;
}
.adthrive-interstitial {
margin-bottom: 0;
margin-top: 0;
}
.adthrive-native-recipe {
display: inline-block;
}
.adthrive-recipe {
min-width: 300px;
}
.adthrive-stuck.adthrive-sticky.adthrive-header,
.adthrive-stuck.adthrive-sticky.adthrive-sidebar {
position: fixed;
top: 0;
z-index: 9999;
}
.adthrive-stuck.adthrive-header {
margin-top: 0;
}
.adthrive-sticky.adthrive-footer {
background-color: hsla(0, 0%, 100%, 0.8);
border-top: 2px solid hsla(0, 0%, 88%, 0.8);
bottom: 0;
box-sizing: content-box;
left: 0;
margin: 0;
max-height: 100px;
overflow: hidden;
position: fixed;
text-align: center;
width: 100%;
z-index: 1000001;
}
.adthrive-sticky.adthrive-footer > .adthrive-close {
background: #fff;
border: 1px solid #b2b2b2;
border-radius: 20px;
color: #b2b2b2;
cursor: pointer;
display: inline-block;
font-family: arial, sans-serif;
font-size: 20px;
line-height: 20px;
padding: 0 5px;
position: absolute;
right: 5px;
top: 5px;
}
.adthrive-device-desktop
.adthrive-sticky.adthrive-footer
> .adthrive-close {
right: 10px;
top: 10px;
}
.adthrive-ccpa-link,
.adthrive-footer-message,
.adthrive-privacy-preferences {
margin-top: 5px;
text-align: center;
}
#next-video,
#stay-video {
background-color: #333;
color: #fff;
cursor: pointer;
height: 40px;
line-height: 40px;
margin: 10px;
opacity: 0.9;
text-align: center;
width: 100px;
}
#next-video {
box-shadow: inset 0 0 0 0 #333;
transition: box-shadow 5s linear;
}
#next-stay-container.loaded #next-video {
box-shadow: inset 100px 0 0 0 red;
}
.jw-flag-small-player #next-video,
.jw-flag-small-player #stay-video {
height: 30px;
line-height: 30px;
width: 75px;
}
#next-stay-container {
bottom: 25%;
margin: 12px;
position: absolute;
right: 0;
}
.jw-flag-small-player #next-stay-container {
margin: 0;
}
.video-box-shadow {
box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
}
.adthrive-wrapper-bar {
background-color: #595959;
border-top-left-radius: 5px;
border-top-right-radius: 5px;
display: none;
font-family: Arial, Helvetica, sans-serif;
height: 36px;
}
.adthrive-video-title {
color: #fff;
font-size: 13px;
font-weight: 700;
text-decoration: none;
}
.adthrive-wrapper-title-wrapper {
align-items: center;
display: inline-flex;
justify-content: center;
margin-left: 10px;
margin-right: 10px;
min-width: 0;
}
.adthrive-wrapper-title-wrapper > a > svg,
.adthrive-wrapper-title-wrapper > div > svg {
fill: #fff;
margin-right: 5px;
vertical-align: middle;
}
.adthrive-wrapper-title-wrapper > a {
text-decoration: none;
}
.adthrive-video-text-cutoff {
color: #fff;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.adthrive-collapse-player {
border-bottom: 1px solid #dbdbdb;
border-top: 1px solid #dbdbdb;
margin-left: auto;
margin-right: auto;
padding: 8px !important;
width: 90%;
}
.adthrive-player-position.adthrive-collapse-float {
position: fixed;
width: 300px;
z-index: 2147483644;
}
.adthrive-player-position.adthrive-collapse-float.adthrive-collapse-right {
right: 5px;
top: 0;
}
.adthrive-player-position.adthrive-collapse-float.adthrive-collapse-bottom-right {
bottom: 100px;
right: 5px;
}
.adthrive-player-position.adthrive-collapse-float.adthrive-collapse-bottom-left {
bottom: 100px;
left: 5px;
}
.adthrive-player-position.adthrive-collapse-float
> .adthrive-player-title {
display: none;
}
.adthrive-player-position.adthrive-collapse-sticky {
padding-bottom: 20px;
padding-top: 20px;
position: fixed;
z-index: 9999;
}
.adthrive-player-position.adthrive-collapse-sticky
> .adthrive-player-title {
display: none;
}
.adthrive-collapse-mobile-background {
background-color: #000;
left: 0;
position: fixed;
top: 0;
z-index: 99990;
}
.adthrive-top-collapse-close {
left: -30px;
position: fixed;
top: 5px;
z-index: 1;
}
.adthrive-top-collapse-wrapper-bar > * .adthrive-top-collapse-close {
left: 0;
position: relative;
top: 0;
}
.adthrive-top-collapse-wrapper-bar > * .adthrive-wrapper-float-close {
display: none;
float: none;
margin-bottom: 0;
}
.adthrive-player-position.adthrive-collapse-mobile {
position: fixed;
width: 300px;
z-index: 99998;
}
.adthrive-player-position.adthrive-collapse-mobile.adthrive-collapse-medium,
.adthrive-player-position.adthrive-collapse-mobile.adthrive-collapse-small {
width: 272px;
}
.adthrive-player-position.adthrive-collapse-mobile.adthrive-collapse-top-right {
right: 10px;
top: 26px;
}
.adthrive-player-position.adthrive-collapse-mobile.adthrive-collapse-top-left {
left: 5px;
top: 26px;
}
.adthrive-player-position.adthrive-collapse-mobile.adthrive-collapse-bottom-left {
bottom: 52px;
left: 5px;
}
.adthrive-player-position.adthrive-collapse-mobile.adthrive-collapse-bottom-right {
bottom: 52px;
right: 10px;
}
.adthrive-player-position.adthrive-collapse-mobile
> .adthrive-player-title {
display: none;
}
.adthrive-player-position.adthrive-collapse-mobile.adthrive-collapse-top-center
> .adthrive-wrapper-bar {
display: none !important;
}
.adthrive-player-position.adthrive-collapse-mobile.adthrive-collapse-top-center
> .adthrive-top-collapse-wrapper-bar {
display: block;
}
.adthrive-player-position.adthrive-collapse-mobile.adthrive-collapse-top-center.adthrive-player-without-wrapper-text {
left: 50%;
padding-bottom: 5px;
padding-top: 5px;
top: 0;
transform: translateX(-50%);
}
.adthrive-player-position.adthrive-collapse-mobile.adthrive-collapse-top-center.adthrive-player-with-wrapper-text {
padding-bottom: 5px;
padding-top: 5px;
right: 5px;
top: 0;
}
.adthrive-top-collapse-wrapper-bar {
color: #fff;
display: none;
left: 5px;
padding-bottom: 5px;
padding-top: 5px;
position: fixed;
top: 0;
width: -webkit-calc(100% - 282px);
width: -moz-calc(100% - 282px);
width: calc(100% - 282px);
z-index: 99998;
}
.adthrive-top-collapse-wrapper-video-title {
-webkit-line-clamp: 3;
line-clamp: 3;
-webkit-box-orient: vertical;
color: #fff;
display: -webkit-box;
font-size: 13px;
font-weight: 700;
line-height: 1.2;
overflow: hidden;
text-decoration: none;
text-overflow: ellipsis;
}
.adthrive-top-collapse-wrapper-bar a a.adthrive-learn-more-link {
color: #fff;
display: inline-block;
font-size: 13px;
line-height: 1.2;
}
h3.adthrive-player-title {
margin: 10px 0;
}
.adthrive-wrapper-close {
align-items: center;
color: #fff;
font-size: 36px;
height: 36px;
justify-content: center;
margin-left: auto;
margin-right: 0;
min-width: 36px;
}
.adthrive-wrapper-float-close {
cursor: pointer;
display: none;
float: right;
margin-bottom: 5px;
}
.adthrive-top-left-outer {
height: 78px;
left: -30px;
position: absolute;
top: -55px;
width: 78px;
}
.adthrive-top-left-outer > svg {
bottom: 30px;
left: 30px;
position: absolute;
}
.adthrive-top-left-inner {
position: absolute;
top: 0;
}
.adthrive-top-left-inner-wrapper.adthrive-wrapper-float-close,
.adthrive-top-left-inner.adthrive-wrapper-float-close {
background: rgba(0, 0, 0, 0.5);
color: #fff;
padding: 2px;
pointer-events: none;
width: 100%;
z-index: 99;
}
.adthrive-top-left-inner-wrapper.adthrive-wrapper-float-close {
position: absolute;
top: 36px;
}
.adthrive-sticky-outstream > .adthrive-wrapper-float-close {
position: absolute;
right: 1px;
top: 32px;
}
.adthrive-sticky-outstream
> .adthrive-wrapper-float-close.adthrive-wrapper-close-outside-left {
left: 2px;
}
.adthrive-sticky-outstream
> .adthrive-wrapper-float-close.adthrive-wrapper-close-bkgd-50 {
background: rgba(0, 0, 0, 0.5);
color: #fff;
left: 0;
padding: 2px;
pointer-events: none;
top: 52px;
}
.adthrive-wrapper-close-bkgd-50 > #adthrive-sticky-outstream-close {
padding: 2px 0 0 2px;
pointer-events: all;
}
.adthrive-sticky-outstream {
display: none;
overflow: hidden;
padding-top: 20px;
position: fixed;
z-index: 2147483644;
}
.adthrive-sticky-outstream.adthrive-sticky-outstream-mobile {
bottom: 52px;
right: 10px;
}
.adthrive-sticky-outstream.adthrive-sticky-outstream-desktop {
bottom: 100px;
right: 5px;
}
.adthrive-sticky-outstream.adthrive-sticky-outstream-active {
display: block;
}
.adthrive-video-stickyoutstream div:first-of-type {
margin: -1px;
}
.adthrive-instream-close {
pointer-events: all;
}
.adthrive-instream-close.adthrive-float-left {
float: left;
}
.adthrive-ccpa-link,
.adthrive-ccpa-link span,
.adthrive-footer-message span,
.adthrive-privacy-preferences a {
color: #a9a9a9;
font-family: Arial, Helvetica Neue, Helvetica, sans-serif;
font-size: 13px;
}
.adthrive-ccpa-link a {
cursor: pointer;
text-decoration: underline;
}
.adthrive-device-phone .adthrive-footer-message {
margin-bottom: 60px;
}
.adthrive-footer-message {
margin-bottom: 100px;
}
.adthrive-footer-message > span {
border-top: 1px solid #b2b2b2;
padding-top: 5px;
text-transform: uppercase;
}
#_inv_voicefive___ {
display: none;
}
</style>
<link
rel="stylesheet"
type="text/css"
href="https://ads.adthrive.com/sites/61575e8e934c48ea554b3caa/ads.min.css"
/>
<script src="//cdn.id5-sync.com/api/1.0/id5-api.js"></script>
<iframe name="adreporter" style="display: none"></iframe>
<link
rel="preload"
href="https://adservice.google.com/adsid/integrator.js?domain=www.merriam-webster.com"
as="script"
/>
<script
type="text/javascript"
src="https://adservice.google.com/adsid/integrator.js?domain=www.merriam-webster.com"
></script>
<link
rel="preload"
href="https://adservice.google.com/adsid/integrator.js?domain=www.merriam-webster.com"
as="script"
/>
<script
type="text/javascript"
src="https://adservice.google.com/adsid/integrator.js?domain=www.merriam-webster.com"
></script>
<link
rel="preload"
href="https://adservice.google.com/adsid/integrator.js?domain=www.merriam-webster.com"
as="script"
/>
<script
type="text/javascript"
src="https://adservice.google.com/adsid/integrator.js?domain=www.merriam-webster.com"
></script>
</head>
<body
class="no-touch wod-article-page cross-dungarees-lite adthrive-device-tablet"
>
<script>
document.body.classList.add("cross-dungarees-lite");
</script>
<!-- Google Tag Manager (noscript) -->
<noscript
><iframe
src="https://www.googletagmanager.com/ns.html?id=GTM-WW4KHXF"
height="0"
width="0"
style="display: none; visibility: hidden"
></iframe
></noscript>
<!-- End Google Tag Manager (noscript) -->
<div class="outer-container">
<div class="main-container">
<header class="top-header position-fixed w-100 shrinkheader">
<nav class="navbar container-xxl">
<a
href="/"
class="navbar-brand d-flex"
title="Merriam Webster - established 1828"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="100%"
height="100%"
viewBox="0 0 41 42"
fill="none"
class="svg replaced-svg"
>
<title>Merriam-Webster Logo</title>
<path
d="M0 20.5291C0 9.20443 9.20999 0.0291138 20.5723 0.0291138C31.9347 0.0291138 41 9.20881 41 20.5291C41 31.8538 31.9347 41.0291 20.5723 41.0291C9.21437 41.0335 0 31.8538 0 20.5291Z"
fill="white"
></path>
<path
d="M1.5 20.5269C1.5 10.0337 10.009 1.52911 20.5022 1.52911C30.9954 1.52911 39.5 10.0337 39.5 20.5269C39.5 31.0202 30.9954 39.5248 20.5022 39.5291C10.009 39.5291 1.50433 31.0202 1.5 20.5269ZM2.74342 20.5269C2.74342 25.4313 4.73201 29.8677 7.9467 33.0824C11.1614 36.2971 15.5978 38.2814 20.5022 38.2857C25.4065 38.2857 29.8429 36.2971 33.0576 33.0824C36.2723 29.8677 38.2609 25.4313 38.2609 20.5269C38.2609 15.6226 36.2723 11.1862 33.0576 7.97148C29.8429 4.7568 25.4065 2.7682 20.5022 2.7682C15.5935 2.7682 11.1614 4.75246 7.9467 7.97148C4.73201 11.1862 2.74342 15.6226 2.74342 20.5269Z"
fill="#D71920"
></path>
<path
d="M22.58 25.1859C22.58 24.7011 22.9294 24.4041 23.3355 24.3997C23.8946 24.3997 24.1654 24.8321 24.1654 25.3999L24.4667 25.4174L24.5017 24.5439H24.4842L24.4973 24.5308C24.1523 24.2207 23.7636 24.1377 23.3224 24.1377C22.6367 24.1377 21.9991 24.6094 21.9991 25.4086C22.0078 27.0683 24.161 26.3564 24.1435 27.4875C24.1435 28.0073 23.816 28.3785 23.3093 28.3785H23.2875C22.6498 28.3654 22.2524 27.8413 22.2349 27.1556L21.8986 27.1381V27.1556L21.9074 27.2386L21.9947 28.3916C22.3834 28.6144 22.8114 28.6711 23.2264 28.6711C24.0212 28.6711 24.8161 28.23 24.8161 27.2692C24.803 25.6794 22.5581 26.1424 22.58 25.1859ZM19.9114 24.1813C19.7717 24.1813 19.6406 24.2076 19.5009 24.225L18.7715 24.688L18.8763 24.7753C19.0729 24.7142 19.2694 24.6792 19.4572 24.6792C20.4705 24.6792 20.9203 25.6226 20.9247 26.5791C20.9247 27.5705 20.4923 28.4091 19.597 28.4091C19.0117 28.4091 18.658 28.0029 18.658 27.4177V21.6045L18.4789 21.5259C18.112 21.6875 17.6665 21.8316 17.256 21.884L17.2472 22.05C17.5137 22.0675 17.7058 22.1112 17.9373 22.2247L17.9198 26.863C17.9198 27.0726 17.9198 27.2779 17.9198 27.4875C17.9198 27.8588 17.9155 28.23 17.8893 28.6187L18.0552 28.7104L18.3915 28.3873C18.6711 28.5532 19.0205 28.6842 19.3393 28.6886C20.9247 28.6842 21.6104 27.5487 21.6104 26.3171C21.6104 24.9195 20.9858 24.1813 19.9114 24.1813ZM14.8757 22.5479L14.8888 22.3208L12.7662 22.3033L12.7487 22.5304L13.5785 22.7532L13.4563 23.1069L12.0674 27.0333C11.9145 26.5791 10.779 23.1506 10.7004 22.858L10.8052 22.692L11.4953 22.5872L11.5084 22.3383L9.21542 22.3252V22.3426H9.19795V22.5741L9.82687 22.7182L9.94042 22.9279C9.86181 23.2205 8.67385 26.6009 8.51225 27.0508L7.13649 22.7663L7.1758 22.7532L7.84402 22.5872L7.8746 22.3383H7.85713H7.77414L5.48994 22.3164L5.46811 22.5479L6.28483 22.7488L8.16722 28.6973L8.45547 28.7104L10.1719 23.9804L11.7617 28.6842L12.0674 28.6973L14.1463 22.7401L14.8757 22.5479ZM7.12339 22.775L7.18016 22.9497L7.12339 22.775ZM13.5829 22.7401L13.5305 22.727L13.5829 22.7401ZM27.5807 27.6841L27.5545 27.7059C27.358 27.9025 27.0523 28.2082 26.8077 28.2082C26.3404 28.1994 26.1613 27.8763 26.1569 27.291C26.1569 27.2648 26.1569 27.2386 26.1569 27.2124V24.8802H26.1875L27.4279 24.8976L27.4454 24.4652L26.1395 24.4478L26.1569 23.3341L25.9342 23.3166C25.7551 23.9411 25.2616 24.308 24.7812 24.6574L24.7724 24.8802H24.7899V24.8976H25.4101L25.3926 27.5705C25.3926 28.4047 25.9298 28.7061 26.4146 28.7104C26.4321 28.7104 26.4539 28.7104 26.4714 28.7104C27.1571 28.6755 27.6244 27.9942 27.6288 27.9942L27.5851 27.7147L27.5807 27.6841ZM25.2922 20.0628H25.314C25.8337 20.0497 26.253 19.8532 26.6505 19.5431L26.6286 20.0715C26.6286 20.0715 26.633 20.0715 26.6374 20.0715H26.6461C26.6461 20.0715 26.6592 20.0672 26.6636 20.0672C26.8252 20.0497 27.6594 19.8619 28.035 19.792L28.0612 19.7876L27.9301 19.5867L27.3231 19.5256V16.9182C27.3231 16.1626 26.9955 15.822 26.467 15.822C26.4408 15.822 26.419 15.822 26.3928 15.822C26.3185 15.822 26.2399 15.8263 26.1657 15.8656L25.2092 16.4378C25.1131 16.4989 24.7681 16.6867 24.755 16.8527L24.7244 17.3287L24.7899 17.3812L25.2878 17.2807C25.349 17.2676 25.4407 17.272 25.4407 17.1671V17.154C25.4363 17.0711 25.4319 16.9924 25.4319 16.9182C25.4363 16.5863 25.5106 16.3373 26.1133 16.25C26.1351 16.2456 26.1569 16.2456 26.1788 16.2456C26.4801 16.2456 26.6592 16.5644 26.6592 17.1803V17.8092C26.2487 17.9358 25.7988 18.1149 25.3184 18.2721C24.9559 18.39 24.3925 18.5647 24.3925 19.2854C24.3925 19.6129 24.7812 20.0628 25.2922 20.0628ZM26.6461 20.0541H26.6417L26.6505 19.9274L26.6461 20.0541ZM26.6767 18.0232V18.0275C26.5981 18.0538 26.5282 18.0756 26.4539 18.0974C26.5282 18.0712 26.5981 18.0494 26.6767 18.0232ZM26.6767 18.0406V18.3202L26.6592 19.2548C26.4015 19.4164 25.9997 19.6217 25.7639 19.6217C25.445 19.6217 25.1175 19.3989 25.1175 19.1063C25.1131 18.5298 25.7289 18.3638 26.6767 18.0406ZM23.2264 14.7956C23.4273 14.7956 23.6151 14.634 23.6194 14.4156C23.6194 14.1929 23.4535 13.992 23.2264 13.9876C23.008 13.9876 22.8507 14.206 22.8507 14.4156C22.8507 14.6165 23.0342 14.7956 23.2264 14.7956ZM22.9425 19.6872L22.1651 19.8139L22.1519 20.0235L24.3837 20.041V20.0235H24.4012V19.8313L23.6238 19.6697L23.6369 15.9268L23.4709 15.8482C23.1259 16.001 22.6411 16.1364 22.2568 16.1888L22.2393 16.3985C22.4882 16.4159 22.7372 16.4596 22.9556 16.5688L22.9425 19.6872ZM16.7756 19.6566L16.0287 19.7833L16.0156 20.0279L18.2212 20.0453L18.2387 19.8008L17.4787 19.6392L17.4918 17.5471C17.4918 17.403 17.8849 16.4378 18.3435 16.4378C18.4439 16.4378 18.5881 16.512 18.6754 16.5775L18.9025 16.5994L19.0641 16.0272C18.9156 15.9006 18.575 15.8787 18.3959 15.8787C17.9417 15.8831 17.8063 16.4028 17.6272 16.7479L17.5137 16.9313V15.9311L17.3128 15.8525L17.3084 15.87L17.2997 15.8525C16.9634 16.0054 16.4655 16.1408 16.0724 16.1932L16.0549 16.4028C16.3126 16.4203 16.5659 16.464 16.7843 16.5732L16.7756 19.6566ZM7.05788 19.7964L6.27609 19.6348L6.71284 14.9179L6.75215 14.8L8.85292 19.8706L8.97084 19.8794L11.0148 14.8524L11.0716 14.9572L11.4734 19.6479L10.6349 19.7745L10.6218 20.0191L13.0282 20.0366L13.0457 19.792L12.3163 19.6304L11.7922 14.4244L12.6133 14.2977L12.609 14.2802H12.6264L12.6177 14.0706L10.8314 14.0531L9.04509 18.3944L7.23258 14.0619L5.41133 14.0531L5.38512 14.2802L6.27609 14.4462L5.77383 19.6523L5.08377 19.7789L5.07066 20.0235L7.04041 20.041L7.05788 19.7964ZM34.5644 17.2021C34.5687 16.3504 34.1364 15.87 33.2323 15.8438C33.2279 15.8438 33.2236 15.8438 33.2192 15.8438C33.11 15.8438 32.9353 15.8875 32.6907 16.0796L32.0574 16.6212C31.8303 16.1932 31.3979 15.8569 30.8913 15.8525C30.5594 15.8525 30.4371 15.8962 30.175 16.1015L29.5723 16.4946V15.9224L29.3758 15.8438C29.0395 15.9967 28.5634 16.1321 28.1878 16.1845L28.1704 16.3461C28.4149 16.3635 28.6595 16.4072 28.8692 16.5164L28.8648 19.6392L28.2053 19.7658L28.1922 19.9886L30.2318 20.006L30.2493 19.8051L29.5636 19.6217L29.5767 16.8221C29.8781 16.595 30.2187 16.3199 30.5769 16.3199C31.3412 16.3199 31.3586 17.0929 31.363 17.7786V19.6392L30.7035 19.7876L30.6904 19.9886L32.73 20.006L32.7475 19.8051L32.0618 19.6217L32.0749 16.8134C32.3675 16.5994 32.7606 16.3723 33.1231 16.3723C33.8132 16.3723 33.8568 16.9531 33.8612 17.569C33.8612 17.6738 33.8612 17.7742 33.8612 17.8791V19.6392L33.2017 19.7876L33.1886 19.9886L35.1977 20.006L35.2151 19.8051L34.56 19.6217L34.5644 17.2021ZM14.4564 20.137C14.8801 20.137 15.1771 20.0803 15.2426 20.041L16.2384 19.0059L15.9588 18.984C15.6356 19.3203 15.3212 19.6042 14.8626 19.6042C14.8408 19.6042 14.8189 19.6042 14.7971 19.6042C13.4999 19.5256 13.3209 18.5473 13.3165 17.4292H13.3427L15.5963 17.4467C15.8453 17.4467 15.9457 17.4161 15.9457 17.0885C15.9457 16.3592 15.3212 15.8525 14.452 15.8525C13.4257 15.8525 12.6002 16.6212 12.6002 17.9839C12.6046 19.3684 13.4213 20.1327 14.4564 20.137ZM14.3341 16.1058C14.9587 16.1058 15.2251 16.5513 15.2251 17.1278C15.2251 17.1584 15.2251 17.1934 15.2251 17.2283L13.3383 17.2108C13.382 16.6649 13.7489 16.1058 14.3341 16.1058ZM22.1869 16.0229C22.0384 15.8962 21.6977 15.8744 21.5187 15.8744C21.0644 15.8787 20.929 16.3985 20.75 16.7435L20.6364 16.9269V15.9268L20.4355 15.8482L20.4312 15.8656L20.4224 15.8482C20.0861 16.001 19.5882 16.1364 19.1952 16.1888L19.1821 16.3985C19.4397 16.4159 19.693 16.4596 19.9114 16.5688L19.9027 19.6566L19.1558 19.7833L19.1384 20.0235H19.1558H19.2126L21.344 20.041L21.3614 19.7964L20.6015 19.6348L20.619 17.5428C20.619 17.3986 21.012 16.4334 21.4663 16.4334C21.5667 16.4334 21.7108 16.5077 21.7982 16.5732L22.0253 16.595L22.1869 16.0229ZM32.8392 25.0723L32.7169 25.2689V24.2119L32.5029 24.1333L32.4986 24.1508L32.4898 24.1333C32.136 24.2949 31.6163 24.439 31.2014 24.4914L31.1839 24.7142C31.4547 24.7317 31.7211 24.7753 31.9482 24.8933L31.9395 28.1383L31.1534 28.2737L31.1403 28.527L33.455 28.5445L33.4725 28.2912L32.6776 28.1208L32.6907 25.9196C32.6907 25.7711 33.1013 24.7535 33.5861 24.7535C33.6909 24.7535 33.8437 24.8321 33.9355 24.902L34.1713 24.9238L34.3416 24.3211C34.1888 24.1901 33.8263 24.1682 33.6428 24.1682C33.1711 24.1595 33.0314 24.7098 32.8392 25.0723ZM16.0418 28.1339C16.0156 28.1339 15.9938 28.1339 15.9719 28.1339C14.6005 28.051 14.4127 27.0159 14.4084 25.8366L16.8192 25.8541C17.0813 25.8541 17.1861 25.8192 17.1861 25.4741C17.1861 24.7055 16.5266 24.1682 15.6138 24.1682C14.5307 24.1726 13.6615 24.9806 13.6572 26.4175C13.6615 27.8806 14.5219 28.693 15.6138 28.693C16.0637 28.693 16.3737 28.6318 16.4436 28.5925L17.4962 27.5007L17.2036 27.4744C16.8585 27.8369 16.5266 28.1339 16.0418 28.1339ZM15.4828 24.4434C16.1423 24.4434 16.4262 24.9151 16.4262 25.5265C16.4262 25.5615 16.4262 25.5964 16.4262 25.6314L14.4302 25.6139C14.4783 25.0286 14.8626 24.4434 15.4828 24.4434ZM31.2014 27.4482C30.8607 27.8064 30.5288 28.1034 30.044 28.1034C30.0178 28.1034 29.996 28.1034 29.9698 28.1034C28.5984 28.0204 28.4106 26.9853 28.4062 25.8061L30.8171 25.8235C31.0791 25.8235 31.1839 25.7886 31.1839 25.4436C31.1839 24.6749 30.5244 24.1377 29.6116 24.1377C28.5285 24.142 27.655 24.95 27.655 26.3869C27.655 27.8544 28.5198 28.6624 29.6116 28.6624C30.0571 28.6624 30.3716 28.6013 30.4415 28.562L31.494 27.4701L31.2014 27.4482ZM29.485 24.4128C30.1445 24.4128 30.4284 24.8845 30.4284 25.496C30.4284 25.5309 30.4284 25.5658 30.424 25.6008L28.428 25.5833C28.4805 25.0024 28.8692 24.4128 29.485 24.4128ZM35.1802 17.7044V18.294H36.7831V17.7044H35.1802Z"
fill="#004990"
></path>
</svg>
</a>
<a
href="javascript:void(0);"
class="navbar-close"
aria-label="Close Search"
>
<div class="chevron-left-circle">
<svg
width="7"
height="12"
viewBox="0 0 7 12"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M0.667825 5.58964L5.76148 0.488749C6.05802 0.210202 6.51157 0.210202 6.79067 0.488749C7.06978 0.767297 7.06978 1.23734 6.79067 1.51589L2.2029 6.09451L6.79067 10.6731C7.06978 10.9691 7.06978 11.4217 6.79067 11.7003C6.51157 11.9788 6.05802 11.9788 5.76148 11.7003L0.667824 6.61678C0.38872 6.32083 0.38872 5.86819 0.667825 5.58964Z"
fill="#97BECE"
></path>
</svg>
</div>
</a>
<div
class="search-form-container d-flex col rounded flex-wrap flex-lg-nowrap me-xl-2"
>
<div class="w-100 button-switcher-container order-lg-1 order-2">
<div class="button-switcher rounded">
<button
id="mw-search-toggle"
class="btn btn-toggle rounded"
role="switch"
data-toggle="button"
autocomplete="off"
data-search-url="/dictionary"
title="Toggle Search Dictionary/Thesaurus"
>
<div class="btn-switch"></div>
</button>
</div>
</div>
<div
class="search-container d-flex col rounded order-lg-2 order-1 flex-fill"
>
<form
id="search-form"
class="d-flex w-100 position-relative search-form"
autocomplete="off"
novalidate=""
action="/dictionary"
>
<input
id="search-term"
class="form-control rounded border-dark search"
type="search"
placeholder="Search Dictionary"
aria-label="Search"
value=""
autocomplete="off"
spellcheck="false"
autocorrect="off"
autocapitalize="off"
/>
<button
class="btn position-absolute close-button"
title="close"
aria-label="Close Search"
type="reset"
>
<svg
width="12"
height="13"
viewBox="0 0 12 13"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M7.42616 6.5L11.7046 10.7785C12.0985 11.1723 12.0985 11.8108 11.7046 12.2046C11.3108 12.5985 10.6723 12.5985 10.2785 12.2046L6 7.92616L1.72153 12.2046C1.3277 12.5985 0.68919 12.5985 0.295367 12.2046C-0.0984557 11.8108 -0.0984557 11.1723 0.295367 10.7785L4.57384 6.5L0.295367 2.22153C-0.0984557 1.8277 -0.0984557 1.18919 0.295367 0.795367C0.68919 0.401544 1.3277 0.401544 1.72153 0.795367L6 5.07384L10.2785 0.795367C10.6723 0.401544 11.3108 0.401544 11.7046 0.795367C12.0985 1.18919 12.0985 1.8277 11.7046 2.22153L7.42616 6.5Z"
fill="#97BECE"
></path>
</svg>
</button>
<button
class="btn position-absolute search-button search-dictionary"
title="Search"
aria-label="Search Word"
type="submit"
>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="19px"
height="21px"
viewBox="0 0 26 29"
version="1.1"
class="svg replaced-svg"
>
<g
class="Search"
stroke="none"
stroke-width="1"
fill="none"
fill-rule="evenodd"
>
<g
class="g-search-icon"
transform="translate(1.000000, 1.000000)"
fill="#fff"
fill-rule="nonzero"
>
<path
d="M17.5185815,17.4073633 L24.5896493,24.4784311 C24.9801736,24.8689554 24.9801736,25.5021204 24.5896493,25.8926447 L23.1754357,27.3068582 C22.7849114,27.6973825 22.1517464,27.6973825 21.7612221,27.3068582 L14.6901543,20.2357904 C14.29963,19.8452661 14.29963,19.2121011 14.6901543,18.8215769 L16.1043679,17.4073633 C16.4948922,17.016839 17.1280572,17.016839 17.5185815,17.4073633 Z M10.5,21 C4.70101013,21 0,16.2989899 0,10.5 C0,4.70101013 4.70101013,0 10.5,0 C16.2989899,0 21,4.70101013 21,10.5 C21,16.2989899 16.2989899,21 10.5,21 Z M10.5,18 C14.6421356,18 18,14.6421356 18,10.5 C18,6.35786438 14.6421356,3 10.5,3 C6.35786438,3 3,6.35786438 3,10.5 C3,14.6421356 6.35786438,18 10.5,18 Z"
class="Oval"
></path>
</g>
</g>
</svg>
</button>
</form>
<div
class="search-results-auto overflow-auto collapse shadow mt-3 rounded"
></div>
</div>
</div>
<button
class="navbar-toggler"
type="button"
aria-expanded="false"
aria-label="Toggle navigation"
>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="24px"
height="20px"
viewBox="0 0 24 20"
version="1.1"
class="svg replaced-svg"
>
<title>Menu Toggle</title>
<g
id="Menu"
stroke="none"
stroke-width="1"
fill="none"
fill-rule="evenodd"
>
<rect
class="menu-rec"
fill="#ffffff"
x="0"
y="0"
width="24"
height="3"
rx="1.5"
></rect>
<rect
class="menu-rec"
fill="#ffffff"
x="0"
y="16"
width="24"
height="3"
rx="1.5"
></rect>
<rect
class="menu-rec"
fill="#ffffff"
x="0"
y="8"
width="24"
height="3"
rx="1.5"
></rect>
</g>
</svg>
</button>
<div class="navigation-container order-md-4 p-2">
<a
href="javascript:void(0);"
class="btn-close btn-close-white btn-lg text-decoration-none d-lg-none text-white"
title="close menu"
aria-label="close menu"
>
</a>
<div class="navigation d-lg-flex">
<div
class="navigation-first-half d-flex flex-xl-row flexcolumn justify-content-center align-items-center text-center pb-4 p-lg-0 order-lg-2 row g-0"
>
<a
href="/"
class="text-decoration-none mt-4 mb-4 d-lg-none logo-mobile"
>
<svg
xmlns="http://www.w3.org/2000/svg"
width="82"
height="82"
viewBox="0 0 41 41"
fill="none"
class="svg menu-mob-logo replaced-svg"
>
<title>Merriam-Webster Logo</title>
<path
d="M1.5 20.4978C1.5 10.0046 10.009 1.5 20.5022 1.5C30.9954 1.5 39.5 10.0046 39.5 20.4978C39.5 30.9911 30.9954 39.4957 20.5022 39.5C10.009 39.5 1.50433 30.9911 1.5 20.4978ZM2.74342 20.4978C2.74342 25.4022 4.73201 29.8386 7.9467 33.0533C11.1614 36.268 15.5978 38.2523 20.5022 38.2566C25.4065 38.2566 29.8429 36.268 33.0576 33.0533C36.2723 29.8386 38.2609 25.4022 38.2609 20.4978C38.2609 15.5935 36.2723 11.1571 33.0576 7.94237C29.8429 4.72768 25.4065 2.73908 20.5022 2.73908C15.5935 2.73908 11.1614 4.72335 7.9467 7.94237C4.73201 11.1571 2.74342 15.5935 2.74342 20.4978Z"
fill="white"
></path>
<path
d="M22.58 25.1568C22.58 24.672 22.9294 24.375 23.3356 24.3706C23.8946 24.3706 24.1654 24.803 24.1654 25.3708L24.4667 25.3882L24.5017 24.5147H24.4842L24.4973 24.5016C24.1523 24.1915 23.7636 24.1086 23.3225 24.1086C22.6368 24.1086 21.9991 24.5803 21.9991 25.3795C22.0078 27.0392 24.161 26.3273 24.1435 27.4584C24.1435 27.9782 23.816 28.3494 23.3094 28.3494H23.2875C22.6499 28.3363 22.2524 27.8122 22.2349 27.1265L21.8986 27.109V27.1265L21.9074 27.2095L21.9947 28.3625C22.3834 28.5852 22.8115 28.642 23.2264 28.642C24.0213 28.642 24.8161 28.2009 24.8161 27.2401C24.803 25.6503 22.5581 26.1132 22.58 25.1568ZM19.9114 24.1522C19.7717 24.1522 19.6407 24.1784 19.5009 24.1959L18.7715 24.6589L18.8763 24.7462C19.0729 24.6851 19.2694 24.6501 19.4572 24.6501C20.4705 24.6501 20.9203 25.5935 20.9247 26.55C20.9247 27.5414 20.4923 28.38 19.597 28.38C19.0117 28.38 18.658 27.9738 18.658 27.3886V21.5754L18.4789 21.4968C18.112 21.6584 17.6665 21.8025 17.256 21.8549L17.2473 22.0209C17.5137 22.0384 17.7059 22.082 17.9373 22.1956L17.9199 26.8339C17.9199 27.0435 17.9199 27.2488 17.9199 27.4584C17.9199 27.8297 17.9155 28.2009 17.8893 28.5896L18.0553 28.6813L18.3915 28.3581C18.6711 28.5241 19.0205 28.6551 19.3393 28.6595C20.9247 28.6551 21.6104 27.5196 21.6104 26.2879C21.6104 24.8903 20.9858 24.1522 19.9114 24.1522ZM14.8757 22.5188L14.8888 22.2917L12.7662 22.2742L12.7487 22.5013L13.5786 22.7241L13.4563 23.0778L12.0674 27.0042C11.9145 26.55 10.779 23.1215 10.7004 22.8289L10.8052 22.6629L11.4953 22.5581L11.5084 22.3092L9.21544 22.2961V22.3135H9.19796V22.545L9.82688 22.6891L9.94044 22.8988C9.86182 23.1914 8.67386 26.5718 8.51227 27.0217L7.13651 22.7372L7.17581 22.7241L7.84404 22.5581L7.87461 22.3092H7.85714H7.77416L5.48996 22.2873L5.46812 22.5188L6.28484 22.7197L8.16724 28.6682L8.45549 28.6813L10.1719 23.9513L11.7617 28.6551L12.0674 28.6682L14.1463 22.711L14.8757 22.5188ZM7.1234 22.7459L7.18018 22.9206L7.1234 22.7459ZM13.5829 22.711L13.5305 22.6979L13.5829 22.711ZM27.5808 27.655L27.5546 27.6768C27.358 27.8733 27.0523 28.1791 26.8077 28.1791C26.3404 28.1703 26.1613 27.8471 26.157 27.2619C26.157 27.2357 26.157 27.2095 26.157 27.1833V24.851H26.1875L27.4279 24.8685L27.4454 24.4361L26.1395 24.4187L26.157 23.3049L25.9342 23.2875C25.7551 23.912 25.2616 24.2789 24.7812 24.6283L24.7725 24.851H24.7899V24.8685H25.4101L25.3926 27.5414C25.3926 28.3756 25.9298 28.677 26.4146 28.6813C26.4321 28.6813 26.4539 28.6813 26.4714 28.6813C27.1571 28.6464 27.6244 27.9651 27.6288 27.9651L27.5851 27.6855L27.5808 27.655ZM25.2922 20.0337H25.314C25.8338 20.0206 26.253 19.824 26.6505 19.514L26.6286 20.0424C26.6286 20.0424 26.633 20.0424 26.6374 20.0424H26.6461C26.6461 20.0424 26.6592 20.0381 26.6636 20.0381C26.8252 20.0206 27.6594 19.8328 28.035 19.7629L28.0612 19.7585L27.9302 19.5576L27.3231 19.4965V16.8891C27.3231 16.1335 26.9955 15.7928 26.4671 15.7928C26.4408 15.7928 26.419 15.7928 26.3928 15.7928C26.3186 15.7928 26.2399 15.7972 26.1657 15.8365L25.2092 16.4087C25.1131 16.4698 24.7681 16.6576 24.755 16.8236L24.7244 17.2996L24.7899 17.352L25.2878 17.2516C25.349 17.2385 25.4407 17.2429 25.4407 17.138V17.1249C25.4363 17.042 25.432 16.9633 25.432 16.8891C25.4363 16.5572 25.5106 16.3082 26.1133 16.2209C26.1351 16.2165 26.157 16.2165 26.1788 16.2165C26.4802 16.2165 26.6592 16.5353 26.6592 17.1511V17.7801C26.2487 17.9067 25.7988 18.0858 25.3184 18.243C24.9559 18.3609 24.3925 18.5356 24.3925 19.2563C24.3925 19.5838 24.7812 20.0337 25.2922 20.0337ZM26.6461 20.025H26.6418L26.6505 19.8983L26.6461 20.025ZM26.6767 17.9941V17.9984C26.5981 18.0246 26.5282 18.0465 26.4539 18.0683C26.5282 18.0421 26.5981 18.0203 26.6767 17.9941ZM26.6767 18.0115V18.2911L26.6592 19.2257C26.4015 19.3873 25.9997 19.5926 25.7639 19.5926C25.4451 19.5926 25.1175 19.3698 25.1175 19.0772C25.1131 18.5007 25.7289 18.3347 26.6767 18.0115ZM23.2264 14.7665C23.4273 14.7665 23.6151 14.6049 23.6194 14.3865C23.6194 14.1638 23.4535 13.9629 23.2264 13.9585C23.008 13.9585 22.8508 14.1769 22.8508 14.3865C22.8508 14.5874 23.0342 14.7665 23.2264 14.7665ZM22.9425 19.6581L22.1651 19.7847L22.152 19.9944L24.3838 20.0118V19.9944H24.4012V19.8022L23.6238 19.6406L23.6369 15.8977L23.4709 15.8191C23.1259 15.9719 22.6411 16.1073 22.2568 16.1597L22.2393 16.3694C22.4883 16.3868 22.7372 16.4305 22.9556 16.5397L22.9425 19.6581ZM16.7756 19.6275L16.0287 19.7542L16.0156 19.9987L18.2212 20.0162L18.2387 19.7716L17.4787 19.61L17.4918 17.518C17.4918 17.3739 17.8849 16.4087 18.3435 16.4087C18.444 16.4087 18.5881 16.4829 18.6754 16.5484L18.9025 16.5703L19.0641 15.9981C18.9156 15.8715 18.575 15.8496 18.3959 15.8496C17.9417 15.854 17.8063 16.3737 17.6272 16.7188L17.5137 16.9022V15.902L17.3128 15.8234L17.3084 15.8409L17.2997 15.8234C16.9634 15.9763 16.4655 16.1117 16.0724 16.1641L16.0549 16.3737C16.3126 16.3912 16.5659 16.4349 16.7843 16.5441L16.7756 19.6275ZM7.05789 19.7673L6.27611 19.6057L6.71286 14.8888L6.75217 14.7709L8.85293 19.8415L8.97085 19.8503L11.0148 14.8233L11.0716 14.9281L11.4734 19.6188L10.6349 19.7454L10.6218 19.99L13.0283 20.0075L13.0457 19.7629L12.3164 19.6013L11.7923 14.3952L12.6133 14.2686L12.609 14.2511H12.6265L12.6177 14.0415L10.8314 14.024L9.0451 18.3653L7.23259 14.0327L5.41134 14.024L5.38514 14.2511L6.27611 14.4171L5.77385 19.6231L5.08378 19.7498L5.07068 19.9944L7.04042 20.0118L7.05789 19.7673ZM34.5644 17.173C34.5688 16.3213 34.1364 15.8409 33.2323 15.8147C33.2279 15.8147 33.2236 15.8147 33.2192 15.8147C33.11 15.8147 32.9353 15.8584 32.6907 16.0505L32.0574 16.5921C31.8303 16.1641 31.398 15.8278 30.8913 15.8234C30.5594 15.8234 30.4371 15.8671 30.1751 16.0724L29.5723 16.4654V15.8933L29.3758 15.8147C29.0395 15.9675 28.5635 16.1029 28.1878 16.1553L28.1704 16.3169C28.415 16.3344 28.6595 16.3781 28.8692 16.4873L28.8648 19.61L28.2053 19.7367L28.1922 19.9594L30.2318 19.9769L30.2493 19.776L29.5636 19.5926L29.5767 16.793C29.8781 16.5659 30.2187 16.2907 30.5769 16.2907C31.3412 16.2907 31.3587 17.0638 31.363 17.7495V19.61L30.7035 19.7585L30.6904 19.9594L32.73 19.9769L32.7475 19.776L32.0618 19.5926L32.0749 16.7843C32.3675 16.5703 32.7606 16.3432 33.1231 16.3432C33.8132 16.3432 33.8569 16.924 33.8612 17.5398C33.8612 17.6447 33.8612 17.7451 33.8612 17.8499V19.61L33.2017 19.7585L33.1886 19.9594L35.1977 19.9769L35.2152 19.776L34.56 19.5926L34.5644 17.173ZM14.4564 20.1079C14.8801 20.1079 15.1771 20.0512 15.2426 20.0118L16.2384 18.9768L15.9589 18.9549C15.6357 19.2912 15.3212 19.5751 14.8626 19.5751C14.8408 19.5751 14.8189 19.5751 14.7971 19.5751C13.4999 19.4965 13.3209 18.5182 13.3165 17.4001H13.3427L15.5963 17.4176C15.8453 17.4176 15.9457 17.387 15.9457 17.0594C15.9457 16.33 15.3212 15.8234 14.4521 15.8234C13.4257 15.8234 12.6002 16.5921 12.6002 17.9548C12.6046 19.3393 13.4213 20.1036 14.4564 20.1079ZM14.3341 16.0767C14.9587 16.0767 15.2251 16.5222 15.2251 17.0987C15.2251 17.1293 15.2251 17.1642 15.2251 17.1992L13.3384 17.1817C13.382 16.6358 13.7489 16.0767 14.3341 16.0767ZM22.1869 15.9938C22.0384 15.8671 21.6977 15.8453 21.5187 15.8453C21.0645 15.8496 20.9291 16.3694 20.75 16.7144L20.6364 16.8978V15.8977L20.4355 15.8191L20.4312 15.8365L20.4224 15.8191C20.0861 15.9719 19.5882 16.1073 19.1952 16.1597L19.1821 16.3694C19.4397 16.3868 19.6931 16.4305 19.9114 16.5397L19.9027 19.6275L19.1559 19.7542L19.1384 19.9944H19.1559H19.2126L21.344 20.0118L21.3614 19.7673L20.6015 19.6057L20.619 17.5136C20.619 17.3695 21.012 16.4043 21.4663 16.4043C21.5667 16.4043 21.7108 16.4785 21.7982 16.5441L22.0253 16.5659L22.1869 15.9938ZM32.8392 25.0432L32.7169 25.2397V24.1828L32.5029 24.1042L32.4986 24.1217L32.4898 24.1042C32.1361 24.2658 31.6163 24.4099 31.2014 24.4623L31.184 24.6851C31.4547 24.7025 31.7212 24.7462 31.9483 24.8641L31.9395 28.1092L31.1534 28.2446L31.1403 28.4979L33.455 28.5154L33.4725 28.2621L32.6776 28.0917L32.6907 25.8905C32.6907 25.742 33.1013 24.7244 33.5861 24.7244C33.6909 24.7244 33.8438 24.803 33.9355 24.8729L34.1713 24.8947L34.3417 24.292C34.1888 24.161 33.8263 24.1391 33.6429 24.1391C33.1712 24.1304 33.0314 24.6807 32.8392 25.0432ZM16.0418 28.1048C16.0156 28.1048 15.9938 28.1048 15.972 28.1048C14.6006 28.0218 14.4128 26.9867 14.4084 25.8075L16.8192 25.825C17.0813 25.825 17.1861 25.79 17.1861 25.445C17.1861 24.6763 16.5266 24.1391 15.6138 24.1391C14.5307 24.1435 13.6615 24.9515 13.6572 26.3884C13.6615 27.8515 14.5219 28.6639 15.6138 28.6639C16.0637 28.6639 16.3738 28.6027 16.4436 28.5634L17.4962 27.4715L17.2036 27.4453C16.8586 27.8078 16.5266 28.1048 16.0418 28.1048ZM15.4828 24.4143C16.1423 24.4143 16.4262 24.886 16.4262 25.4974C16.4262 25.5324 16.4262 25.5673 16.4262 25.6022L14.4302 25.5848C14.4783 24.9995 14.8626 24.4143 15.4828 24.4143ZM31.2014 27.4191C30.8608 27.7773 30.5288 28.0743 30.044 28.0743C30.0178 28.0743 29.996 28.0743 29.9698 28.0743C28.5984 27.9913 28.4106 26.9562 28.4062 25.7769L30.8171 25.7944C31.0791 25.7944 31.184 25.7595 31.184 25.4144C31.184 24.6458 30.5245 24.1086 29.6117 24.1086C28.5285 24.1129 27.655 24.9209 27.655 26.3578C27.655 27.8253 28.5198 28.6333 29.6117 28.6333C30.0571 28.6333 30.3716 28.5721 30.4415 28.5328L31.494 27.441L31.2014 27.4191ZM29.485 24.3837C30.1445 24.3837 30.4284 24.8554 30.4284 25.4669C30.4284 25.5018 30.4284 25.5367 30.424 25.5717L28.4281 25.5542C28.4805 24.9733 28.8692 24.3837 29.485 24.3837ZM35.1802 17.6752V18.2649H36.7831V17.6752H35.1802Z"
fill="white"
></path>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M20.5 40.7616C31.6902 40.7616 40.7616 31.6902 40.7616 20.5C40.7616 9.30981 31.6902 0.238372 20.5 0.238372C9.30981 0.238372 0.238372 9.30981 0.238372 20.5C0.238372 31.6902 9.30981 40.7616 20.5 40.7616ZM20.5 41C31.8218 41 41 31.8218 41 20.5C41 9.17816 31.8218 0 20.5 0C9.17816 0 0 9.17816 0 20.5C0 31.8218 9.17816 41 20.5 41Z"
fill="white"
></path>
</svg>
</a>
<div class="d-flex d-lg-none col-6">
<div class="h5 fw-bold loggedin-links text-white text-left">
Hello,
<div class="mw-username pt-2 text-truncate">Username</div>
</div>
</div>
<div
class="loggedout-links d-flex justify-content-evenly ps-4 pe-4 p-lg-0 align-items-center mt-1 mt-lg-0"
>
<a
class="btn btn-gradient text-white btn-md active text-decoration-none mr-1 mr-lg-3 me-1 me-lg-3 d-lg-none d-xl-none d-xxl-inline"
rel="nofollow"
href="/login"
>
Log In
</a>
<a
class="btn btn-gradient text-white btn-md active text-decoration-none ms-lg-3 d-lg-none"
rel="nofollow"
href="/register"
>
Sign Up
</a>
</div>
<div class="d-none d-xxl-flex">
<ul class="loggedin-links">
<li class="dropdown">
<a
id="mw-global-nav-login-links"
href="javascript:void(0);"
class="text-white text-decoration-none btn btn-blue parent dropdown-toggle mw-username-container d-flex justify-content-between align-items-center"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<span
class="mw-username text-truncate d-inline-block"
style="max-width: 75px"
>Username
</span>
<span class="active-arrow">
<div class="arrow-up"></div>
</span>
</a>
<ul
aria-labelledby="mw-global-nav-login-links"
class="dropdown-menu menu-list-items submenu flex-column rounded shadow-sm"
>
<li class="loggedin-links">
<a
rel="nofollow"
href="/saved-words"
class="d-flex justify-content-between w-100 rounded"
>
<span>My Words</span>
</a>
</li>
<li>
<a
rel="nofollow"
href="/recents"
class="d-flex justify-content-between rounded"
>
<span>Recents</span>
</a>
</li>
<li>
<a
rel="nofollow"
href="/settings"
class="d-flex justify-content-between rounded"
>
<span>Settings</span>
</a>
</li>
<li>
<a
rel="nofollow"
href="/logout"
class="ul-sign-out d-flex justify-content-between rounded"
>
<span>Log Out</span>
</a>
</li>
</ul>
</li>
</ul>
</div>
</div>
<ul
class="navigation-second-half d-flex flex-column flex-lg-row justify-content-start align-items-lg-center order-lg-1 p-0"
>
<li
class="position-relative d-flex me-xl-2 justify-content-between flex-column flex-lg-row"
>
<a
id="mw-global-nav-games-quizzes"
class="w-100 text-white text-decoration-none btn btn-blue"
href="/games"
>Games & Quizzes</a
>
</li>
<li
class="position-relative d-flex me-xl-2 justify-content-between flex-column flex-lg-row"
>
<a
id="mw-global-nav-thesaurus"
class="w-100 text-white text-decoration-none btn btn-blue"
href="/thesaurus"
>Thesaurus</a
>
</li>
<li
class="position-relative d-flex me-xl-2 justify-content-between flex-column flex-lg-row"
>
<a
id="mw-global-nav-features"
class="w-100 text-white text-decoration-none btn btn-blue"
href="/words-at-play"
>Features</a
>
</li>
<li
class="position-relative d-flex me-xl-2 justify-content-between flex-column flex-lg-row"
>
<a
id="mw-global-nav-wod"
class="w-100 text-white text-decoration-none btn btn-blue"
href="/word-of-the-day"
>Word of the Day</a
>
</li>
<li
class="position-relative me-xl-2 justify-content-between flex-column flex-lg-row d-none d-xxl-flex"
>
<a
id="mw-global-nav-shop"
class="w-100 text-white text-decoration-none btn btn-blue"
href="https://shop.merriam-webster.com/?utm_source=mwsite&utm_medium=nav&utm_content=header"
>Shop</a
>
</li>
<li
class="position-relative me-xl-2 justify-content-between flex-column flex-lg-row d-none d-xxl-flex"
>
<a
id="mw-global-nav-joinmwu"
class="w-100 text-white text-decoration-none btn btn-blue"
href="https://unabridged.merriam-webster.com/subscriber/register/p1?refc=HDR_GLOBAL_JOINMWU"
>Join MWU</a
>
</li>
<li
class="position-relative d-flex me-xl-2 justify-content-between flex-column flex-lg-row dropdown d-xxl-none"
>
<a
id="mw-global-nav-show-more-mobile"
href="javascript:void(0);"
class="w-100 text-white text-decoration-none btn btn-blue parent dropdown-toggle d-flex justify-content-between align-items-center"
role="button"
data-bs-toggle="dropdown"
aria-expanded="false"
>
<span>More</span>
<span class="active-arrow">
<div class="arrow-up"></div>
</span>
</a>
<ul
aria-labelledby="mw-global-nav-show-more-mobile"
class="dropdown-menu submenu menu-list-items flex-row justify-content-between flex-column shadow ps-4 pb-3"
>
<li
class="position-relative d-flex me-xl-2 justify-content-between flex-column flex-lg-row"
>
<a
href="https://shop.merriam-webster.com/?utm_source=mwsite&utm_medium=nav&utm_content=header"
target="_blank"
rel="noopener noreferrer"
class="dropdown-item d-flex justify-content-between w-100 text-white text-decoration-none rounded"
>
<span>Shop M-W Books</span>
<span class="external-link">
<svg
xmlns="http://www.w3.org/2000/svg"
class="link-icon-svg svg replaced-svg"
width="11"
height="10"
viewBox="0 0 11 10"
fill="none"
data-inject-url="https://www.merriam-webster.com/dist-cross-dungarees/2023-04-05_15-17-24-b38e9d74/images/svg/link-icon.svg"
>
<title>link icon</title>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M7.16171 1.04167H8.72261L4.86475 4.9024L5.60077 5.63897L9.45156 1.78531V3.33333H10.4924V1.04167H10.4926V0.743537L10.4995 0.73657L10.4926 0.729603V0H10.4924H9.7635H9.45156H7.16171V1.04167ZM0.5 1.66667H4.83011V2.70833H1.54089V8.9998H7.78623V5.66647H8.82712V9.99938L0.5 9.9998V1.66667Z"
fill="#265667"
></path>
</svg>
</span>
</a>
</li>
<li
class="position-relative d-flex me-xl-2 justify-content-between flex-column flex-lg-row"
>
<a
href="https://unabridged.merriam-webster.com/subscriber/register/p1?refc=HDR_GLOBAL_JOINMWU"
target="_blank"
rel="noopener noreferrer"
class="dropdown-item d-flex justify-content-between w-100 text-white text-decoration-none rounded"
>
<span>Join MWU</span>
<span class="external-link d-none">
<svg
class="link-icon-svg svg replaced-svg"
width="11"
height="10"
viewBox="0 0 11 10"
fill="none"
xmlns="http://www.w3.org/2000/svg"
data-inject-url="https://www.merriam-webster.com/dist-cross-dungarees/2023-04-05_15-17-24-b38e9d74/images/svg/link-icon.svg"
>
<title>link icon</title>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M7.16171 1.04167H8.72261L4.86475 4.9024L5.60077 5.63897L9.45156 1.78531V3.33333H10.4924V1.04167H10.4926V0.743537L10.4995 0.73657L10.4926 0.729603V0H10.4924H9.7635H9.45156H7.16171V1.04167ZM0.5 1.66667H4.83011V2.70833H1.54089V8.9998H7.78623V5.66647H8.82712V9.99938L0.5 9.9998V1.66667Z"
fill="#265667"
></path>
</svg>
</span>
</a>
</li>
<ul class="p-0 m-0 d-none d-lg-block">
<li
class="loggedout-links position-relative me-xl-2 justify-content-between flex-column flex-lg-row mt-3"
>
<button
rel="nofollow"
onclick="window.location.href='/login'"
class="ul-sign-in fw-bold text-center btn btn-gradient btn-md active w-100 text-white text-decoration-none"
>
<span class="text-white">Log In</span>
</button>
</li>
<li
class="loggedin-links position-relative me-xl-2 justify-content-between flex-column flex-lg-row bg-white mt-4 mb-5"
>
<span
class="d-flex justify-content-between w-100 text-white text-decoration-none border-bottom border-gold ps-0"
>
<span
class="fs-4 fw-bold font-logo mw-username text-truncate"
style="max-width: 250px"
>Username</span
>
</span>
</li>
<li
class="loggedin-links position-relative me-xl-2 justify-content-between flex-column flex-lg-row mt-4"
>
<a
rel="nofollow"
href="/saved-words"
class="d-flex justify-content-between w-100 text-white text-decoration-none"
>
<span>My Words</span>
</a>
</li>
<li
class="loggedin-links position-relative me-xl-2 justify-content-between flex-column flex-lg-row"
>
<a
rel="nofollow"
href="/recents"
class="d-flex justify-content-between w-100 text-white text-decoration-none"
>
<span>Recents</span>
</a>
</li>
<li
class="loggedin-links position-relative me-xl-2 justify-content-between flex-column flex-lg-row"
>
<a
rel="nofollow"
href="/settings"
class="d-flex justify-content-between w-100 text-white text-decoration-none"
>
<span>Account</span>
</a>
</li>
<li
class="loggedin-links position-relative me-xl-2 justify-content-between flex-column flex-lg-row mt-3"
>
<button
rel="nofollow"
onclick="window.location.href='/logout'"
class="ul-sign-out fw-bold text-center btn btn-gradient btn-md active w-100 text-white text-decoration-none"
>
<span class="text-white">Log Out</span>
</button>
</li>
</ul>
</ul>
</li>
<li class="d-flex d-lg-none mt-5">
<ul class="m-0 p-0 w-100 mt-4">
<li class="loggedin-links ps-4 ms-2">
<span
class="d-flex justify-content-between w-100 text-white text-decoration-none border-bottom border-gold"
>
<span class="h3 fw-bold font-logo">Settings</span>
</span>
</li>
<li class="loggedin-links mt-4">
<a
rel="nofollow"
href="/saved-words"
class="d-flex justify-content-between w-100 text-white text-decoration-none"
>
<span>My Words</span>
</a>
</li>
<li class="loggedin-links">
<a
rel="nofollow"
href="/recents"
class="d-flex justify-content-between w-100 text-white text-decoration-none"
>
<span>Recents</span>
</a>
</li>
<li class="loggedin-links">
<a
rel="nofollow"
href="/settings"
class="d-flex justify-content-between w-100 text-white text-decoration-none"
>
<span>Account</span>
</a>
</li>
<li class="loggedin-links ps-5 pe-5 mt-4">
<button
rel="nofollow"
onclick="window.location.href='/logout'"
class="ul-sign-out fw-bold text-center btn btn-gradient btn-md active w-100 text-white text-decoration-none"
>
<span>Log Out</span>
</button>
</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div class="d-lg-none">
<div
class="search-results-auto overflow-auto search-results-sm collapse shadow-sm"
></div>
</div>
<!-- search-results-auto -->
</header>
<div class="header-placeholder">
<div class="container-xxl d-none d-lg-block position-relative">
<div class="est font-logo rounded text-center" aria-hidden="true">
Est. 1828
</div>
</div>
</div>
<div class="main-wrapper clearfix">
<main>
<article>
<div class="article-header-container wod-article-header">
<div class="w-a-title">
<h1 class="d-inline">Word of the Day</h1>
<span> : April 10, 2023</span>
</div>
<div class="under-widget-title-line"></div>
<div class="quick-def-box">
<div class="word-header">
<div class="word-and-pronunciation">
<h2 class="word-header-txt">foible</h2>
<a
class="play-pron wod-autoplay hoverable"
data-lang="en_us"
data-file="foible01"
data-dir="f"
href="javascript:void(0)"
title="Listen to the pronunciation of foible"
>play <span class="play-box"></span
></a>
</div>
</div>
<span
class="scrollDepth"
data-eventname="wotd-headword"
></span>
<!-- end simple definition header -->
<div class="word-attributes">
<span class="main-attr">noun</span>
<!--<span class="word-syllables">fru <span class="dot"></span> gal</span>-->
<span class="word-syllables">FOY-bul</span>
<!--<span class="pr">\FOY-bul\</span>-->
</div>
<!-- end word attributes -->
<!--Next and previous buttons rendered depending on if we have content-->
<div class="nav-arrow-container">
<a
href="/word-of-the-day/auspicious-2023-04-09"
class="prev-wod-arrow"
rel="nofollow"
>Prev</a
>
<a href="#" class="next-wod-arrow disabled" rel="nofollow"
>Next</a
>
</div>
</div>
</div>
<hr class="blue-divide thin-divide" />
<div class="lr-cols-area clearfix sticky-column d-flex">
<div class="left-content">
<div class="wod-article-container">
<!--1-st part of word-->
<div class="wod-definition-container">
<h2>What It Means</h2>
<p>
<em>Foibles</em> are minor flaws or shortcomings in
character or behavior. In fencing,
<em>foible</em> refers to the part of a sword's blade
between the middle and point, which is considered the
weakest part.
</p>
<p>
// He was amused daily by the <em>foibles</em> of his
eccentric neighbor.
</p>
<p>
<a
href="https://www.merriam-webster.com/dictionary/foible"
>See the entry ></a
>
</p>
<span
class="scrollDepth"
data-eventname="wotd-definition"
></span>
<h2>
<span class="wotd-example-label">foible</span> in
Context
</h2>
<div class="wotd-examples">
<div class="left-content-box">
<p>
"Films about important historical moments are often
marked by a heavy solemnity, a sometimes suffocating
respectfulness that can make one forget that these
events involved real people, human beings with
passions and <em>foibles</em>." — Michael Ordoña,
<em>The Los Angeles Times</em>, 20 Jan. 2023
</p>
<span
class="scrollDepth"
data-eventname="wotd-examples"
></span>
</div>
<div
id="wotd-right-content-box"
class="right-content-box active-subscribe"
>
<div id="wotd-subscribe-box">
<!--Subscribe WOD Box-->
<div id="subscribe-wod-box" class="clearfix">
<h3 class="header">
Build your vocabulary! Get Word of the Day in
your inbox every day.
</h3>
<form
class="js-wod-subscribe-frm"
action="/"
data-source="mwsite"
data-campaign="wotd"
data-medium="wotd-side-box"
>
<input
type="text"
class="wod-subscribe-input"
name="email"
aria-label="Your email address"
placeholder="Your email address"
/>
<input
type="submit"
aria-label="Sign up for Merriam-Webster's Word of the Day newsletter"
name="submit"
class="subscribe-btn"
value="Subscribe"
/>
</form>
</div>
<!--Subscribe WOD Box end-->
</div>
<span
class="scrollDepth"
data-eventname="wotd-subscribe-box"
></span>
<div id="wotd-games-box">
<div class="wgt-side wgt-games-side">
<div
class="wgt-header d-flex align-items-center justify-content-evenly mb-4"
>
<div
class="d-flex flex-column text-center justify-content-center me-2 mr-2"
>
<a
href="/"
title="Merriam Webster"
class="text-decoration-none mw-logo"
>
<svg
width="57"
height="57"
viewBox="0 0 57 57"
fill="none"
xmlns="http://www.w3.org/2000/svg"
>
<path
d="M0 28.5C0 12.7559 12.8041 0 28.6006 0C44.397 0 57 12.762 57 28.5C57 44.2441 44.397 57 28.6006 57C12.8102 57.0061 0 44.2441 0 28.5Z"
fill="white"
></path>
<path
fill-rule="evenodd"
clip-rule="evenodd"
d="M28.5 56.6686C44.0571 56.6686 56.6686 44.0571 56.6686 28.5C56.6686 12.9429 44.0571 0.331395 28.5 0.331395C12.9429 0.331395 0.331395 12.9429 0.331395 28.5C0.331395 44.0571 12.9429 56.6686 28.5 56.6686ZM28.5 57C44.2401 57 57 44.2401 57 28.5C57 12.7599 44.2401 0 28.5 0C12.7599 0 0 12.7599 0 28.5C0 44.2401 12.7599 57 28.5 57Z"
fill="#D71920"
></path>
<path
d="M2.08537 28.4971C2.08537 13.9089 13.9149 2.08545 28.503 2.08545C43.0911 2.08545 54.9146 13.9089 54.9146 28.4971C54.9146 43.0852 43.0911 54.9087 28.503 54.9147C13.9149 54.9147 2.09139 43.0852 2.08537 28.4971ZM3.81402 28.4971C3.81402 35.3153 6.57865 41.483 11.0479 45.9522C15.517 50.4214 21.6848 53.18 28.503 53.1861C35.3213 53.1861 41.489 50.4214 45.9582 45.9522C50.4274 41.483 53.192 35.3153 53.192 28.4971C53.192 21.6788 50.4274 15.5111 45.9582 11.0419C41.489 6.57272 35.3213 3.80808 28.503 3.80808C21.6788 3.80808 15.517 6.56669 11.0479 11.0419C6.57865 15.5111 3.81402 21.6788 3.81402 28.4971Z"
fill="#D71920"
></path>
<path
d="M31.3917 34.9741C31.3917 34.3001 31.8774 33.8872 32.4421 33.8811C33.2193 33.8811 33.5958 34.4823 33.5958 35.2716L34.0147 35.2959L34.0633 34.0815H34.039L34.0572 34.0633C33.5775 33.6322 33.0371 33.5168 32.4239 33.5168C31.4706 33.5168 30.5841 34.1726 30.5841 35.2837C30.5962 37.5911 33.5897 36.6014 33.5654 38.174C33.5654 38.8965 33.11 39.4126 32.4057 39.4126H32.3753C31.4888 39.3944 30.9363 38.6658 30.912 37.7125L30.4444 37.6882V37.7125L30.4566 37.8279L30.578 39.4308C31.1184 39.7405 31.7135 39.8195 32.2903 39.8195C33.3954 39.8195 34.5005 39.2062 34.5005 37.8704C34.4823 35.6602 31.3613 36.3038 31.3917 34.9741ZM27.6817 33.5775C27.4874 33.5775 27.3053 33.614 27.111 33.6383L26.097 34.2819L26.2427 34.4033C26.5159 34.3183 26.7892 34.2697 27.0503 34.2697C28.4589 34.2697 29.0843 35.5813 29.0904 36.911C29.0904 38.2893 28.4893 39.4551 27.2446 39.4551C26.4309 39.4551 25.9391 38.8904 25.9391 38.0768V29.9951L25.6902 29.8858C25.1801 30.1105 24.5608 30.3109 23.99 30.3837L23.9779 30.6145C24.3483 30.6388 24.6154 30.6995 24.9372 30.8573L24.913 37.3057C24.913 37.5971 24.913 37.8825 24.913 38.174C24.913 38.6901 24.9069 39.2062 24.8705 39.7466L25.1012 39.8741L25.5687 39.4248C25.9573 39.6555 26.4431 39.8377 26.8863 39.8437C29.0904 39.8377 30.0437 38.259 30.0437 36.5467C30.0437 34.6037 29.1754 33.5775 27.6817 33.5775ZM20.6809 31.3067L20.6991 30.9909L17.7481 30.9666L17.7238 31.2824L18.8775 31.592L18.7075 32.0839L16.7766 37.5425C16.5641 36.911 14.9854 32.1446 14.8761 31.7378L15.0219 31.507L15.9812 31.3613L15.9994 31.0152L12.8117 30.997V31.0213H12.7874V31.3431L13.6617 31.5435L13.8196 31.8349C13.7103 32.2417 12.0588 36.9414 11.8341 37.5668L9.92146 31.6103L9.97611 31.592L10.9051 31.3613L10.9476 31.0152H10.9233H10.808L7.63236 30.9849L7.602 31.3067L8.73745 31.586L11.3544 39.8559L11.7552 39.8741L14.1414 33.2982L16.3516 39.8377L16.7766 39.8559L19.6668 31.5738L20.6809 31.3067ZM9.90325 31.6224L9.98218 31.8653L9.90325 31.6224ZM18.8836 31.5738L18.8107 31.5556L18.8836 31.5738ZM38.344 38.4472L38.3075 38.4776C38.0343 38.7508 37.6093 39.1758 37.2692 39.1758C36.6196 39.1637 36.3706 38.7144 36.3645 37.9007C36.3645 37.8643 36.3645 37.8279 36.3645 37.7914V34.5491H36.407L38.1315 34.5733L38.1557 33.9722L36.3403 33.9479L36.3645 32.3996L36.0549 32.3753C35.8059 33.2436 35.1198 33.7536 34.4519 34.2394L34.4397 34.5491H34.464V34.5733H35.3262L35.302 38.2893C35.302 39.4491 36.0488 39.868 36.7228 39.8741C36.7471 39.8741 36.7774 39.8741 36.8017 39.8741C37.755 39.8255 38.4047 38.8783 38.4108 38.8783L38.35 38.4897L38.344 38.4472ZM35.1623 27.8518H35.1927C35.9152 27.8335 36.4981 27.5603 37.0507 27.1292L37.0203 27.8639C37.0203 27.8639 37.0264 27.8639 37.0324 27.8639H37.0446C37.0446 27.8639 37.0628 27.8578 37.0689 27.8578C37.2935 27.8335 38.4533 27.5725 38.9755 27.4753L39.0119 27.4692L38.8297 27.1899L37.9857 27.1049V23.48C37.9857 22.4296 37.5303 21.956 36.7956 21.956C36.7592 21.956 36.7288 21.956 36.6924 21.956C36.5892 21.956 36.4799 21.962 36.3767 22.0167L35.0469 22.8121C34.9134 22.8971 34.4337 23.1582 34.4155 23.3889L34.373 24.0508L34.464 24.1236L35.1562 23.984C35.2412 23.9658 35.3687 23.9718 35.3687 23.8261V23.8079C35.3627 23.6925 35.3566 23.5832 35.3566 23.48C35.3627 23.0185 35.4659 22.6724 36.3038 22.551C36.3342 22.5449 36.3645 22.5449 36.3949 22.5449C36.8139 22.5449 37.0628 22.9882 37.0628 23.8443V24.7187C36.492 24.8947 35.8666 25.1437 35.1987 25.3623C34.6948 25.5262 33.9115 25.7691 33.9115 26.771C33.9115 27.2264 34.4519 27.8518 35.1623 27.8518ZM37.0446 27.8396H37.0385L37.0507 27.6635L37.0446 27.8396ZM37.0871 25.0162V25.0223C36.9778 25.0587 36.8806 25.089 36.7774 25.1194C36.8806 25.083 36.9778 25.0526 37.0871 25.0162ZM37.0871 25.0405V25.4291L37.0628 26.7285C36.7046 26.9531 36.1459 27.2385 35.8181 27.2385C35.3748 27.2385 34.9194 26.9288 34.9194 26.522C34.9134 25.7205 35.7695 25.4898 37.0871 25.0405ZM32.2903 20.5291C32.5696 20.5291 32.8307 20.3044 32.8368 20.0008C32.8368 19.6911 32.606 19.4118 32.2903 19.4058C31.9867 19.4058 31.7681 19.7094 31.7681 20.0008C31.7681 20.2801 32.0231 20.5291 32.2903 20.5291ZM31.8956 27.3296L30.8148 27.5057L30.7966 27.7971L33.8993 27.8214V27.7971H33.9236V27.5299L32.8428 27.3053L32.8611 22.1017L32.6303 21.9924C32.1506 22.2049 31.4767 22.3931 30.9423 22.466L30.9181 22.7574C31.2642 22.7817 31.6103 22.8425 31.9138 22.9942L31.8956 27.3296ZM23.3221 27.2871L22.2838 27.4632L22.2656 27.8032L25.3319 27.8275L25.3562 27.4874L24.2997 27.2628L24.3179 24.3544C24.3179 24.154 24.8644 22.8121 25.5019 22.8121C25.6416 22.8121 25.842 22.9153 25.9634 23.0064L26.2791 23.0368L26.5038 22.2413C26.2973 22.0652 25.8237 22.0349 25.5748 22.0349C24.9433 22.041 24.7551 22.7635 24.5061 23.2432L24.3483 23.4982V22.1078L24.069 21.9985L24.0629 22.0227L24.0508 21.9985C23.5832 22.211 22.891 22.3992 22.3445 22.4721L22.3203 22.7635C22.6785 22.7878 23.0307 22.8485 23.3343 23.0003L23.3221 27.2871ZM9.81217 27.4814L8.7253 27.2567L9.33249 20.6991L9.38714 20.5351L12.3077 27.5846L12.4717 27.5967L15.3133 20.608L15.3922 20.7537L15.9509 27.2749L14.785 27.451L14.7668 27.791L18.1124 27.8153L18.1367 27.4753L17.1227 27.2506L16.3941 20.013L17.5356 19.8369L17.5295 19.8126H17.5538L17.5417 19.5211L15.0583 19.4968L12.5749 25.5323L10.055 19.509L7.52307 19.4968L7.48664 19.8126L8.7253 20.0433L8.02704 27.281L7.06768 27.4571L7.04946 27.7971L9.78788 27.8214L9.81217 27.4814ZM48.0529 23.8747C48.059 22.6907 47.4579 22.0227 46.201 21.9863C46.1949 21.9863 46.1889 21.9863 46.1828 21.9863C46.031 21.9863 45.7881 22.047 45.4481 22.3142L44.5677 23.0671C44.2519 22.4721 43.6508 22.0045 42.9465 21.9985C42.485 21.9985 42.315 22.0592 41.9507 22.3446L41.1128 22.891V22.0956L40.8395 21.9863C40.372 22.1988 39.7101 22.3871 39.188 22.4599L39.1637 22.6846C39.5037 22.7089 39.8437 22.7696 40.1352 22.9214L40.1291 27.2628L39.2123 27.4389L39.194 27.7485L42.0296 27.7728L42.0539 27.4935L41.1006 27.2385L41.1188 23.3464C41.5378 23.0307 42.0114 22.6482 42.5093 22.6482C43.5719 22.6482 43.5962 23.7229 43.6022 24.6762V27.2628L42.6854 27.4692L42.6672 27.7485L45.5027 27.7728L45.527 27.4935L44.5737 27.2385L44.5919 23.3343C44.9988 23.0368 45.5452 22.721 46.0492 22.721C47.0086 22.721 47.0693 23.5286 47.0753 24.3847C47.0753 24.5304 47.0753 24.6701 47.0753 24.8158V27.2628L46.1585 27.4692L46.1403 27.7485L48.9333 27.7728L48.9576 27.4935L48.0468 27.2385L48.0529 23.8747ZM20.0979 27.955C20.6869 27.955 21.0998 27.876 21.1909 27.8214L22.5753 26.3824L22.1867 26.352C21.7374 26.8195 21.3002 27.2142 20.6626 27.2142C20.6323 27.2142 20.6019 27.2142 20.5716 27.2142C18.7682 27.1049 18.5193 25.7448 18.5132 24.1904H18.5496L21.6827 24.2147C22.0288 24.2147 22.1685 24.1722 22.1685 23.7168C22.1685 22.7028 21.3002 21.9985 20.0919 21.9985C18.665 21.9985 17.5174 23.0671 17.5174 24.9615C17.5235 26.8863 18.6589 27.9489 20.0979 27.955ZM19.9279 22.3506C20.7962 22.3506 21.1666 22.97 21.1666 23.7715C21.1666 23.814 21.1666 23.8625 21.1666 23.9111L18.5435 23.8868C18.6043 23.1278 19.1143 22.3506 19.9279 22.3506ZM30.8452 22.2353C30.6387 22.0592 30.1651 22.0288 29.9162 22.0288C29.2847 22.0349 29.0965 22.7574 28.8475 23.2371L28.6897 23.4921V22.1017L28.4104 21.9924L28.4043 22.0167L28.3921 21.9924C27.9246 22.2049 27.2324 22.3931 26.6859 22.466L26.6677 22.7574C27.026 22.7817 27.3781 22.8425 27.6817 22.9942L27.6696 27.2871L26.6313 27.4632L26.607 27.7971H26.6313H26.7102L29.6733 27.8214L29.6976 27.4814L28.6411 27.2567L28.6654 24.3483C28.6654 24.1479 29.2119 22.806 29.8433 22.806C29.983 22.806 30.1834 22.9092 30.3048 23.0003L30.6205 23.0307L30.8452 22.2353ZM45.6545 34.8162L45.4845 35.0894V33.6201L45.187 33.5108L45.1809 33.535L45.1688 33.5108C44.677 33.7354 43.9544 33.9358 43.3776 34.0087L43.3533 34.3183C43.7297 34.3426 44.1001 34.4033 44.4159 34.5673L44.4037 39.0787L43.3108 39.2669L43.2926 39.6191L46.5107 39.6434L46.535 39.2912L45.4299 39.0544L45.4481 35.9942C45.4481 35.7877 46.0188 34.373 46.6928 34.373C46.8385 34.373 47.0511 34.4823 47.1786 34.5794L47.5065 34.6098L47.7433 33.7718C47.5307 33.5897 47.0268 33.5593 46.7718 33.5593C46.116 33.5472 45.9217 34.3122 45.6545 34.8162ZM22.302 39.0726C22.2656 39.0726 22.2353 39.0726 22.2049 39.0726C20.2983 38.9572 20.0372 37.5182 20.0312 35.8788L23.3828 35.9031C23.7472 35.9031 23.8929 35.8545 23.8929 35.3748C23.8929 34.3062 22.976 33.5593 21.707 33.5593C20.2012 33.5654 18.9929 34.6887 18.9868 36.6864C18.9929 38.7204 20.189 39.8498 21.707 39.8498C22.3324 39.8498 22.7635 39.7648 22.8607 39.7102L24.324 38.1922L23.9172 38.1558C23.4375 38.6597 22.976 39.0726 22.302 39.0726ZM21.5248 33.9419C22.4417 33.9419 22.8364 34.5976 22.8364 35.4477C22.8364 35.4963 22.8364 35.5448 22.8364 35.5934L20.0615 35.5691C20.1283 34.7555 20.6626 33.9419 21.5248 33.9419ZM43.3776 38.1193C42.904 38.6172 42.4425 39.0301 41.7685 39.0301C41.7321 39.0301 41.7017 39.0301 41.6653 39.0301C39.7587 38.9147 39.4976 37.4757 39.4916 35.8363L42.8432 35.8606C43.2076 35.8606 43.3533 35.812 43.3533 35.3323C43.3533 34.2637 42.4364 33.5168 41.1674 33.5168C39.6616 33.5229 38.4472 34.6462 38.4472 36.6439C38.4472 38.684 39.6494 39.8073 41.1674 39.8073C41.7867 39.8073 42.2239 39.7223 42.3211 39.6677L43.7844 38.1497L43.3776 38.1193ZM40.9913 33.8994C41.9082 33.8994 42.3028 34.5551 42.3028 35.4052C42.3028 35.4538 42.3028 35.5023 42.2968 35.5509L39.5219 35.5266C39.5948 34.7191 40.1352 33.8994 40.9913 33.8994ZM48.9091 24.5729V25.3926H51.1374V24.5729H48.9091Z"
fill="#004990"
></path>
</svg>
</a>
<div class="text-uppercase mt-2">
<a
class="fw-bold text-uppercase text-deocration-none wgt-header"
style="letter-spacing: 1px"
href="/games"
>
Test Your Vocabulary
</a>
</div>
<hr class="m-2 w-100" />
<h4 class="jc-wgt-title-type1 fs-6 m-0 p-0">
<span
class="text-capitalize small"
style="letter-spacing: 1px"
>
<p class="lead m-0">
What Did You Just Call Me?
</p>
</span>
</h4>
</div>
</div>
<div class="wgt-games-side-items">
<div class="wgts-quiz-with-answers">
<ul class="wgts-quiz-question m-0 p-0 mb-2">
<li class="wgts-quiz-image">
<div class="thumbnail">
<span
class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="brown chihuahua sitting on the floor with squinting eyes looking at the camera"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-global-side-widget/brown%20chihuahua%20sitting%20on%20the%20floor%20with%20squinting%20eyes%20looking%20at%20the%20camera-9700-0a5a68cddc529ae67b13eb5595f1fe3f@1x.jpg"
data-caption=""
data-credit="getty images"
data-type="quiz"
data-dim="quiz-global-side-widget"
data-ret-pref="brown chihuahua sitting on the floor with squinting eyes looking at the camera-9700-0a5a68cddc529ae67b13eb5595f1fe3f"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-global-side-widget/brown%20chihuahua%20sitting%20on%20the%20floor%20with%20squinting%20eyes%20looking%20at%20the%20camera-9700-0a5a68cddc529ae67b13eb5595f1fe3f@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-global-side-widget/brown%20chihuahua%20sitting%20on%20the%20floor%20with%20squinting%20eyes%20looking%20at%20the%20camera-9700-0a5a68cddc529ae67b13eb5595f1fe3f@2x.jpg 2x"
pair-id="9702"
image-id="9700"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</div>
</li>
<li class="lead">
Before we went to her house, Hannah told
us her aunt was a
<em>flibbertigibbet</em>.
</li>
</ul>
<div class="content m-0 p-0 mb-4">
<ul class="quiz-answer-list m-0 p-0">
<li>
<a
class="quiz-answer"
href="/games/insult-compliment?q=3818&a=14182"
>Insulting</a
>
<a
class="quiz-answer"
href="/games/insult-compliment?q=3818&a=14183"
>Complimentary</a
>
</li>
</ul>
</div>
</div>
<div class="wgts-quiz">
<div class="thumbnail">
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="Name That Thing"
data-src="https://merriam-webster.com/assets/mw/static/images/old-quizzes/name-that-thing/80x60@1x.jpg"
data-dim="80x60"
data-srcset="https://merriam-webster.com/assets/mw/static/images/old-quizzes/name-that-thing/80x60@1x.jpg 1x, https://merriam-webster.com/assets/mw/static/images/old-quizzes/name-that-thing/80x60@2x.jpg 2x"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</div>
<div class="content">
<p class="blurb p-0 m-0">
You know what it looks like… but what is
it called?
</p>
<a
class="to-quiz"
href="/games/name-that-thing"
>TAKE THE QUIZ</a
>
</div>
</div>
<div class="wgts-quiz last">
<div class="thumbnail">
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="Solve today's spelling word game by finding as many words as you can with using just 7 letters. Longer words score more points."
data-src="https://merriam-webster.com/assets/mw/static/images/games/iframe/blossom-word-game/485x364@1x.jpg"
data-srcset="https://merriam-webster.com/assets/mw/static/images/games/iframe/blossom-word-game/485x364@1x.jpg 1x, https://merriam-webster.com/assets/mw/static/images/games/iframe/blossom-word-game/485x364@2x.jpg 2x"
data-dim="485x364"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</div>
<div class="content">
<p class="blurb p-0 m-0">
<!--
-->Can you make 12 words with 7 letters?<!--
-->
</p>
<a
class="to-quiz"
href="/games/blossom-word-game"
>PLAY</a
>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<hr class="blue-divide thin-divide desktop-only" />
<!--2-nd part of word-->
<div class="did-you-know-wrapper">
<h2>Did You Know?</h2>
<p>
Many word lovers agree that the pen is mightier than the
sword. But be they
<a
href="https://www.merriam-webster.com/dictionary/hone#h1"
>honed</a
>
in wit or form, even the sharpest tools in the shed have
their flaws. That’s where <em>foible</em> comes in
handy. Borrowed from French in the 1600s, the word
originally referred to the weakest part of a fencing
sword, that part being the portion between the middle
and the pointed tip. The English <em>foible</em> soon
came to be applied not only to weaknesses in blades but
also to minor failings in character. The French source
of <em>foible</em> is also at a remove from the fencing
arena; the French <em>foible</em> means "weak," and it
comes from the same Old French term, <em>feble</em>,
that gave us
<em
><a
href="https://www.merriam-webster.com/dictionary/feeble"
>feeble</a
></em
>.
</p>
<span
class="scrollDepth"
data-eventname="wotd-did-you-know"
></span>
</div>
<hr class="blue-divide thin-divide no-float" />
<div class="game-recirc-widget">
<h2>Test Your Vocabulary with M-W Quizzes</h2>
<div class="chalenges-bar">
<button
class="slick-prev slick-arrow"
aria-label="Previous"
type="button"
style=""
>
Previous
</button>
<div
class="challenges-slider bar-items slick-initialized slick-slider"
>
<div class="slick-list draggable">
<div
class="slick-track"
style="
opacity: 1;
width: 30000px;
transform: translate3d(-852px, 0px, 0px);
"
>
<div
class="item slick-slide slick-cloned"
style=""
data-slick-index="-3"
id=""
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/famous-novels-first-lines?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="book-magic-glow"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb@1x.jpg"
data-caption="book with a magical glow"
data-credit=""
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb@2x.jpg 2x"
pair-id="9964"
image-id="9962"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/famous-novels-first-lines?src=wotdl"
tabindex="-1"
>Famous Novels, First Lines Quiz</a
>
</p>
<a
href="/games/famous-novels-first-lines?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
<div
class="item slick-slide slick-cloned"
style=""
data-slick-index="-2"
id=""
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/weather-words?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="colorful-umbrella-among-black-umbrellas"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da@1x.jpg"
data-caption="Colorful umbrella in a sea of black umbrellas"
data-credit="Getty"
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da@2x.jpg 2x"
pair-id="9949"
image-id="9947"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/weather-words?src=wotdl"
tabindex="-1"
>Weather Words</a
>
</p>
<a
href="/games/weather-words?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
<div
class="item slick-slide slick-cloned"
style=""
data-slick-index="-1"
id=""
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/animals-3?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="serval"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/serval-9917-20e9bee53bdc9afa944a1a815d531c07@1x.jpg"
data-caption="serval"
data-credit="Getty"
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="serval-9917-20e9bee53bdc9afa944a1a815d531c07"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/serval-9917-20e9bee53bdc9afa944a1a815d531c07@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/serval-9917-20e9bee53bdc9afa944a1a815d531c07@2x.jpg 2x"
pair-id="9919"
image-id="9917"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/animals-3?src=wotdl"
tabindex="-1"
>Name That Animal: Volume 3</a
>
</p>
<a
href="/games/animals-3?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
<div
class="item slick-slide slick-current slick-active"
style=""
data-slick-index="0"
aria-hidden="false"
tabindex="0"
>
<a
class="img-link"
href="/games/name-that-hat?src=wotdl"
tabindex="0"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="back-of-head-mortarboard"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/back-of-head-mortarboard-10064-4e5e855e2ec66d5e2e40cf7aad826e68@1x.jpg"
data-caption="mortarboard"
data-credit="Getty"
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="back-of-head-mortarboard-10064-4e5e855e2ec66d5e2e40cf7aad826e68"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/back-of-head-mortarboard-10064-4e5e855e2ec66d5e2e40cf7aad826e68@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/back-of-head-mortarboard-10064-4e5e855e2ec66d5e2e40cf7aad826e68@2x.jpg 2x"
pair-id="10066"
image-id="10064"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/name-that-hat?src=wotdl"
tabindex="0"
>Name That Hat!</a
>
</p>
<a
href="/games/name-that-hat?src=wotdl"
class="arrow-link"
tabindex="0"
>Play Now</a
>
</div>
<div
class="item slick-slide slick-active"
style=""
data-slick-index="1"
aria-hidden="false"
tabindex="0"
>
<a
class="img-link"
href="/games/ntt-flowers-quiz?src=wotdl"
tabindex="0"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="name that thing flower edition"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/name%20that%20thing%20flower%20edition-3542-c2569c2183097e7ecf1abe632526ed37@1x.jpg"
data-caption=""
data-credit=""
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="name that thing flower edition-3542-c2569c2183097e7ecf1abe632526ed37"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/name%20that%20thing%20flower%20edition-3542-c2569c2183097e7ecf1abe632526ed37@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/name%20that%20thing%20flower%20edition-3542-c2569c2183097e7ecf1abe632526ed37@2x.jpg 2x"
pair-id="3545"
image-id="3542"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/ntt-flowers-quiz?src=wotdl"
tabindex="0"
>Name That Flower</a
>
</p>
<a
href="/games/ntt-flowers-quiz?src=wotdl"
class="arrow-link"
tabindex="0"
>Play Now</a
>
</div>
<div
class="item slick-slide slick-active"
style=""
data-slick-index="2"
aria-hidden="false"
tabindex="0"
>
<a
class="img-link"
href="/games/feeling-lucky?src=wotdl"
tabindex="0"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="womans hand holding a green four leaf clover"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/womans%20hand%20holding%20a%20green%20four%20leaf%20clover-9991-238ff35c2de30a43a767d786fe20d2ef@1x.jpg"
data-caption=""
data-credit="Getty Images"
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="womans hand holding a green four leaf clover-9991-238ff35c2de30a43a767d786fe20d2ef"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/womans%20hand%20holding%20a%20green%20four%20leaf%20clover-9991-238ff35c2de30a43a767d786fe20d2ef@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/womans%20hand%20holding%20a%20green%20four%20leaf%20clover-9991-238ff35c2de30a43a767d786fe20d2ef@2x.jpg 2x"
pair-id="9993"
image-id="9991"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/feeling-lucky?src=wotdl"
tabindex="0"
>Are You Feeling Lucky?</a
>
</p>
<a
href="/games/feeling-lucky?src=wotdl"
class="arrow-link"
tabindex="0"
>Play Now</a
>
</div>
<div
class="item slick-slide"
style=""
data-slick-index="3"
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/famous-novels-first-lines?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="book-magic-glow"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb@1x.jpg"
data-caption="book with a magical glow"
data-credit=""
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb@2x.jpg 2x"
pair-id="9964"
image-id="9962"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/famous-novels-first-lines?src=wotdl"
tabindex="-1"
>Famous Novels, First Lines Quiz</a
>
</p>
<a
href="/games/famous-novels-first-lines?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
<div
class="item slick-slide"
style=""
data-slick-index="4"
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/weather-words?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="colorful-umbrella-among-black-umbrellas"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da@1x.jpg"
data-caption="Colorful umbrella in a sea of black umbrellas"
data-credit="Getty"
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da@2x.jpg 2x"
pair-id="9949"
image-id="9947"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/weather-words?src=wotdl"
tabindex="-1"
>Weather Words</a
>
</p>
<a
href="/games/weather-words?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
<div
class="item slick-slide"
style=""
data-slick-index="5"
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/animals-3?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="serval"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/serval-9917-20e9bee53bdc9afa944a1a815d531c07@1x.jpg"
data-caption="serval"
data-credit="Getty"
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="serval-9917-20e9bee53bdc9afa944a1a815d531c07"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/serval-9917-20e9bee53bdc9afa944a1a815d531c07@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/serval-9917-20e9bee53bdc9afa944a1a815d531c07@2x.jpg 2x"
pair-id="9919"
image-id="9917"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/animals-3?src=wotdl"
tabindex="-1"
>Name That Animal: Volume 3</a
>
</p>
<a
href="/games/animals-3?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
<div
class="item slick-slide slick-cloned"
style=""
data-slick-index="6"
id=""
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/name-that-hat?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="back-of-head-mortarboard"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/back-of-head-mortarboard-10064-4e5e855e2ec66d5e2e40cf7aad826e68@1x.jpg"
data-caption="mortarboard"
data-credit="Getty"
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="back-of-head-mortarboard-10064-4e5e855e2ec66d5e2e40cf7aad826e68"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/back-of-head-mortarboard-10064-4e5e855e2ec66d5e2e40cf7aad826e68@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/back-of-head-mortarboard-10064-4e5e855e2ec66d5e2e40cf7aad826e68@2x.jpg 2x"
pair-id="10066"
image-id="10064"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/name-that-hat?src=wotdl"
tabindex="-1"
>Name That Hat!</a
>
</p>
<a
href="/games/name-that-hat?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
<div
class="item slick-slide slick-cloned"
style=""
data-slick-index="7"
id=""
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/ntt-flowers-quiz?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="name that thing flower edition"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/name%20that%20thing%20flower%20edition-3542-c2569c2183097e7ecf1abe632526ed37@1x.jpg"
data-caption=""
data-credit=""
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="name that thing flower edition-3542-c2569c2183097e7ecf1abe632526ed37"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/name%20that%20thing%20flower%20edition-3542-c2569c2183097e7ecf1abe632526ed37@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/name%20that%20thing%20flower%20edition-3542-c2569c2183097e7ecf1abe632526ed37@2x.jpg 2x"
pair-id="3545"
image-id="3542"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/ntt-flowers-quiz?src=wotdl"
tabindex="-1"
>Name That Flower</a
>
</p>
<a
href="/games/ntt-flowers-quiz?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
<div
class="item slick-slide slick-cloned"
style=""
data-slick-index="8"
id=""
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/feeling-lucky?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="womans hand holding a green four leaf clover"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/womans%20hand%20holding%20a%20green%20four%20leaf%20clover-9991-238ff35c2de30a43a767d786fe20d2ef@1x.jpg"
data-caption=""
data-credit="Getty Images"
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="womans hand holding a green four leaf clover-9991-238ff35c2de30a43a767d786fe20d2ef"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/womans%20hand%20holding%20a%20green%20four%20leaf%20clover-9991-238ff35c2de30a43a767d786fe20d2ef@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/womans%20hand%20holding%20a%20green%20four%20leaf%20clover-9991-238ff35c2de30a43a767d786fe20d2ef@2x.jpg 2x"
pair-id="9993"
image-id="9991"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/feeling-lucky?src=wotdl"
tabindex="-1"
>Are You Feeling Lucky?</a
>
</p>
<a
href="/games/feeling-lucky?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
<div
class="item slick-slide slick-cloned"
style=""
data-slick-index="9"
id=""
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/famous-novels-first-lines?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="book-magic-glow"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb@1x.jpg"
data-caption="book with a magical glow"
data-credit=""
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/book-magic-glow-9962-96dfef56a128e8f332bfd32e04ce87eb@2x.jpg 2x"
pair-id="9964"
image-id="9962"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/famous-novels-first-lines?src=wotdl"
tabindex="-1"
>Famous Novels, First Lines Quiz</a
>
</p>
<a
href="/games/famous-novels-first-lines?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
<div
class="item slick-slide slick-cloned"
style=""
data-slick-index="10"
id=""
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/weather-words?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="colorful-umbrella-among-black-umbrellas"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da@1x.jpg"
data-caption="Colorful umbrella in a sea of black umbrellas"
data-credit="Getty"
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/colorful-umbrella-among-black-umbrellas-9947-dfecb4285a7aa027f48bb3d49356b1da@2x.jpg 2x"
pair-id="9949"
image-id="9947"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/weather-words?src=wotdl"
tabindex="-1"
>Weather Words</a
>
</p>
<a
href="/games/weather-words?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
<div
class="item slick-slide slick-cloned"
style=""
data-slick-index="11"
id=""
aria-hidden="true"
tabindex="-1"
>
<a
class="img-link"
href="/games/animals-3?src=wotdl"
tabindex="-1"
>
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="serval"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/serval-9917-20e9bee53bdc9afa944a1a815d531c07@1x.jpg"
data-caption="serval"
data-credit="Getty"
data-type="quiz"
data-dim="quiz-games-landing-weekly-sm"
data-ret-pref="serval-9917-20e9bee53bdc9afa944a1a815d531c07"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/serval-9917-20e9bee53bdc9afa944a1a815d531c07@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-games-landing-weekly-sm/serval-9917-20e9bee53bdc9afa944a1a815d531c07@2x.jpg 2x"
pair-id="9919"
image-id="9917"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="
/></span>
</a>
<p>
<a
href="/games/animals-3?src=wotdl"
tabindex="-1"
>Name That Animal: Volume 3</a
>
</p>
<a
href="/games/animals-3?src=wotdl"
class="arrow-link"
tabindex="-1"
>Play Now</a
>
</div>
</div>
</div>
</div>
<button
class="slick-next slick-arrow"
aria-label="Next"
type="button"
style=""
>
Next
</button>
</div>
</div>
<span
class="scrollDepth"
data-eventname="wotd-quiz-recirc"
></span>
<hr class="blue-divide thin-divide" />
<div class="wod-activity-container">
<h2>Test Your Vocabulary</h2>
<p>
Unscramble the letters to create a word that refers to a
particular kind of fencing sword: BRASE.
</p>
<a href="http://bit.ly/3JZNjCF" class="view-answer-link"
>VIEW THE ANSWER</a
>
</div>
<span
class="scrollDepth"
data-eventname="wotd-daily-quiz"
></span>
<hr class="blue-divide thin-divide" />
<!--podcasts widget-->
<div class="podcast-player-block wod-podcast-player-block">
<div class="title-block">
<h2>Podcast</h2>
</div>
<!-- <div class="subscribe-block">
<h3> <a rel="nofollow" href="https://itunes.apple.com/us/podcast/merriam-websters-word-day/id164829166?mt=2" class="subscribe-link" target="_blank"><span class="rss-podcast-icon"></span>SUBSCRIBE</a></h3>
</div> -->
<div class="podcast-container">
<div
id="art19-podcast-player"
class="art19-web-player awp-medium awp-theme-light-blue"
data-episode-id="7f3d298f-5054-4857-9766-ba4653a5b39e"
></div>
</div>
</div>
<span
class="scrollDepth"
data-eventname="wotd-podcast"
></span>
<hr class="blue-divide" />
<!--more wods widget-->
<div class="more-words-of-day-container" style="">
<div class="title-container">
<h2>More Words of the Day</h2>
</div>
<ul class="more-wod-items">
<li>
<h4>Apr 09</h4>
<h2>
<a
href="/word-of-the-day/auspicious-2023-04-09"
rel="nofollow"
>auspicious</a
>
</h2>
</li>
<li>
<h4>Apr 08</h4>
<h2>
<a
href="/word-of-the-day/circumscribe-2023-04-08"
rel="nofollow"
>circumscribe</a
>
</h2>
</li>
<li>
<h4>Apr 07</h4>
<h2>
<a
href="/word-of-the-day/equivocal-2023-04-07"
rel="nofollow"
>equivocal</a
>
</h2>
</li>
<li>
<h4>Apr 06</h4>
<h2>
<a
href="/word-of-the-day/seder-2023-04-06"
rel="nofollow"
>seder</a
>
</h2>
</li>
<li>
<h4>Apr 05</h4>
<h2>
<a
href="/word-of-the-day/gerrymander-2023-04-05"
rel="nofollow"
>gerrymander</a
>
</h2>
</li>
<li>
<h4>Apr 04</h4>
<h2>
<a
href="/word-of-the-day/belated-2023-04-04"
rel="nofollow"
>belated</a
>
</h2>
</li>
</ul>
<div class="cta-container">
<a href="/word-of-the-day/calendar"
>SEE ALL WORDS OF THE DAY</a
>
</div>
</div>
<span class="scrollDepth" data-eventname="wotd-more"></span>
</div>
</div>
<!-- end left side -->
<div class="right-rail d-none d-md-block h-100">
<div
id="AdThrive_Sidebar_1_tablet"
class="adthrive-ad adthrive-sidebar adthrive-sidebar-1 adthrive-ad-cls"
style="min-height: 250px"
data-google-query-id="CM-N4oLen_4CFcSJ7gEd0SsE_w"
>
<div
id="google_ads_iframe_/18190176,15510053/AdThrive_Sidebar_1/61575e8e934c48ea554b3caa_0__container__"
style="
border: 0pt none;
display: inline-block;
width: 300px;
height: 250px;
"
>
<iframe
frameborder="0"
src="https://128701c5cac5e55c1c540f649fc54f7a.safeframe.googlesyndication.com/safeframe/1-0-40/html/container.html"
id="google_ads_iframe_/18190176,15510053/AdThrive_Sidebar_1/61575e8e934c48ea554b3caa_0"
title="3rd party ad content"
name=""
scrolling="no"
marginwidth="0"
marginheight="0"
width="300"
height="250"
data-is-safeframe="true"
sandbox="allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation"
role="region"
aria-label="Advertisement"
tabindex="0"
data-google-container-id="3"
style="border: 0px; vertical-align: bottom"
data-load-complete="true"
></iframe>
</div>
</div>
<!-- right rail ad -->
<div class="right-rail-wgt-container">
<div
class="games-landing-page-redesign-container"
style="clear: both"
>
<div class="games-landing-section">
<div class="games-landing-section-row px-0">
<div class="row">
<div class="w-100 large-view">
<a
href="https://www.quordle.com/"
class="text-decoration-none games-landing-section-col games-landing-section-col-responsive games-landing-section-col-featured position-relative mb-0"
>
<div class="img-link">
<span class="lazyload-container ratio-4-3"
><img
data-sizes="auto"
alt="Play Quordle Game"
data-src="https://merriam-webster.com/assets/mw/static/images/games/external/quordle/485x364@1x.jpg"
data-srcset="https://merriam-webster.com/assets/mw/static/images/games/external/quordle/485x364@1x.jpg 1x, https://merriam-webster.com/assets/mw/static/images/games/external/quordle/485x364@2x.jpg 2x"
data-dim="485x364"
class="lazyloaded"
src="https://merriam-webster.com/assets/mw/static/images/games/external/quordle/485x364@1x.jpg"
srcset="
https://merriam-webster.com/assets/mw/static/images/games/external/quordle/485x364@1x.jpg 1x,
https://merriam-webster.com/assets/mw/static/images/games/external/quordle/485x364@2x.jpg 2x
"
data-loaded="true"
/></span>
</div>
<div
class="games-landing-section-img-panel-overlay"
>
<div>
<h3
class="games-landing-section-col-text fw-normal font-weight-normal"
>
Can you solve 4 words at once?
</h3>
<div
class="games-landing-section-col-nav-btn-container"
>
<button
class="games-landing-d-sm-hide gold"
>
Play
</button>
<button
class="games-landing-d-sm-only gold"
>
Play
</button>
</div>
</div>
</div>
<h3
class="games-landing-section-col-text my-3 games-landing-d-sm-hide"
>
Can you solve 4 words at once?
</h3>
<div
class="games-landing-section-col-nav-btn-container games-landing-d-sm-hide"
>
<button class="games-landing-d-sm-hide gold">
Play
</button>
<button class="games-landing-d-sm-only gold">
Play
</button>
</div>
</a>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- sticky right rail ad -->
<div
id="AdThrive_Sidebar_9_tablet"
class="adthrive-ad adthrive-sidebar adthrive-sidebar-9 adthrive-ad-cls adthrive-sticky"
style="min-height: 250px"
data-google-query-id="COvo1YLen_4CFaQ5RAgdluUC_A"
>
<div
id="google_ads_iframe_/18190176,15510053/AdThrive_Sidebar_9/61575e8e934c48ea554b3caa_0__container__"
style="border: 0pt none"
>
<iframe
id="google_ads_iframe_/18190176,15510053/AdThrive_Sidebar_9/61575e8e934c48ea554b3caa_0"
name="google_ads_iframe_/18190176,15510053/AdThrive_Sidebar_9/61575e8e934c48ea554b3caa_0"
title="3rd party ad content"
width="300"
height="250"
scrolling="no"
marginwidth="0"
marginheight="0"
frameborder="0"
role="region"
aria-label="Advertisement"
tabindex="0"
style="border: 0px; vertical-align: bottom"
data-load-complete="true"
data-google-container-id="2"
></iframe>
</div>
</div>
</div>
<!-- End right side -->
</div>
<!-- end main content -->
<!-- WW: Subscribe Unabridged-->
<div id="subscribe-unabridged" class="clearfix">
<div class="header">
Love words? Need even more definitions?
</div>
<p class="teaser">
Subscribe to America's largest dictionary and get thousands
more definitions and advanced search—ad free!
</p>
<a
class="subscribe-btn text-decoration-none"
rel="noopener"
target="_blank"
href="https://unabridged.merriam-webster.com/subscriber/register/p1?refc=INLINE_WOD_MWU"
>Merriam-Webster unabridged</a
>
</div>
</article>
</main>
</div>
<!-- End main wrapper -->
<div class="additional-content-area show-full-list">
<!-- show full list class extends area to show 4 items on mobile instead of 3 -->
<div class="additional-items additional-items-widget">
<span class="items__header">Words at Play</span>
<ul>
<li>
<a
class="item-card"
href="/words-at-play/12-longest-unusually-long-english-words"
>
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="top 10 unusually long and interesting words vol 2 embourgeoisement"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/top%2010%20unusually%20long%20and%20interesting%20words%20vol%202%20embourgeoisement-446-d03855602d5bf5706e68429129b89019@1x.jpg"
data-caption=""
data-credit=""
data-type="article"
data-dim="art-global-footer-recirc"
data-ret-pref="top 10 unusually long and interesting words vol 2 embourgeoisement-446-d03855602d5bf5706e68429129b89019"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/top%2010%20unusually%20long%20and%20interesting%20words%20vol%202%20embourgeoisement-446-d03855602d5bf5706e68429129b89019@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/top%2010%20unusually%20long%20and%20interesting%20words%20vol%202%20embourgeoisement-446-d03855602d5bf5706e68429129b89019@2x.jpg 2x"
pair-id="446"
image-id="446"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text"
>13 Unusually Long English Words</span
>
<p class="mell-gr235">
<span>Pulchritudinous and many more</span>
</p>
</div>
</a>
</li>
<li>
<a
class="item-card"
href="/words-at-play/mums-the-letter-when-letters-dont-say-a-thing"
>
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="image536372841"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/image536372841-4232-ace70d7a79d9aedc117d0b5c8daa40e3@1x.jpg"
data-caption=""
data-credit=""
data-type="article"
data-dim="art-global-footer-recirc"
data-ret-pref="image536372841-4232-ace70d7a79d9aedc117d0b5c8daa40e3"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/image536372841-4232-ace70d7a79d9aedc117d0b5c8daa40e3@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/image536372841-4232-ace70d7a79d9aedc117d0b5c8daa40e3@2x.jpg 2x"
pair-id="4234"
image-id="4232"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text"
>Every Letter Is Silent, Sometimes</span
>
<p class="mell-gr235">
<span>When each letter can be seen but not heard</span>
</p>
</div>
</a>
</li>
<li>
<a
class="item-card"
href="/words-at-play/8-nicer-ways-to-say-stupid"
>
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="image576109549"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/image576109549-4449-ca3d24dc53afcdd597ea3c01af71edf4@1x.jpg"
data-caption=""
data-credit=""
data-type="article"
data-dim="art-global-footer-recirc"
data-ret-pref="image576109549-4449-ca3d24dc53afcdd597ea3c01af71edf4"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/image576109549-4449-ca3d24dc53afcdd597ea3c01af71edf4@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/image576109549-4449-ca3d24dc53afcdd597ea3c01af71edf4@2x.jpg 2x"
pair-id="4451"
image-id="4449"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text"
>'Dunderhead' and Other ‘Nicer’ Ways to Say Stupid</span
>
<p class="mell-gr235">
<span>As illustrated by some very smart pups</span>
</p>
</div>
</a>
</li>
<li>
<a class="item-card" href="/time-traveler/">
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="merriam webster time traveler"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/merriam-webster-time-traveler-5771-630b7456c73849b51efad8bc5a55aae9@1x.jpg"
data-caption=""
data-credit=""
data-type="article"
data-dim="art-global-footer-recirc"
data-ret-pref="merriam-webster-time-traveler-5771-630b7456c73849b51efad8bc5a55aae9"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/merriam-webster-time-traveler-5771-630b7456c73849b51efad8bc5a55aae9@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/article/art-global-footer-recirc/merriam-webster-time-traveler-5771-630b7456c73849b51efad8bc5a55aae9@2x.jpg 2x"
pair-id="5773"
image-id="5771"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text"
>When Were Words First Used?</span
>
<p class="mell-gr235">
<span>Look up any year to find out</span>
</p>
</div>
</a>
</li>
</ul>
</div>
<div class="additional-items additional-items-widget">
<span class="items__header">Ask the Editors</span>
<ul>
<li>
<a class="item-card" href="/video/weird-plurals">
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="video moose goose weird plurals"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/video-moose-goose-weird-plurals-1138@1x.jpg"
data-caption=""
data-credit=""
data-type="video"
data-dim="vid-global-footer-recirc"
data-ret-pref="video-moose-goose-weird-plurals-1138"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/video-moose-goose-weird-plurals-1138@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/video-moose-goose-weird-plurals-1138@2x.jpg 2x"
pair-id="1140"
image-id="1138"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text">Weird Plurals</span>
<p class="mell-gr235">
<span
>One goose, two geese. One moose, two... moose.
Wh...</span
>
</p>
</div>
</a>
</li>
<li>
<a class="item-card" href="/video/irregardless">
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="video irregardless grammar peeve blend of the synonyms irrespective and regardless"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/video-irregardless-grammar-peeve-blend-of-the-synonyms-irrespective-and-regardless-1144@1x.jpg"
data-caption=""
data-credit=""
data-type="video"
data-dim="vid-global-footer-recirc"
data-ret-pref="video-irregardless-grammar-peeve-blend-of-the-synonyms-irrespective-and-regardless-1144"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/video-irregardless-grammar-peeve-blend-of-the-synonyms-irrespective-and-regardless-1144@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/video-irregardless-grammar-peeve-blend-of-the-synonyms-irrespective-and-regardless-1144@2x.jpg 2x"
pair-id="1146"
image-id="1144"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text">Irregardless</span>
<p class="mell-gr235">
<span
>It is in fact a real word (but that doesn't mean
...</span
>
</p>
</div>
</a>
</li>
<li>
<a class="item-card" href="/video/bring-vs-take">
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="bring vs take video"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/bring-vs-take-video-1587@1x.jpg"
data-caption=""
data-credit=""
data-type="video"
data-dim="vid-global-footer-recirc"
data-ret-pref="bring-vs-take-video-1587"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/bring-vs-take-video-1587@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/bring-vs-take-video-1587@2x.jpg 2x"
pair-id="1595"
image-id="1587"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text">Bring vs. Take</span>
<p class="mell-gr235">
<span
>Both words imply motion, but the difference may
b...</span
>
</p>
</div>
</a>
</li>
<li>
<a class="item-card" href="/video/defenestration">
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="video defenesetration"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/video-defenesetration-1163@1x.jpg"
data-caption=""
data-credit=""
data-type="video"
data-dim="vid-global-footer-recirc"
data-ret-pref="video-defenesetration-1163"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/video-defenesetration-1163@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/video/vid-global-footer-recirc/video-defenesetration-1163@2x.jpg 2x"
pair-id="1165"
image-id="1163"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text">Defenestration</span>
<p class="mell-gr235">
<span
>The fascinating story behind many people's
favori...</span
>
</p>
</div>
</a>
</li>
</ul>
</div>
<div class="additional-items additional-items-widget">
<span class="items__header">Word Games</span>
<ul>
<li>
<a class="item-card" href="/games/name-that-hat">
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="back-of-head-mortarboard"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-global-footer-recirc/back-of-head-mortarboard-10064-e628383268d81f98a3a47ca0f9d93478@1x.jpg"
data-caption="mortarboard"
data-credit="Getty"
data-type="quiz"
data-dim="quiz-global-footer-recirc"
data-ret-pref="back-of-head-mortarboard-10064-e628383268d81f98a3a47ca0f9d93478"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-global-footer-recirc/back-of-head-mortarboard-10064-e628383268d81f98a3a47ca0f9d93478@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-global-footer-recirc/back-of-head-mortarboard-10064-e628383268d81f98a3a47ca0f9d93478@2x.jpg 2x"
pair-id="10066"
image-id="10064"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text">Name That Hat!</span>
<p class="mell-gr235">
<span>Time to put on your thinking cap.</span>
</p>
<p class="quiz-link">Take the quiz</p>
</div>
</a>
</li>
<li>
<a class="item-card" href="/games/ntt-flowers-quiz">
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="name that thing flower edition"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-global-footer-recirc/name%20that%20thing%20flower%20edition-3542-d832e19a67f24cf3b20a4d856bb7ced6@1x.jpg"
data-caption=""
data-credit=""
data-type="quiz"
data-dim="quiz-global-footer-recirc"
data-ret-pref="name that thing flower edition-3542-d832e19a67f24cf3b20a4d856bb7ced6"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-global-footer-recirc/name%20that%20thing%20flower%20edition-3542-d832e19a67f24cf3b20a4d856bb7ced6@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-global-footer-recirc/name%20that%20thing%20flower%20edition-3542-d832e19a67f24cf3b20a4d856bb7ced6@2x.jpg 2x"
pair-id="3545"
image-id="3542"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text">Name That Flower</span>
<p class="mell-gr235">
<span
>Can you tell the difference between a lilac and
a...</span
>
</p>
<p class="quiz-link">Take the quiz</p>
</div>
</a>
</li>
<li>
<a class="item-card" href="/games/name-that-thing">
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="Name That Thing"
data-src="https://merriam-webster.com/assets/mw/static/images/old-quizzes/name-that-thing/261x174@1x.jpg"
data-dim="261x174"
data-srcset="https://merriam-webster.com/assets/mw/static/images/old-quizzes/name-that-thing/261x174@1x.jpg 1x, https://merriam-webster.com/assets/mw/static/images/old-quizzes/name-that-thing/261x174@2x.jpg 2x"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text">Name That Thing</span>
<p class="mell-gr235">
<span
>You know what it looks like… but what is it
cal...</span
>
</p>
<p class="quiz-link">Take the quiz</p>
</div>
</a>
</li>
<li>
<a
class="item-card"
href="/word-games/scripps-spelling-bee-quiz"
>
<div class="item-content">
<span
><span class="lazyload-container ratio-3-2"
><img
data-sizes="auto"
alt="winning words from the national spelling bee logo"
is_retina="true"
data-src="https://merriam-webster.com/assets/mw/images/quiz/quiz-global-footer-recirc/winning-words-from-the-national-spelling-bee-logo-3736-9bdcdf51c9576d8b4572b774b3ba9e75@1x.jpg"
data-caption=""
data-credit=""
data-type="quiz"
data-dim="quiz-global-footer-recirc"
data-ret-pref="winning-words-from-the-national-spelling-bee-logo-3736-9bdcdf51c9576d8b4572b774b3ba9e75"
data-ret-x="1"
data-srcset="https://merriam-webster.com/assets/mw/images/quiz/quiz-global-footer-recirc/winning-words-from-the-national-spelling-bee-logo-3736-9bdcdf51c9576d8b4572b774b3ba9e75@1x.jpg 1x, https://merriam-webster.com/assets/mw/images/quiz/quiz-global-footer-recirc/winning-words-from-the-national-spelling-bee-logo-3736-9bdcdf51c9576d8b4572b774b3ba9e75@2x.jpg 2x"
pair-id="3739"
image-id="3736"
class="lazyload"
src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" /></span
></span>
<span class="item-title-text">Spelling Bee Quiz</span>
<p class="mell-gr235">
<span
>Can you outdo past winners of the National
Spelli...</span
>
</p>
<p class="quiz-link">Take the quiz</p>
</div>
</a>
</li>
</ul>
</div>
</div>
<!-- End additional content -->
<script>
window.mwdata.legacyUbWodSubscribe = false;
window.mwdata.legacyUbWodEmail = "";
</script>
<!-- adhesion -->
<footer class="global-footer">
<div class="footer-mast clearfix">
<div class="mw-logo-section lazyload">
<a href="/" class="footer-logo">Merriam Webster</a>
</div>
<div class="footer-mast-content clearfix">
<div class="footer-subscribe-block">
<div class="footer-subscribe-msg">
<p>Learn a new word every day. Delivered to your inbox!</p>
</div>
<form
data-medium="footer"
class="footer-subscribe js-wod-subscribe-frm"
>
<input
class="footer-subscribe-field"
type="text"
name="email"
value=""
aria-label="Sign up for Merriam-Webster's Word of the Day newsletter"
placeholder="Your email address"
/>
<input
class="footer-subscribe-button"
type="submit"
name="submit"
aria-label="Subscribe"
value="SUBSCRIBE"
/>
<input
class="footer-subscribe-button hidden arrow"
type="submit"
name="submit"
value=">"
/>
</form>
</div>
<div class="footer-dictionaries">
<p>OTHER MERRIAM-WEBSTER DICTIONARIES</p>
<div class="other-dictionaries">
<ul>
<li>
<a href="https://unabridged.merriam-webster.com/"
>MERRIAM-WEBSTER'S UNABRIDGED DICTIONARY</a
>
</li>
<li>
<a href="https://scrabble.merriam.com/"
>SCRABBLE<sup>®</sup> WORD FINDER</a
>
</li>
<li>
<a href="https://dictionaryapi.com/"
>MERRIAM-WEBSTER DICTIONARY API</a
>
</li>
</ul>
<ul>
<li>
<a href="https://www.nglish.com/spanish/en/"
>NGLISH - SPANISH-ENGLISH TRANSLATION</a
>
</li>
<li>
<a href="https://arabic.britannicaenglish.com/en/"
>BRITANNICA ENGLISH - ARABIC TRANSLATION</a
>
</li>
</ul>
</div>
</div>
<div class="follow-us lazyload">
<p>FOLLOW US</p>
<div class="follow-links">
<ul>
<li>
<a
href="https://www.facebook.com/merriamwebster"
rel="noopener"
target="_blank"
class="social-link social-fb"
>Facebook</a
>
</li>
<li>
<a
href="https://twitter.com/merriamwebster"
rel="noopener"
target="_blank"
class="social-link social-tw"
>Twitter</a
>
</li>
<li>
<a
href="https://www.youtube.com/user/MerriamWebsterOnline"
rel="noopener"
target="_blank"
class="social-link social-play"
>YouTube</a
>
</li>
<li>
<a
href="https://www.instagram.com/merriamwebster/"
rel="noopener"
target="_blank"
class="social-link social-ig"
>Instagram</a
>
</li>
</ul>
</div>
</div>
</div>
</div>
<div class="footer-foot clearfix footer-oa cafemedia-footer-foot">
<div class="footer-foot-content clearfix">
<ul class="footer-menu browse-dictionary">
<li>
<a href="/browse/dictionary/a">Browse the Dictionary:</a>
</li>
<li><a href="/browse/dictionary/a">a</a></li>
<li><a href="/browse/dictionary/b">b</a></li>
<li><a href="/browse/dictionary/c">c</a></li>
<li><a href="/browse/dictionary/d">d</a></li>
<li><a href="/browse/dictionary/e">e</a></li>
<li><a href="/browse/dictionary/f">f</a></li>
<li><a href="/browse/dictionary/g">g</a></li>
<li><a href="/browse/dictionary/h">h</a></li>
<li><a href="/browse/dictionary/i">i</a></li>
<li><a href="/browse/dictionary/j">j</a></li>
<li><a href="/browse/dictionary/k">k</a></li>
<li><a href="/browse/dictionary/l">l</a></li>
<li><a href="/browse/dictionary/m">m</a></li>
<li><a href="/browse/dictionary/n">n</a></li>
<li><a href="/browse/dictionary/o">o</a></li>
<li><a href="/browse/dictionary/p">p</a></li>
<li><a href="/browse/dictionary/q">q</a></li>
<li><a href="/browse/dictionary/r">r</a></li>
<li><a href="/browse/dictionary/s">s</a></li>
<li><a href="/browse/dictionary/t">t</a></li>
<li><a href="/browse/dictionary/u">u</a></li>
<li><a href="/browse/dictionary/v">v</a></li>
<li><a href="/browse/dictionary/w">w</a></li>
<li><a href="/browse/dictionary/x">x</a></li>
<li><a href="/browse/dictionary/y">y</a></li>
<li><a href="/browse/dictionary/z">z</a></li>
<li><a href="/browse/dictionary/0">0-9</a></li>
<li><a href="/browse/dictionary/bio">BIO</a></li>
<li><a href="/browse/dictionary/geo">GEO</a></li>
</ul>
<ul class="footer-menu">
<li>
<a href="/">Home <span class="rborder"></span></a>
</li>
<li>
<a href="/help">Help <span class="rborder"></span></a>
</li>
<li>
<a href="/about-us">About Us <span class="rborder"></span></a>
</li>
<li>
<a
href="https://shop.merriam-webster.com/?utm_source=mwsite&utm_medium=nav&utm_content=footer"
>Shop <span class="rborder"></span
></a>
</li>
<li>
<a href="/advertising"
>Advertising Info <span class="rborder"></span
></a>
</li>
<li>
<a
href="https://www.dictionaryapi.com/"
rel="noopener"
target="_blank"
>Dictionary API <span class="rborder"></span
></a>
</li>
<li>
<a href="/contact-us"
>Contact Us <span class="rborder"></span
></a>
</li>
<li>
<a
href="https://unabridged.merriam-webster.com/subscriber/register/p1?refc=FOOTER_JOINMWU"
rel="noopener"
target="_blank"
>Join MWU <span class="rborder"></span
></a>
</li>
<li>
<a href="/video">Videos <span class="rborder"></span></a>
</li>
<li>
<a href="/words-at-play/word-of-the-year"
>Word of the Year <span class="rborder"></span
></a>
</li>
<li>
<a href="/kids"
>Kid's Dictionary <span class="rborder"></span
></a>
</li>
<li>
<a href="/legal"
>Law Dictionary <span class="rborder"></span
></a>
</li>
<li>
<a href="/medical"
>Medical Dictionary <span class="rborder"></span
></a>
</li>
<li>
<a href="/privacy-policy"
>Privacy Policy <span class="rborder"></span
></a>
</li>
<li class="last"><a href="/terms-of-use">Terms of Use</a></li>
</ul>
<ul class="footer-menu">
<li>
<a href="/browse/thesaurus/a"
>Browse the Thesaurus <span class="rborder"></span
></a>
</li>
<li>
<a href="/browse/medical/a"
>Browse the Medical Dictionary <span class="rborder"></span
></a>
</li>
<li>
<a href="/browse/legal/a"
>Browse the Legal Dictionary <span class="rborder"></span
></a>
</li>
<li class="last">
<a href="/browse/kids/a">Browse the Kid's Dictionary</a>
</li>
</ul>
<p class="copyright">© 2023 Merriam-Webster, Incorporated</p>
</div>
</div>
</footer>
</div>
</div>
<script
defer=""
src="https://merriam-webster.com/assets/mw/jwplayer-8.10.3/jwplayer.js"
></script>
<script
defer=""
src="/dist-cross-dungarees/2023-04-05_15-17-24-b38e9d74/compiled/js/js-word-of-the-day.16152c72b17cce4b5411.js"
></script>
<link
rel="stylesheet"
href="/dist-cross-dungarees/2023-04-05_15-17-24-b38e9d74/compiled/css/style-art19.6c44b1379c072caad9b3.css"
media="screen"
/>
<script
src="https://web-player.art19.com/assets/current.js"
type="text/javascript"
async=""
></script>
<script type="text/javascript" id="">
(function (a, e, b, f, g, c, d) {
a[b] =
a[b] ||
function () {
(a[b].q = a[b].q || []).push(arguments);
};
c = e.createElement(f);
c.async = 1;
c.src = "https://www.clarity.ms/tag/" + g + "?ref\x3dgtm2";
d = e.getElementsByTagName(f)[0];
d.parentNode.insertBefore(c, d);
})(window, document, "clarity", "script", "fq2f5zdaqe");
</script>
<script type="text/javascript" id="">
var scrEm = document.createElement("script");
scrEm.setAttribute("id", "funnel-relay-installer");
scrEm.setAttribute(
"data-customer-id",
"merriamwebster_6e5b0_merriamwebster"
);
scrEm.setAttribute("data-property-id", "PROPERTY_ID");
scrEm.setAttribute("data-autorun", "true");
scrEm.setAttribute("async", "true");
scrEm.setAttribute(
"src",
"https://cdn-magiclinks.trackonomics.net/client/static/v2/merriamwebster_6e5b0_merriamwebster.js"
);
document.head.appendChild(scrEm);
</script>
<iframe
src="https://ads.adthrive.com/builds/core/16dfc7b/html/topics.html"
id="adthrive-topics-api"
style="display: none"
></iframe
><iframe
src="https://ads.adthrive.com/builds/core/16dfc7b/html/rnf.html"
id="adthrive-mcmp"
style="display: none"
></iframe
><iframe
id="__uspapiLocator"
name="__uspapiLocator"
style="display: none"
></iframe>
<div id="adthrive-ccpa-modal" class="adthrive-ccpa-modal">
<div id="adthrive-ccpa-modal-content" class="adthrive-ccpa-modal-content">
<div id="adthrive-ccpa-modal-close-btn-container"><span>✕</span></div>
<div id="adthrive-ccpa-modal-title">
Do Not Sell Or Share My Personal Information
</div>
<span id="adthrive-ccpa-modal-language"
>You have chosen to opt-out of the sale or sharing of your information
from this site and any of its affiliates. To opt back in please click
the "Customize my ad experience" link.<br />
<br />This site collects information through the use of cookies and
other tracking tools. Cookies and these tools do not contain any
information that personally identifies a user, but personal
information that would be stored about you may be linked to the
information stored in and obtained from them. This information would
be used and shared for Analytics, Ad Serving, Interest Based
Advertising, among other purposes.<br />
<br />For more information please visit this site's Privacy
Policy.</span
>
<div class="adthrive-ccpa-lower-buttons-container">
<div
id="adthrive-ccpa-modal-cancel-btn"
class="adthrive-ccpa-modal-btn"
>
CANCEL
</div>
<div
id="adthrive-ccpa-modal-continue-btn"
class="adthrive-ccpa-modal-btn"
>
CONTINUE
</div>
</div>
</div>
</div>
<iframe
id="__gppLocator"
name="__gppLocator"
style="display: none"
></iframe>
<div
id="AdThrive_Footer_1_tablet"
class="adthrive-ad adthrive-footer adthrive-footer-1 adthrive-ad-cls adthrive-sticky"
style="min-height: 90px"
data-google-query-id="CNrdvYLen_4CFfswRAgdeIYBmQ"
>
<div
id="google_ads_iframe_/18190176,15510053/AdThrive_Footer_1/61575e8e934c48ea554b3caa_0__container__"
style="
border: 0pt none;
display: inline-block;
width: 728px;
height: 90px;
"
>
<iframe
frameborder="0"
src="https://128701c5cac5e55c1c540f649fc54f7a.safeframe.googlesyndication.com/safeframe/1-0-40/html/container.html"
id="google_ads_iframe_/18190176,15510053/AdThrive_Footer_1/61575e8e934c48ea554b3caa_0"
title="3rd party ad content"
name=""
scrolling="no"
marginwidth="0"
marginheight="0"
width="728"
height="90"
data-is-safeframe="true"
sandbox="allow-forms allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-top-navigation-by-user-activation"
role="region"
aria-label="Advertisement"
tabindex="0"
data-google-container-id="1"
style="border: 0px; vertical-align: bottom"
data-load-complete="true"
></iframe>
</div>
</div>
<div class="adthrive-comscore adthrive-footer-message">
<div id="adthrive-ccpa-link" class="adthrive-ccpa-link">
Information from your device can be used to personalize your ad
experience. <br /><br /><a id="ccpaTag"
>Do not sell or share my personal information.</a
>
</div>
</div>
<script
type="text/javascript"
async="true"
src="https://cdn.brandmetrics.com/scripts/bundle/65568.js?sid=f9816ecc-b51b-4747-bc3e-1ea86a0677a2&toploc=www.merriam-webster.com"
></script>
<iframe
src="https://128701c5cac5e55c1c540f649fc54f7a.safeframe.googlesyndication.com/safeframe/1-0-40/html/container.html"
style="visibility: hidden; display: none"
></iframe>
<div id="confiant_tag_holder" style="display: none"></div>
<iframe
src="https://s.amazon-adsystem.com/iu3?cm3ppd=1&d=dtb-pub&csif=t&dl=n-mediagrid_n-index_n-sharethrough_pm-db5_rbd_n-vmg_ox-db5_an-db5_3lift"
style="display: none"
></iframe
><iframe
height="0"
width="0"
frameborder="0"
src="https://pandg.tapad.com/tag?referrer_url=&page_url=https%3A%2F%2Fwww.merriam-webster.com%2Fword-of-the-day&owner=P%26G&bp_id=cafemedia&ch=%7B%22architecture%22%3A%22%22%2C%22bitness%22%3A%22%22%2C%22brands%22%3A%5B%5D%2C%22fullVersionList%22%3A%5B%5D%2C%22mobile%22%3Afalse%2C%22model%22%3A%22%22%2C%22platform%22%3A%22%22%2C%22platformVersion%22%3A%22%22%7D&initiator=js"
style="display: none"
></iframe>
<script
type="text/javascript"
src="https://pghub.io/js/pandg-sdk.js"
></script>
</body>
<iframe
sandbox="allow-scripts allow-same-origin"
id="183fa1a6ae092f6d"
frameborder="0"
allowtransparency="true"
marginheight="0"
marginwidth="0"
width="0"
hspace="0"
vspace="0"
height="0"
style="height: 0px; width: 0px; display: none"
scrolling="no"
src="https://u.openx.net/w/1.0/cm?id=891039ac-a916-42bb-a651-4be9e3b201da&ph=a3aece0c-9e80-4316-8deb-faf804779bd1&gdpr=&gdpr_consent=&r=https%3A%2F%2Fprebid-server.rubiconproject.com%2Fsetuid%3Fbidder%3Dopenx%26gdpr%3D%26gdpr_consent%3D%26us_privacy%3D1YNY%26gpp%3D%26gpp_sid%3D%26account%3D%26f%3Db%26uid%3D"
>
</iframe
><iframe
sandbox="allow-scripts allow-same-origin"
id="194ea54971259529"
frameborder="0"
allowtransparency="true"
marginheight="0"
marginwidth="0"
width="0"
hspace="0"
vspace="0"
height="0"
style="height: 0px; width: 0px; display: none"
scrolling="no"
src="https://ads.pubmatic.com/AdServer/js/user_sync.html?gdpr=&gdpr_consent=&us_privacy=1YNY&predirect=https%3A%2F%2Fprebid-server.rubiconproject.com%2Fsetuid%3Fbidder%3Dpubmatic%26gdpr%3D%26gdpr_consent%3D%26us_privacy%3D1YNY%26gpp%3D%26gpp_sid%3D%26account%3D%26f%3Db%26uid%3D"
>
</iframe>
</html>
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/hf.ts
|
import { HfInference, HfInferenceEndpoint } from "@huggingface/inference";
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
/**
* Interface that extends EmbeddingsParams and defines additional
* parameters specific to the HuggingFaceInferenceEmbeddings class.
*/
export interface HuggingFaceInferenceEmbeddingsParams extends EmbeddingsParams {
apiKey?: string;
model?: string;
endpointUrl?: string;
}
/**
* Class that extends the Embeddings class and provides methods for
* generating embeddings using Hugging Face models through the
* HuggingFaceInference API.
*/
export class HuggingFaceInferenceEmbeddings
extends Embeddings
implements HuggingFaceInferenceEmbeddingsParams
{
apiKey?: string;
model: string;
endpointUrl?: string;
client: HfInference | HfInferenceEndpoint;
constructor(fields?: HuggingFaceInferenceEmbeddingsParams) {
super(fields ?? {});
this.model = fields?.model ?? "BAAI/bge-base-en-v1.5";
this.apiKey =
fields?.apiKey ?? getEnvironmentVariable("HUGGINGFACEHUB_API_KEY");
this.endpointUrl = fields?.endpointUrl;
this.client = this.endpointUrl
? new HfInference(this.apiKey).endpoint(this.endpointUrl)
: new HfInference(this.apiKey);
}
async _embed(texts: string[]): Promise<number[][]> {
// replace newlines, which can negatively affect performance.
const clean = texts.map((text) => text.replace(/\n/g, " "));
return this.caller.call(() =>
this.client.featureExtraction({
model: this.model,
inputs: clean,
})
) as Promise<number[][]>;
}
/**
* Method that takes a document as input and returns a promise that
* resolves to an embedding for the document. It calls the _embed method
* with the document as the input and returns the first embedding in the
* resulting array.
* @param document Document to generate an embedding for.
* @returns Promise that resolves to an embedding for the document.
*/
embedQuery(document: string): Promise<number[]> {
return this._embed([document]).then((embeddings) => embeddings[0]);
}
/**
* Method that takes an array of documents as input and returns a promise
* that resolves to a 2D array of embeddings for each document. It calls
* the _embed method with the documents as the input.
* @param documents Array of documents to generate embeddings for.
* @returns Promise that resolves to a 2D array of embeddings for each document.
*/
embedDocuments(documents: string[]): Promise<number[][]> {
return this._embed(documents);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/baidu_qianfan.ts
|
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
/** @deprecated Install and import from @langchain/baidu-qianfan instead. */
export interface BaiduQianfanEmbeddingsParams extends EmbeddingsParams {
/** Model name to use */
modelName: "embedding-v1" | "bge_large_zh" | "bge_large_en" | "tao-8k";
/**
* Timeout to use when making requests to BaiduQianfan.
*/
timeout?: number;
/**
* The maximum number of characters allowed for embedding in a single request varies by model:
* - Embedding-V1 model: up to 1000 characters
* - bge-large-zh model: up to 2000 characters
* - bge-large-en model: up to 2000 characters
* - tao-8k model: up to 28000 characters
*
* Note: These limits are model-specific and should be adhered to for optimal performance.
*/
batchSize?: number;
/**
* Whether to strip new lines from the input text.
*/
stripNewLines?: boolean;
}
interface EmbeddingCreateParams {
input: string[];
}
interface EmbeddingResponse {
data: { object: "embedding"; index: number; embedding: number[] }[];
usage: {
prompt_tokens: number;
total_tokens: number;
};
id: string;
}
interface EmbeddingErrorResponse {
error_code: number | string;
error_msg: string;
}
export class BaiduQianfanEmbeddings
extends Embeddings
implements BaiduQianfanEmbeddingsParams
{
modelName: BaiduQianfanEmbeddingsParams["modelName"] = "embedding-v1";
batchSize = 16;
stripNewLines = true;
baiduApiKey: string;
baiduSecretKey: string;
accessToken: string;
constructor(
fields?: Partial<BaiduQianfanEmbeddingsParams> & {
verbose?: boolean;
baiduApiKey?: string;
baiduSecretKey?: string;
}
) {
const fieldsWithDefaults = { maxConcurrency: 2, ...fields };
super(fieldsWithDefaults);
const baiduApiKey =
fieldsWithDefaults?.baiduApiKey ??
getEnvironmentVariable("BAIDU_API_KEY");
const baiduSecretKey =
fieldsWithDefaults?.baiduSecretKey ??
getEnvironmentVariable("BAIDU_SECRET_KEY");
if (!baiduApiKey) {
throw new Error("Baidu API key not found");
}
if (!baiduSecretKey) {
throw new Error("Baidu Secret key not found");
}
this.baiduApiKey = baiduApiKey;
this.baiduSecretKey = baiduSecretKey;
this.modelName = fieldsWithDefaults?.modelName ?? this.modelName;
if (this.modelName === "tao-8k") {
if (fieldsWithDefaults?.batchSize && fieldsWithDefaults.batchSize !== 1) {
throw new Error(
"tao-8k model supports only a batchSize of 1. Please adjust your batchSize accordingly"
);
}
this.batchSize = 1;
} else {
this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;
}
this.stripNewLines =
fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;
}
/**
* Method to generate embeddings for an array of documents. Splits the
* documents into batches and makes requests to the BaiduQianFan API to generate
* embeddings.
* @param texts Array of documents to generate embeddings for.
* @returns Promise that resolves to a 2D array of embeddings for each document.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
const batches = chunkArray(
this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts,
this.batchSize
);
const batchRequests = batches.map((batch) => {
const params = this.getParams(batch);
return this.embeddingWithRetry(params);
});
const batchResponses = await Promise.all(batchRequests);
const embeddings: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batch = batches[i];
const batchResponse = batchResponses[i] || [];
for (let j = 0; j < batch.length; j += 1) {
embeddings.push(batchResponse[j]);
}
}
return embeddings;
}
/**
* Method to generate an embedding for a single document. Calls the
* embeddingWithRetry method with the document as the input.
* @param text Document to generate an embedding for.
* @returns Promise that resolves to an embedding for the document.
*/
async embedQuery(text: string): Promise<number[]> {
const params = this.getParams([
this.stripNewLines ? text.replace(/\n/g, " ") : text,
]);
const embeddings = (await this.embeddingWithRetry(params)) || [[]];
return embeddings[0];
}
/**
* Method to generate an embedding params.
* @param texts Array of documents to generate embeddings for.
* @returns an embedding params.
*/
private getParams(
texts: EmbeddingCreateParams["input"]
): EmbeddingCreateParams {
return {
input: texts,
};
}
/**
* Private method to make a request to the BaiduAI API to generate
* embeddings. Handles the retry logic and returns the response from the
* API.
* @param request Request to send to the BaiduAI API.
* @returns Promise that resolves to the response from the API.
*/
private async embeddingWithRetry(body: EmbeddingCreateParams) {
if (!this.accessToken) {
this.accessToken = await this.getAccessToken();
}
return fetch(
`https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/embeddings/${this.modelName}?access_token=${this.accessToken}`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(body),
}
).then(async (response) => {
const embeddingData: EmbeddingResponse | EmbeddingErrorResponse =
await response.json();
if ("error_code" in embeddingData && embeddingData.error_code) {
throw new Error(
`${embeddingData.error_code}: ${embeddingData.error_msg}`
);
}
return (embeddingData as EmbeddingResponse).data.map(
({ embedding }) => embedding
);
});
}
/**
* Method that retrieves the access token for making requests to the Baidu
* API.
* @returns The access token for making requests to the Baidu API.
*/
private async getAccessToken() {
const url = `https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=${this.baiduApiKey}&client_secret=${this.baiduSecretKey}`;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Accept: "application/json",
},
});
if (!response.ok) {
const text = await response.text();
const error = new Error(
`Baidu get access token failed with status code ${response.status}, response: ${text}`
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(error as any).response = response;
throw error;
}
const json = await response.json();
return json.access_token;
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/llama_cpp.ts
|
/* eslint-disable import/no-extraneous-dependencies */
import { LlamaModel, LlamaContext, getLlama } from "node-llama-cpp";
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
import {
LlamaBaseCppInputs,
createLlamaModel,
createLlamaContext,
} from "../utils/llama_cpp.js";
/**
* Note that the modelPath is the only required parameter. For testing you
* can set this in the environment variable `LLAMA_PATH`.
*/
export interface LlamaCppEmbeddingsParams
extends LlamaBaseCppInputs,
EmbeddingsParams {}
/**
* @example
* ```typescript
* // Initialize LlamaCppEmbeddings with the path to the model file
* const embeddings = await LlamaCppEmbeddings.initialize({
* modelPath: llamaPath,
* });
*
* // Embed a query string using the Llama embeddings
* const res = embeddings.embedQuery("Hello Llama!");
*
* // Output the resulting embeddings
* console.log(res);
*
* ```
*/
export class LlamaCppEmbeddings extends Embeddings {
_model: LlamaModel;
_context: LlamaContext;
public constructor(inputs: LlamaCppEmbeddingsParams) {
super(inputs);
const _inputs = inputs;
_inputs.embedding = true;
}
/**
* Initializes the llama_cpp model for usage in the embeddings wrapper.
* @param inputs - the inputs passed onto the model.
* @returns A Promise that resolves to the LlamaCppEmbeddings type class.
*/
public static async initialize(
inputs: LlamaBaseCppInputs
): Promise<LlamaCppEmbeddings> {
const instance = new LlamaCppEmbeddings(inputs);
const llama = await getLlama();
instance._model = await createLlamaModel(inputs, llama);
instance._context = await createLlamaContext(instance._model, inputs);
return instance;
}
/**
* Generates embeddings for an array of texts.
* @param texts - An array of strings to generate embeddings for.
* @returns A Promise that resolves to an array of embeddings.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
const tokensArray = [];
for (const text of texts) {
const encodings = await this.caller.call(
() =>
new Promise((resolve) => {
resolve(this._model.tokenize(text));
})
);
tokensArray.push(encodings);
}
const embeddings: number[][] = [];
for (const tokens of tokensArray) {
const embedArray: number[] = [];
for (let i = 0; i < tokens.length; i += 1) {
const nToken: number = +tokens[i];
embedArray.push(nToken);
}
embeddings.push(embedArray);
}
return embeddings;
}
/**
* Generates an embedding for a single text.
* @param text - A string to generate an embedding for.
* @returns A Promise that resolves to an array of numbers representing the embedding.
*/
async embedQuery(text: string): Promise<number[]> {
const tokens: number[] = [];
const encodings = await this.caller.call(
() =>
new Promise((resolve) => {
resolve(this._model.tokenize(text));
})
);
for (let i = 0; i < encodings.length; i += 1) {
const token: number = +encodings[i];
tokens.push(token);
}
return tokens;
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/bedrock.ts
|
import {
BedrockRuntimeClient,
InvokeModelCommand,
} from "@aws-sdk/client-bedrock-runtime";
import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings";
import type { CredentialType } from "../utils/bedrock/index.js";
/**
* @deprecated The BedrockEmbeddings integration has been moved to the `@langchain/aws` package. Import from `@langchain/aws` instead.
*
* Interface that extends EmbeddingsParams and defines additional
* parameters specific to the BedrockEmbeddings class.
*/
export interface BedrockEmbeddingsParams extends EmbeddingsParams {
/**
* Model Name to use. Defaults to `amazon.titan-embed-text-v1` if not provided
*
*/
model?: string;
/**
* A client provided by the user that allows them to customze any
* SDK configuration options.
*/
client?: BedrockRuntimeClient;
region?: string;
credentials?: CredentialType;
}
/**
* @deprecated The BedrockEmbeddings integration has been moved to the `@langchain/aws` package. Import from `@langchain/aws` instead.
*
* Class that extends the Embeddings class and provides methods for
* generating embeddings using the Bedrock API.
* @example
* ```typescript
* const embeddings = new BedrockEmbeddings({
* region: "your-aws-region",
* credentials: {
* accessKeyId: "your-access-key-id",
* secretAccessKey: "your-secret-access-key",
* },
* model: "amazon.titan-embed-text-v1",
* });
*
* // Embed a query and log the result
* const res = await embeddings.embedQuery(
* "What would be a good company name for a company that makes colorful socks?"
* );
* console.log({ res });
* ```
*/
export class BedrockEmbeddings
extends Embeddings
implements BedrockEmbeddingsParams
{
model: string;
client: BedrockRuntimeClient;
batchSize = 512;
constructor(fields?: BedrockEmbeddingsParams) {
super(fields ?? {});
this.model = fields?.model ?? "amazon.titan-embed-text-v1";
this.client =
fields?.client ??
new BedrockRuntimeClient({
region: fields?.region,
credentials: fields?.credentials,
});
}
/**
* Protected method to make a request to the Bedrock API to generate
* embeddings. Handles the retry logic and returns the response from the
* API.
* @param request Request to send to the Bedrock API.
* @returns Promise that resolves to the response from the API.
*/
protected async _embedText(text: string): Promise<number[]> {
return this.caller.call(async () => {
try {
// replace newlines, which can negatively affect performance.
const cleanedText = text.replace(/\n/g, " ");
const res = await this.client.send(
new InvokeModelCommand({
modelId: this.model,
body: JSON.stringify({
inputText: cleanedText,
}),
contentType: "application/json",
accept: "application/json",
})
);
const body = new TextDecoder().decode(res.body);
return JSON.parse(body).embedding;
} catch (e) {
console.error({
error: e,
});
// eslint-disable-next-line no-instanceof/no-instanceof
if (e instanceof Error) {
throw new Error(
`An error occurred while embedding documents with Bedrock: ${e.message}`
);
}
throw new Error(
"An error occurred while embedding documents with Bedrock"
);
}
});
}
/**
* Method that takes a document as input and returns a promise that
* resolves to an embedding for the document. It calls the _embedText
* method with the document as the input.
* @param document Document for which to generate an embedding.
* @returns Promise that resolves to an embedding for the input document.
*/
embedQuery(document: string): Promise<number[]> {
return this.caller.callWithOptions(
{},
this._embedText.bind(this),
document
);
}
/**
* Method to generate embeddings for an array of texts. Calls _embedText
* method which batches and handles retry logic when calling the AWS Bedrock API.
* @param documents Array of texts for which to generate embeddings.
* @returns Promise that resolves to a 2D array of embeddings for each input document.
*/
async embedDocuments(documents: string[]): Promise<number[][]> {
return Promise.all(documents.map((document) => this._embedText(document)));
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/jina.ts
|
import { existsSync, readFileSync } from "fs";
import { parse } from "url";
import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
/**
* The default Jina API URL for embedding requests.
*/
const JINA_API_URL = "https://api.jina.ai/v1/embeddings";
/**
* Check if a URL is a local file.
* @param url - The URL to check.
* @returns True if the URL is a local file, False otherwise.
*/
function isLocal(url: string): boolean {
const urlParsed = parse(url);
if (urlParsed.protocol === null || urlParsed.protocol === "file:") {
return existsSync(urlParsed.pathname || "");
}
return false;
}
/**
* Get the bytes string of a file.
* @param filePath - The path to the file.
* @returns The bytes string of the file.
*/
function getBytesStr(filePath: string): string {
const imageFile = readFileSync(filePath);
return Buffer.from(imageFile).toString("base64");
}
/**
* Input parameters for the Jina embeddings
*/
export interface JinaEmbeddingsParams extends EmbeddingsParams {
/**
* The API key to use for authentication.
* If not provided, it will be read from the `JINA_API_KEY` environment variable.
*/
apiKey?: string;
/**
* The model ID to use for generating embeddings.
* Default: `jina-embeddings-v2-base-en`
*/
model?: string;
}
/**
* Response from the Jina embeddings API.
*/
export interface JinaEmbeddingsResponse {
/**
* The embeddings generated for the input texts.
*/
data: { index: number; embedding: number[] }[];
/**
* The detail of the response e.g usage, model used etc.
*/
detail?: string;
}
/**
* A class for generating embeddings using the Jina API.
* @example
* ```typescript
* // Embed a query using the JinaEmbeddings class
* const model = new JinaEmbeddings();
* const res = await model.embedQuery(
* "What would be a good name for a semantic search engine ?",
* );
* console.log({ res });
* ```
*/
export class JinaEmbeddings extends Embeddings implements JinaEmbeddingsParams {
apiKey: string;
model: string;
/**
* Constructor for the JinaEmbeddings class.
* @param fields - An optional object with properties to configure the instance.
*/
constructor(fields?: Partial<JinaEmbeddingsParams> & { verbose?: boolean }) {
const fieldsWithDefaults = {
model: "jina-embeddings-v2-base-en",
...fields,
};
super(fieldsWithDefaults);
const apiKey =
fieldsWithDefaults?.apiKey ||
getEnvironmentVariable("JINA_API_KEY") ||
getEnvironmentVariable("JINA_AUTH_TOKEN");
if (!apiKey) {
throw new Error("Jina API key not found");
}
this.model = fieldsWithDefaults?.model ?? this.model;
this.apiKey = apiKey;
}
/**
* Generates embeddings for an array of inputs.
* @param input - An array of strings or objects to generate embeddings for.
* @returns A Promise that resolves to an array of embeddings.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
private async _embed(input: any): Promise<number[][]> {
const response = await fetch(JINA_API_URL, {
method: "POST",
headers: {
Authorization: `Bearer ${this.apiKey}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ input, model: this.model }),
});
const json = (await response.json()) as JinaEmbeddingsResponse;
if (!json.data) {
throw new Error(json.detail || "Unknown error from Jina API");
}
const sortedEmbeddings = json.data.sort((a, b) => a.index - b.index);
return sortedEmbeddings.map((item) => item.embedding);
}
/**
* Generates embeddings for an array of texts.
* @param texts - An array of strings to generate embeddings for.
* @returns A Promise that resolves to an array of embeddings.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
return this._embed(texts);
}
/**
* Generates an embedding for a single text.
* @param text - A string to generate an embedding for.
* @returns A Promise that resolves to an array of numbers representing the embedding.
*/
async embedQuery(text: string): Promise<number[]> {
const embeddings = await this._embed([text]);
return embeddings[0];
}
/**
* Generates embeddings for an array of image URIs.
* @param uris - An array of image URIs to generate embeddings for.
* @returns A Promise that resolves to an array of embeddings.
*/
async embedImages(uris: string[]): Promise<number[][]> {
const input = uris.map((uri) => (isLocal(uri) ? getBytesStr(uri) : uri));
return this._embed(input);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/gradient_ai.ts
|
import { Gradient } from "@gradientai/nodejs-sdk";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
/**
* Interface for GradientEmbeddings parameters. Extends EmbeddingsParams and
* defines additional parameters specific to the GradientEmbeddings class.
*/
export interface GradientEmbeddingsParams extends EmbeddingsParams {
/**
* Gradient AI Access Token.
* Provide Access Token if you do not wish to automatically pull from env.
*/
gradientAccessKey?: string;
/**
* Gradient Workspace Id.
* Provide workspace id if you do not wish to automatically pull from env.
*/
workspaceId?: string;
}
/**
* Class for generating embeddings using the Gradient AI's API. Extends the
* Embeddings class and implements GradientEmbeddingsParams and
*/
export class GradientEmbeddings
extends Embeddings
implements GradientEmbeddingsParams
{
gradientAccessKey?: string;
workspaceId?: string;
batchSize = 128;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
model: any;
constructor(fields: GradientEmbeddingsParams) {
super(fields);
this.gradientAccessKey =
fields?.gradientAccessKey ??
getEnvironmentVariable("GRADIENT_ACCESS_TOKEN");
this.workspaceId =
fields?.workspaceId ?? getEnvironmentVariable("GRADIENT_WORKSPACE_ID");
if (!this.gradientAccessKey) {
throw new Error("Missing Gradient AI Access Token");
}
if (!this.workspaceId) {
throw new Error("Missing Gradient AI Workspace ID");
}
}
/**
* Method to generate embeddings for an array of documents. Splits the
* documents into batches and makes requests to the Gradient API to generate
* embeddings.
* @param texts Array of documents to generate embeddings for.
* @returns Promise that resolves to a 2D array of embeddings for each document.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
await this.setModel();
const mappedTexts = texts.map((text) => ({ input: text }));
const batches = chunkArray(mappedTexts, this.batchSize);
const batchRequests = batches.map((batch) =>
this.caller.call(async () =>
this.model.generateEmbeddings({
inputs: batch,
})
)
);
const batchResponses = await Promise.all(batchRequests);
const embeddings: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batch = batches[i];
const { embeddings: batchResponse } = batchResponses[i];
for (let j = 0; j < batch.length; j += 1) {
embeddings.push(batchResponse[j].embedding);
}
}
return embeddings;
}
/**
* Method to generate an embedding for a single document. Calls the
* embedDocuments method with the document as the input.
* @param text Document to generate an embedding for.
* @returns Promise that resolves to an embedding for the document.
*/
async embedQuery(text: string): Promise<number[]> {
const data = await this.embedDocuments([text]);
return data[0];
}
/**
* Method to set the model to use for generating embeddings.
* @sets the class' `model` value to that of the retrieved Embeddings Model.
*/
async setModel() {
if (this.model) return;
const gradient = new Gradient({
accessToken: this.gradientAccessKey,
workspaceId: this.workspaceId,
});
this.model = await gradient.getEmbeddingsModel({
slug: "bge-large",
});
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/alibaba_tongyi.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
export interface AlibabaTongyiEmbeddingsParams extends EmbeddingsParams {
/** Model name to use */
modelName: "text-embedding-v2";
/**
* Timeout to use when making requests to AlibabaTongyi.
*/
timeout?: number;
/**
* The maximum number of documents to embed in a single request. This is
* limited by the AlibabaTongyi API to a maximum of 2048.
*/
batchSize?: number;
/**
* Whether to strip new lines from the input text.
*/
stripNewLines?: boolean;
parameters?: {
/**
* 取值:query 或者 document,默认值为 document
* 说明:文本转换为向量后可以应用于检索、聚类、分类等下游任务,
* 对检索这类非对称任务为了达到更好的检索效果建议区分查询文本(query)和
* 底库文本(document)类型, 聚类、分类等对称任务可以不用特殊指定,
* 采用系统默认值"document"即可
*/
text_type?: "query" | "document";
};
}
interface EmbeddingCreateParams {
model: AlibabaTongyiEmbeddingsParams["modelName"];
input: {
texts: string[];
};
parameters?: AlibabaTongyiEmbeddingsParams["parameters"];
}
interface EmbeddingResponse {
output: {
embeddings: { text_index: number; embedding: number[] }[];
};
usage: {
total_tokens: number;
};
request_id: string;
}
interface EmbeddingErrorResponse {
code: string;
message: string;
request_id: string;
}
export class AlibabaTongyiEmbeddings
extends Embeddings
implements AlibabaTongyiEmbeddingsParams
{
modelName: AlibabaTongyiEmbeddingsParams["modelName"] = "text-embedding-v2";
batchSize = 24;
stripNewLines = true;
apiKey: string;
parameters: EmbeddingCreateParams["parameters"];
constructor(
fields?: Partial<AlibabaTongyiEmbeddingsParams> & {
verbose?: boolean;
apiKey?: string;
}
) {
const fieldsWithDefaults = { maxConcurrency: 2, ...fields };
super(fieldsWithDefaults);
const apiKey =
fieldsWithDefaults?.apiKey ?? getEnvironmentVariable("ALIBABA_API_KEY");
if (!apiKey) throw new Error("AlibabaAI API key not found");
this.apiKey = apiKey;
this.modelName = fieldsWithDefaults?.modelName ?? this.modelName;
this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;
this.stripNewLines =
fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;
this.parameters = {
text_type: fieldsWithDefaults?.parameters?.text_type ?? "document",
};
}
/**
* Method to generate embeddings for an array of documents. Splits the
* documents into batches and makes requests to the AlibabaTongyi API to generate
* embeddings.
* @param texts Array of documents to generate embeddings for.
* @returns Promise that resolves to a 2D array of embeddings for each document.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
const batches = chunkArray(
this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts,
this.batchSize
);
const batchRequests = batches.map((batch) => {
const params = this.getParams(batch);
return this.embeddingWithRetry(params);
});
const batchResponses = await Promise.all(batchRequests);
const embeddings: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batch = batches[i];
const batchResponse = batchResponses[i] || [];
for (let j = 0; j < batch.length; j += 1) {
embeddings.push(batchResponse[j]);
}
}
return embeddings;
}
/**
* Method to generate an embedding for a single document. Calls the
* embeddingWithRetry method with the document as the input.
* @param text Document to generate an embedding for.
* @returns Promise that resolves to an embedding for the document.
*/
async embedQuery(text: string): Promise<number[]> {
const params = this.getParams([
this.stripNewLines ? text.replace(/\n/g, " ") : text,
]);
const embeddings = (await this.embeddingWithRetry(params)) || [[]];
return embeddings[0];
}
/**
* Method to generate an embedding params.
* @param texts Array of documents to generate embeddings for.
* @returns an embedding params.
*/
private getParams(
texts: EmbeddingCreateParams["input"]["texts"]
): EmbeddingCreateParams {
return {
model: this.modelName,
input: {
texts,
},
parameters: this.parameters,
};
}
/**
* Private method to make a request to the OpenAI API to generate
* embeddings. Handles the retry logic and returns the response from the
* API.
* @param request Request to send to the OpenAI API.
* @returns Promise that resolves to the response from the API.
*/
private async embeddingWithRetry(body: EmbeddingCreateParams) {
return fetch(
"https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
},
body: JSON.stringify(body),
}
).then(async (response) => {
const embeddingData: EmbeddingResponse | EmbeddingErrorResponse =
await response.json();
if ("code" in embeddingData && embeddingData.code) {
throw new Error(`${embeddingData.code}: ${embeddingData.message}`);
}
return (embeddingData as EmbeddingResponse).output.embeddings.map(
({ embedding }) => embedding
);
});
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/togetherai.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
/**
* Interface for TogetherAIEmbeddingsParams parameters. Extends EmbeddingsParams and
* defines additional parameters specific to the TogetherAIEmbeddings class.
*/
export interface TogetherAIEmbeddingsParams extends EmbeddingsParams {
/**
* The API key to use for the TogetherAI API.
* @default {process.env.TOGETHER_AI_API_KEY}
*/
apiKey?: string;
/**
* Model name to use
* Alias for `model`
* @default {"togethercomputer/m2-bert-80M-8k-retrieval"}
*/
modelName?: string;
/**
* Model name to use
* @default {"togethercomputer/m2-bert-80M-8k-retrieval"}
*/
model?: string;
/**
* Timeout to use when making requests to TogetherAI.
* @default {undefined}
*/
timeout?: number;
/**
* The maximum number of documents to embed in a single request.
* @default {512}
*/
batchSize?: number;
/**
* Whether to strip new lines from the input text. May not be suitable
* for all use cases.
* @default {false}
*/
stripNewLines?: boolean;
}
/** @ignore */
interface TogetherAIEmbeddingsResult {
object: string;
data: Array<{
object: "embedding";
embedding: number[];
index: number;
}>;
model: string;
request_id: string;
}
/**
* Class for generating embeddings using the TogetherAI API. Extends the
* Embeddings class and implements TogetherAIEmbeddingsParams.
* @example
* ```typescript
* const embeddings = new TogetherAIEmbeddings({
* apiKey: process.env.TOGETHER_AI_API_KEY, // Default value
* model: "togethercomputer/m2-bert-80M-8k-retrieval", // Default value
* });
* const res = await embeddings.embedQuery(
* "What would be a good company name a company that makes colorful socks?"
* );
* ```
*/
export class TogetherAIEmbeddings
extends Embeddings
implements TogetherAIEmbeddingsParams
{
modelName = "togethercomputer/m2-bert-80M-8k-retrieval";
model = "togethercomputer/m2-bert-80M-8k-retrieval";
apiKey: string;
batchSize = 512;
stripNewLines = false;
timeout?: number;
private embeddingsAPIUrl = "https://api.together.xyz/api/v1/embeddings";
constructor(fields?: Partial<TogetherAIEmbeddingsParams>) {
super(fields ?? {});
const apiKey =
fields?.apiKey ?? getEnvironmentVariable("TOGETHER_AI_API_KEY");
if (!apiKey) {
throw new Error("TOGETHER_AI_API_KEY not found.");
}
this.apiKey = apiKey;
this.modelName = fields?.model ?? fields?.modelName ?? this.model;
this.model = this.modelName;
this.timeout = fields?.timeout;
this.batchSize = fields?.batchSize ?? this.batchSize;
this.stripNewLines = fields?.stripNewLines ?? this.stripNewLines;
}
private constructHeaders() {
return {
accept: "application/json",
"content-type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
};
}
private constructBody(input: string) {
const body = {
model: this?.model,
input,
};
return body;
}
/**
* Method to generate embeddings for an array of documents. Splits the
* documents into batches and makes requests to the TogetherAI API to generate
* embeddings.
* @param texts Array of documents to generate embeddings for.
* @returns Promise that resolves to a 2D array of embeddings for each document.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
const batches = chunkArray(
this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts,
this.batchSize
);
let batchResponses: TogetherAIEmbeddingsResult[] = [];
for await (const batch of batches) {
const batchRequests = batch.map((item) => this.embeddingWithRetry(item));
const response = await Promise.all(batchRequests);
batchResponses = batchResponses.concat(response);
}
const embeddings: number[][] = batchResponses.map(
(response) => response.data[0].embedding
);
return embeddings;
}
/**
* Method to generate an embedding for a single document. Calls the
* embeddingWithRetry method with the document as the input.
* @param {string} text Document to generate an embedding for.
* @returns {Promise<number[]>} Promise that resolves to an embedding for the document.
*/
async embedQuery(text: string): Promise<number[]> {
const { data } = await this.embeddingWithRetry(
this.stripNewLines ? text.replace(/\n/g, " ") : text
);
return data[0].embedding;
}
/**
* Private method to make a request to the TogetherAI API to generate
* embeddings. Handles the retry logic and returns the response from the
* API.
* @param {string} input The input text to embed.
* @returns Promise that resolves to the response from the API.
* @TODO Figure out return type and statically type it.
*/
private async embeddingWithRetry(
input: string
): Promise<TogetherAIEmbeddingsResult> {
const body = JSON.stringify(this.constructBody(input));
const headers = this.constructHeaders();
return this.caller.call(async () => {
const fetchResponse = await fetch(this.embeddingsAPIUrl, {
method: "POST",
headers,
body,
});
if (fetchResponse.status === 200) {
return fetchResponse.json();
}
throw new Error(
`Error getting prompt completion from Together AI. ${JSON.stringify(
await fetchResponse.json(),
null,
2
)}`
);
});
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/cloudflare_workersai.ts
|
import { Ai } from "@cloudflare/ai";
import { Fetcher } from "@cloudflare/workers-types";
import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
type AiTextEmbeddingsInput = {
text: string | string[];
};
type AiTextEmbeddingsOutput = {
shape: number[];
data: number[][];
};
/** @deprecated Install and import from "@langchain/cloudflare" instead. */
export interface CloudflareWorkersAIEmbeddingsParams extends EmbeddingsParams {
/** Binding */
binding: Fetcher;
/**
* Model name to use
* Alias for `model`
*/
modelName?: string;
/** Model name to use */
model?: string;
/**
* The maximum number of documents to embed in a single request.
*/
batchSize?: number;
/**
* Whether to strip new lines from the input text. This is recommended by
* OpenAI, but may not be suitable for all use cases.
*/
stripNewLines?: boolean;
}
/** @deprecated Install and import from "@langchain/cloudflare" instead. */
export class CloudflareWorkersAIEmbeddings extends Embeddings {
modelName = "@cf/baai/bge-base-en-v1.5";
model = "@cf/baai/bge-base-en-v1.5";
batchSize = 50;
stripNewLines = true;
ai: Ai;
constructor(fields: CloudflareWorkersAIEmbeddingsParams) {
super(fields);
if (!fields.binding) {
throw new Error(
"Must supply a Workers AI binding, eg { binding: env.AI }"
);
}
this.ai = new Ai(fields.binding);
this.modelName = fields?.model ?? fields.modelName ?? this.model;
this.model = this.modelName;
this.stripNewLines = fields.stripNewLines ?? this.stripNewLines;
}
async embedDocuments(texts: string[]): Promise<number[][]> {
const batches = chunkArray(
this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts,
this.batchSize
);
const batchRequests = batches.map((batch) => this.runEmbedding(batch));
const batchResponses = await Promise.all(batchRequests);
const embeddings: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batchResponse = batchResponses[i];
for (let j = 0; j < batchResponse.length; j += 1) {
embeddings.push(batchResponse[j]);
}
}
return embeddings;
}
async embedQuery(text: string): Promise<number[]> {
const data = await this.runEmbedding([
this.stripNewLines ? text.replace(/\n/g, " ") : text,
]);
return data[0];
}
private async runEmbedding(texts: string[]) {
return this.caller.call(async () => {
const response: AiTextEmbeddingsOutput = await this.ai.run(this.model, {
text: texts,
} as AiTextEmbeddingsInput);
return response.data;
});
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/deepinfra.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
/**
* The default model name to use for generating embeddings.
*/
const DEFAULT_MODEL_NAME = "sentence-transformers/clip-ViT-B-32";
/**
* The default batch size to use for generating embeddings.
* This is limited by the DeepInfra API to a maximum of 1024.
*/
const DEFAULT_BATCH_SIZE = 1024;
/**
* Environment variable name for the DeepInfra API token.
*/
const API_TOKEN_ENV_VAR = "DEEPINFRA_API_TOKEN";
export interface DeepInfraEmbeddingsRequest {
inputs: string[];
normalize?: boolean;
image?: string;
webhook?: string;
}
/**
* Input parameters for the DeepInfra embeddings
*/
export interface DeepInfraEmbeddingsParams extends EmbeddingsParams {
/**
* The API token to use for authentication.
* If not provided, it will be read from the `DEEPINFRA_API_TOKEN` environment variable.
*/
apiToken?: string;
/**
* The model ID to use for generating completions.
* Default: `sentence-transformers/clip-ViT-B-32`
*/
modelName?: string;
/**
* The maximum number of texts to embed in a single request. This is
* limited by the DeepInfra API to a maximum of 1024.
*/
batchSize?: number;
}
/**
* Response from the DeepInfra embeddings API.
*/
export interface DeepInfraEmbeddingsResponse {
/**
* The embeddings generated for the input texts.
*/
embeddings: number[][];
/**
* The number of tokens in the input texts.
*/
input_tokens: number;
/**
* The status of the inference.
*/
request_id?: string;
}
/**
* A class for generating embeddings using the DeepInfra API.
* @example
* ```typescript
* // Embed a query using the DeepInfraEmbeddings class
* const model = new DeepInfraEmbeddings();
* const res = await model.embedQuery(
* "What would be a good company name for a company that makes colorful socks?",
* );
* console.log({ res });
* ```
*/
export class DeepInfraEmbeddings
extends Embeddings
implements DeepInfraEmbeddingsParams
{
apiToken: string;
batchSize: number;
modelName: string;
/**
* Constructor for the DeepInfraEmbeddings class.
* @param fields - An optional object with properties to configure the instance.
*/
constructor(
fields?: Partial<DeepInfraEmbeddingsParams> & {
verbose?: boolean;
}
) {
const fieldsWithDefaults = {
modelName: DEFAULT_MODEL_NAME,
batchSize: DEFAULT_BATCH_SIZE,
...fields,
};
super(fieldsWithDefaults);
const apiKey =
fieldsWithDefaults?.apiToken || getEnvironmentVariable(API_TOKEN_ENV_VAR);
if (!apiKey) {
throw new Error("DeepInfra API token not found");
}
this.modelName = fieldsWithDefaults?.modelName ?? this.modelName;
this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;
this.apiToken = apiKey;
}
/**
* Generates embeddings for an array of texts.
* @param inputs - An array of strings to generate embeddings for.
* @returns A Promise that resolves to an array of embeddings.
*/
async embedDocuments(inputs: string[]): Promise<number[][]> {
const batches = chunkArray(inputs, this.batchSize);
const batchRequests = batches.map((batch: string[]) =>
this.embeddingWithRetry({
inputs: batch,
})
);
const batchResponses = await Promise.all(batchRequests);
const out: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batch = batches[i];
const { embeddings } = batchResponses[i];
for (let j = 0; j < batch.length; j += 1) {
out.push(embeddings[j]);
}
}
return out;
}
/**
* Generates an embedding for a single text.
* @param text - A string to generate an embedding for.
* @returns A Promise that resolves to an array of numbers representing the embedding.
*/
async embedQuery(text: string): Promise<number[]> {
const { embeddings } = await this.embeddingWithRetry({
inputs: [text],
});
return embeddings[0];
}
/**
* Generates embeddings with retry capabilities.
* @param request - An object containing the request parameters for generating embeddings.
* @returns A Promise that resolves to the API response.
*/
private async embeddingWithRetry(
request: DeepInfraEmbeddingsRequest
): Promise<DeepInfraEmbeddingsResponse> {
const response = await this.caller.call(() =>
fetch(`https://api.deepinfra.com/v1/inference/${this.modelName}`, {
method: "POST",
headers: {
Authorization: `Bearer ${this.apiToken}`,
"Content-Type": "application/json",
},
body: JSON.stringify(request),
}).then((res) => res.json())
);
return response as DeepInfraEmbeddingsResponse;
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/minimax.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
import { ConfigurationParameters } from "../chat_models/minimax.js";
/**
* Interface for MinimaxEmbeddings parameters. Extends EmbeddingsParams and
* defines additional parameters specific to the MinimaxEmbeddings class.
*/
export interface MinimaxEmbeddingsParams extends EmbeddingsParams {
/**
* Model name to use
* Alias for `model`
*/
modelName: string;
/** Model name to use */
model: string;
/**
* API key to use when making requests. Defaults to the value of
* `MINIMAX_GROUP_ID` environment variable.
*/
minimaxGroupId?: string;
/**
* Secret key to use when making requests. Defaults to the value of
* `MINIMAX_API_KEY` environment variable.
* Alias for `apiKey`
*/
minimaxApiKey?: string;
/**
* Secret key to use when making requests. Defaults to the value of
* `MINIMAX_API_KEY` environment variable.
*/
apiKey?: string;
/**
* The maximum number of documents to embed in a single request. This is
* limited by the Minimax API to a maximum of 4096.
*/
batchSize?: number;
/**
* Whether to strip new lines from the input text. This is recommended by
* Minimax, but may not be suitable for all use cases.
*/
stripNewLines?: boolean;
/**
* The target use-case after generating the vector.
* When using embeddings, the vector of the target content is first generated through the db and stored in the vector database,
* and then the vector of the retrieval text is generated through the query.
* Note: For the parameters of the partial algorithm, we adopted a separate algorithm plan for query and db.
* Therefore, for a paragraph of text, if it is to be used as a retrieval text, it should use the db,
* and if it is used as a retrieval text, it should use the query.
*/
type?: "db" | "query";
}
export interface CreateMinimaxEmbeddingRequest {
/**
* @type {string}
* @memberof CreateMinimaxEmbeddingRequest
*/
model: string;
/**
* Text to generate vector expectation
* @type {CreateEmbeddingRequestInput}
* @memberof CreateMinimaxEmbeddingRequest
*/
texts: string[];
/**
* The target use-case after generating the vector. When using embeddings,
* first generate the vector of the target content through the db and store it in the vector database,
* and then generate the vector of the retrieval text through the query.
* Note: For the parameter of the algorithm, we use the algorithm scheme of query and db separation,
* so a text, if it is to be retrieved as a text, should use the db,
* if it is used as a retrieval text, should use the query.
* @type {string}
* @memberof CreateMinimaxEmbeddingRequest
*/
type: "db" | "query";
}
/**
* Class for generating embeddings using the Minimax API. Extends the
* Embeddings class and implements MinimaxEmbeddingsParams
* @example
* ```typescript
* const embeddings = new MinimaxEmbeddings();
*
* // Embed a single query
* const queryEmbedding = await embeddings.embedQuery("Hello world");
* console.log(queryEmbedding);
*
* // Embed multiple documents
* const documentsEmbedding = await embeddings.embedDocuments([
* "Hello world",
* "Bye bye",
* ]);
* console.log(documentsEmbedding);
* ```
*/
export class MinimaxEmbeddings
extends Embeddings
implements MinimaxEmbeddingsParams
{
modelName = "embo-01";
model = "embo-01";
batchSize = 512;
stripNewLines = true;
minimaxGroupId?: string;
minimaxApiKey?: string;
apiKey?: string;
type: "db" | "query" = "db";
apiUrl: string;
basePath?: string = "https://api.minimax.chat/v1";
headers?: Record<string, string>;
constructor(
fields?: Partial<MinimaxEmbeddingsParams> & {
configuration?: ConfigurationParameters;
}
) {
const fieldsWithDefaults = { maxConcurrency: 2, ...fields };
super(fieldsWithDefaults);
this.minimaxGroupId =
fields?.minimaxGroupId ?? getEnvironmentVariable("MINIMAX_GROUP_ID");
if (!this.minimaxGroupId) {
throw new Error("Minimax GroupID not found");
}
this.minimaxApiKey =
fields?.apiKey ??
fields?.minimaxApiKey ??
getEnvironmentVariable("MINIMAX_API_KEY");
this.apiKey = this.minimaxApiKey;
if (!this.apiKey) {
throw new Error("Minimax ApiKey not found");
}
this.modelName =
fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model;
this.model = this.modelName;
this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;
this.type = fieldsWithDefaults?.type ?? this.type;
this.stripNewLines =
fieldsWithDefaults?.stripNewLines ?? this.stripNewLines;
this.basePath = fields?.configuration?.basePath ?? this.basePath;
this.apiUrl = `${this.basePath}/embeddings`;
this.headers = fields?.configuration?.headers ?? this.headers;
}
/**
* Method to generate embeddings for an array of documents. Splits the
* documents into batches and makes requests to the Minimax API to generate
* embeddings.
* @param texts Array of documents to generate embeddings for.
* @returns Promise that resolves to a 2D array of embeddings for each document.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
const batches = chunkArray(
this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts,
this.batchSize
);
const batchRequests = batches.map((batch) =>
this.embeddingWithRetry({
model: this.model,
texts: batch,
type: this.type,
})
);
const batchResponses = await Promise.all(batchRequests);
const embeddings: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batch = batches[i];
const { vectors: batchResponse } = batchResponses[i];
for (let j = 0; j < batch.length; j += 1) {
embeddings.push(batchResponse[j]);
}
}
return embeddings;
}
/**
* Method to generate an embedding for a single document. Calls the
* embeddingWithRetry method with the document as the input.
* @param text Document to generate an embedding for.
* @returns Promise that resolves to an embedding for the document.
*/
async embedQuery(text: string): Promise<number[]> {
const { vectors } = await this.embeddingWithRetry({
model: this.model,
texts: [this.stripNewLines ? text.replace(/\n/g, " ") : text],
type: this.type,
});
return vectors[0];
}
/**
* Private method to make a request to the Minimax API to generate
* embeddings. Handles the retry logic and returns the response from the
* API.
* @param request Request to send to the Minimax API.
* @returns Promise that resolves to the response from the API.
*/
private async embeddingWithRetry(request: CreateMinimaxEmbeddingRequest) {
const makeCompletionRequest = async () => {
const url = `${this.apiUrl}?GroupId=${this.minimaxGroupId}`;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
...this.headers,
},
body: JSON.stringify(request),
});
const json = await response.json();
return json;
};
return this.caller.call(makeCompletionRequest);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/ollama.ts
|
import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings";
import { OllamaInput, OllamaRequestParams } from "../utils/ollama.js";
type CamelCasedRequestOptions = Omit<
OllamaInput,
"baseUrl" | "model" | "format" | "headers"
>;
/**
* Interface for OllamaEmbeddings parameters. Extends EmbeddingsParams and
* defines additional parameters specific to the OllamaEmbeddings class.
*/
interface OllamaEmbeddingsParams extends EmbeddingsParams {
/** The Ollama model to use, e.g: "llama2:13b" */
model?: string;
/** Base URL of the Ollama server, defaults to "http://localhost:11434" */
baseUrl?: string;
/** Extra headers to include in the Ollama API request */
headers?: Record<string, string>;
/** Defaults to "5m" */
keepAlive?: string;
/** Advanced Ollama API request parameters in camelCase, see
* https://github.com/jmorganca/ollama/blob/main/docs/modelfile.md#valid-parameters-and-values
* for details of the available parameters.
*/
requestOptions?: CamelCasedRequestOptions;
}
/**
* @deprecated OllamaEmbeddings have been moved to the `@langchain/ollama` package. Install it with `npm install @langchain/ollama`.
*/
export class OllamaEmbeddings extends Embeddings {
model = "llama2";
baseUrl = "http://localhost:11434";
headers?: Record<string, string>;
keepAlive = "5m";
requestOptions?: OllamaRequestParams["options"];
constructor(params?: OllamaEmbeddingsParams) {
super({ maxConcurrency: 1, ...params });
if (params?.model) {
this.model = params.model;
}
if (params?.baseUrl) {
this.baseUrl = params.baseUrl;
}
if (params?.headers) {
this.headers = params.headers;
}
if (params?.keepAlive) {
this.keepAlive = params.keepAlive;
}
if (params?.requestOptions) {
this.requestOptions = this._convertOptions(params.requestOptions);
}
}
/** convert camelCased Ollama request options like "useMMap" to
* the snake_cased equivalent which the ollama API actually uses.
* Used only for consistency with the llms/Ollama and chatModels/Ollama classes
*/
_convertOptions(requestOptions: CamelCasedRequestOptions) {
const snakeCasedOptions: Record<string, unknown> = {};
const mapping: Record<keyof CamelCasedRequestOptions, string> = {
embeddingOnly: "embedding_only",
f16KV: "f16_kv",
frequencyPenalty: "frequency_penalty",
keepAlive: "keep_alive",
logitsAll: "logits_all",
lowVram: "low_vram",
mainGpu: "main_gpu",
mirostat: "mirostat",
mirostatEta: "mirostat_eta",
mirostatTau: "mirostat_tau",
numBatch: "num_batch",
numCtx: "num_ctx",
numGpu: "num_gpu",
numGqa: "num_gqa",
numKeep: "num_keep",
numPredict: "num_predict",
numThread: "num_thread",
penalizeNewline: "penalize_newline",
presencePenalty: "presence_penalty",
repeatLastN: "repeat_last_n",
repeatPenalty: "repeat_penalty",
ropeFrequencyBase: "rope_frequency_base",
ropeFrequencyScale: "rope_frequency_scale",
temperature: "temperature",
stop: "stop",
tfsZ: "tfs_z",
topK: "top_k",
topP: "top_p",
typicalP: "typical_p",
useMLock: "use_mlock",
useMMap: "use_mmap",
vocabOnly: "vocab_only",
};
for (const [key, value] of Object.entries(requestOptions)) {
const snakeCasedOption = mapping[key as keyof CamelCasedRequestOptions];
if (snakeCasedOption) {
snakeCasedOptions[snakeCasedOption] = value;
} else {
// Just pass unknown options through
snakeCasedOptions[key] = value;
}
}
return snakeCasedOptions;
}
async _request(prompt: string): Promise<number[]> {
const { model, baseUrl, keepAlive, requestOptions } = this;
let formattedBaseUrl = baseUrl;
if (formattedBaseUrl.startsWith("http://localhost:")) {
// Node 18 has issues with resolving "localhost"
// See https://github.com/node-fetch/node-fetch/issues/1624
formattedBaseUrl = formattedBaseUrl.replace(
"http://localhost:",
"http://127.0.0.1:"
);
}
const response = await fetch(`${formattedBaseUrl}/api/embeddings`, {
method: "POST",
headers: {
"Content-Type": "application/json",
...this.headers,
},
body: JSON.stringify({
prompt,
model,
keep_alive: keepAlive,
options: requestOptions,
}),
});
if (!response.ok) {
throw new Error(
`Request to Ollama server failed: ${response.status} ${response.statusText}`
);
}
const json = await response.json();
return json.embedding;
}
async _embed(texts: string[]): Promise<number[][]> {
const embeddings: number[][] = await Promise.all(
texts.map((text) => this.caller.call(() => this._request(text)))
);
return embeddings;
}
async embedDocuments(documents: string[]) {
return this._embed(documents);
}
async embedQuery(document: string) {
return (await this.embedDocuments([document]))[0];
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/fireworks.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
/**
* Interface that extends EmbeddingsParams and defines additional
* parameters specific to the FireworksEmbeddings class.
*/
export interface FireworksEmbeddingsParams extends EmbeddingsParams {
/**
* @deprecated Use `model` instead.
*/
modelName: string;
model: string;
/**
* The maximum number of documents to embed in a single request. This is
* limited by the Fireworks AI API to a maximum of 8.
*/
batchSize?: number;
}
/**
* Interface for the request body to generate embeddings.
*/
export interface CreateFireworksEmbeddingRequest {
/**
* @type {string}
* @memberof CreateFireworksEmbeddingRequest
*/
model: string;
/**
* Text to generate vector expectation
* @type {CreateEmbeddingRequestInput}
* @memberof CreateFireworksEmbeddingRequest
*/
input: string | string[];
}
/**
* A class for generating embeddings using the Fireworks AI API.
*/
export class FireworksEmbeddings
extends Embeddings
implements FireworksEmbeddingsParams
{
/**
* @deprecated Use `model` instead.
*/
modelName = "nomic-ai/nomic-embed-text-v1.5";
model = "nomic-ai/nomic-embed-text-v1.5";
batchSize = 8;
private apiKey: string;
basePath?: string = "https://api.fireworks.ai/inference/v1";
apiUrl: string;
headers?: Record<string, string>;
/**
* Constructor for the FireworksEmbeddings class.
* @param fields - An optional object with properties to configure the instance.
*/
constructor(
fields?: Partial<FireworksEmbeddingsParams> & {
verbose?: boolean;
apiKey?: string;
}
) {
const fieldsWithDefaults = { ...fields };
super(fieldsWithDefaults);
const apiKey =
fieldsWithDefaults?.apiKey || getEnvironmentVariable("FIREWORKS_API_KEY");
if (!apiKey) {
throw new Error("Fireworks AI API key not found");
}
this.model = fieldsWithDefaults?.model ?? this.model;
this.modelName = this.model;
this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;
this.apiKey = apiKey;
this.apiUrl = `${this.basePath}/embeddings`;
}
/**
* Generates embeddings for an array of texts.
* @param texts - An array of strings to generate embeddings for.
* @returns A Promise that resolves to an array of embeddings.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
const batches = chunkArray(texts, this.batchSize);
const batchRequests = batches.map((batch) =>
this.embeddingWithRetry({
model: this.model,
input: batch,
})
);
const batchResponses = await Promise.all(batchRequests);
const embeddings: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batch = batches[i];
const { data: batchResponse } = batchResponses[i];
for (let j = 0; j < batch.length; j += 1) {
embeddings.push(batchResponse[j].embedding);
}
}
return embeddings;
}
/**
* Generates an embedding for a single text.
* @param text - A string to generate an embedding for.
* @returns A Promise that resolves to an array of numbers representing the embedding.
*/
async embedQuery(text: string): Promise<number[]> {
const { data } = await this.embeddingWithRetry({
model: this.model,
input: text,
});
return data[0].embedding;
}
/**
* Makes a request to the Fireworks AI API to generate embeddings for an array of texts.
* @param request - An object with properties to configure the request.
* @returns A Promise that resolves to the response from the Fireworks AI API.
*/
private async embeddingWithRetry(request: CreateFireworksEmbeddingRequest) {
const makeCompletionRequest = async () => {
const url = `${this.apiUrl}`;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
...this.headers,
},
body: JSON.stringify(request),
});
if (!response.ok) {
const { error: message } = await response.json();
const error = new Error(
`Error ${response.status}: ${message ?? "Unspecified error"}`
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(error as any).response = response;
throw error;
}
const json = await response.json();
return json;
};
return this.caller.call(makeCompletionRequest);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/voyage.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
/**
* Interface that extends EmbeddingsParams and defines additional
* parameters specific to the VoyageEmbeddings class.
*/
export interface VoyageEmbeddingsParams extends EmbeddingsParams {
modelName: string;
/**
* The maximum number of documents to embed in a single request. This is
* limited by the Voyage AI API to a maximum of 8.
*/
batchSize?: number;
/**
* Input type for the embeddings request.
*/
inputType?: string;
}
/**
* Interface for the request body to generate embeddings.
*/
export interface CreateVoyageEmbeddingRequest {
/**
* @type {string}
* @memberof CreateVoyageEmbeddingRequest
*/
model: string;
/**
* Text to generate vector expectation
* @type {CreateEmbeddingRequestInput}
* @memberof CreateVoyageEmbeddingRequest
*/
input: string | string[];
/**
* Input type for the embeddings request.
*/
input_type?: string;
}
/**
* A class for generating embeddings using the Voyage AI API.
*/
export class VoyageEmbeddings
extends Embeddings
implements VoyageEmbeddingsParams
{
modelName = "voyage-01";
batchSize = 8;
private apiKey: string;
basePath?: string = "https://api.voyageai.com/v1";
apiUrl: string;
headers?: Record<string, string>;
inputType?: string;
/**
* Constructor for the VoyageEmbeddings class.
* @param fields - An optional object with properties to configure the instance.
*/
constructor(
fields?: Partial<VoyageEmbeddingsParams> & {
verbose?: boolean;
apiKey?: string;
inputType?: string; // Make inputType optional
}
) {
const fieldsWithDefaults = { ...fields };
super(fieldsWithDefaults);
const apiKey =
fieldsWithDefaults?.apiKey || getEnvironmentVariable("VOYAGEAI_API_KEY");
if (!apiKey) {
throw new Error("Voyage AI API key not found");
}
this.modelName = fieldsWithDefaults?.modelName ?? this.modelName;
this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;
this.apiKey = apiKey;
this.apiUrl = `${this.basePath}/embeddings`;
this.inputType = fieldsWithDefaults?.inputType;
}
/**
* Generates embeddings for an array of texts.
* @param texts - An array of strings to generate embeddings for.
* @returns A Promise that resolves to an array of embeddings.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
const batches = chunkArray(texts, this.batchSize);
const batchRequests = batches.map((batch) =>
this.embeddingWithRetry({
model: this.modelName,
input: batch,
input_type: this.inputType,
})
);
const batchResponses = await Promise.all(batchRequests);
const embeddings: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batch = batches[i];
const { data: batchResponse } = batchResponses[i];
for (let j = 0; j < batch.length; j += 1) {
embeddings.push(batchResponse[j].embedding);
}
}
return embeddings;
}
/**
* Generates an embedding for a single text.
* @param text - A string to generate an embedding for.
* @returns A Promise that resolves to an array of numbers representing the embedding.
*/
async embedQuery(text: string): Promise<number[]> {
const { data } = await this.embeddingWithRetry({
model: this.modelName,
input: text,
input_type: this.inputType,
});
return data[0].embedding;
}
/**
* Makes a request to the Voyage AI API to generate embeddings for an array of texts.
* @param request - An object with properties to configure the request.
* @returns A Promise that resolves to the response from the Voyage AI API.
*/
private async embeddingWithRetry(request: CreateVoyageEmbeddingRequest) {
const makeCompletionRequest = async () => {
const url = `${this.apiUrl}`;
const response = await fetch(url, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${this.apiKey}`,
...this.headers,
},
body: JSON.stringify(request),
});
const json = await response.json();
return json;
};
return this.caller.call(makeCompletionRequest);
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/ibm.ts
|
import { Embeddings } from "@langchain/core/embeddings";
import {
EmbeddingParameters,
TextEmbeddingsParams,
} from "@ibm-cloud/watsonx-ai/dist/watsonx-ai-ml/vml_v1.js";
import { WatsonXAI } from "@ibm-cloud/watsonx-ai";
import { AsyncCaller } from "@langchain/core/utils/async_caller";
import { WatsonxAuth, WatsonxParams } from "../types/ibm.js";
import { authenticateAndSetInstance } from "../utils/ibm.js";
export interface WatsonxEmbeddingsParams
extends Pick<TextEmbeddingsParams, "headers"> {
truncateInputTokens?: number;
}
export interface WatsonxInputEmbeddings
extends Omit<WatsonxParams, "idOrName"> {
truncateInputTokens?: number;
}
export class WatsonxEmbeddings
extends Embeddings
implements WatsonxEmbeddingsParams, WatsonxParams
{
model: string;
serviceUrl: string;
version: string;
spaceId?: string;
projectId?: string;
truncateInputTokens?: number;
maxRetries?: number;
maxConcurrency?: number;
private service: WatsonXAI;
constructor(fields: WatsonxInputEmbeddings & WatsonxAuth) {
const superProps = { maxConcurrency: 2, ...fields };
super(superProps);
this.model = fields.model;
this.version = fields.version;
this.serviceUrl = fields.serviceUrl;
this.truncateInputTokens = fields.truncateInputTokens;
this.maxConcurrency = fields.maxConcurrency;
this.maxRetries = fields.maxRetries ?? 0;
if (fields.projectId && fields.spaceId)
throw new Error("Maximum 1 id type can be specified per instance");
else if (!fields.projectId && !fields.spaceId)
throw new Error(
"No id specified! At least id of 1 type has to be specified"
);
this.projectId = fields?.projectId;
this.spaceId = fields?.spaceId;
this.serviceUrl = fields?.serviceUrl;
const {
watsonxAIApikey,
watsonxAIAuthType,
watsonxAIBearerToken,
watsonxAIUsername,
watsonxAIPassword,
watsonxAIUrl,
version,
serviceUrl,
} = fields;
const auth = authenticateAndSetInstance({
watsonxAIApikey,
watsonxAIAuthType,
watsonxAIBearerToken,
watsonxAIUsername,
watsonxAIPassword,
watsonxAIUrl,
version,
serviceUrl,
});
if (auth) this.service = auth;
else throw new Error("You have not provided one type of authentication");
}
scopeId() {
if (this.projectId)
return { projectId: this.projectId, modelId: this.model };
else return { spaceId: this.spaceId, modelId: this.model };
}
invocationParams(): EmbeddingParameters {
return {
truncate_input_tokens: this.truncateInputTokens,
};
}
async listModels() {
const listModelParams = {
filters: "function_embedding",
};
const caller = new AsyncCaller({
maxConcurrency: this.maxConcurrency,
maxRetries: this.maxRetries,
});
const listModels = await caller.call(() =>
this.service.listFoundationModelSpecs(listModelParams)
);
return listModels.result.resources?.map((item) => item.model_id);
}
private async embedSingleText(inputs: string[]) {
const textEmbeddingParams: TextEmbeddingsParams = {
inputs,
...this.scopeId(),
parameters: this.invocationParams(),
};
const caller = new AsyncCaller({
maxConcurrency: this.maxConcurrency,
maxRetries: this.maxRetries,
});
const embeddings = await caller.call(() =>
this.service.embedText(textEmbeddingParams)
);
return embeddings.result.results.map((item) => item.embedding);
}
async embedDocuments(documents: string[]): Promise<number[][]> {
const data = await this.embedSingleText(documents);
return data;
}
async embedQuery(document: string): Promise<number[]> {
const data = await this.embedSingleText([document]);
return data[0];
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/premai.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
import Prem from "@premai/prem-sdk";
/**
* Interface for PremEmbeddings parameters. Extends EmbeddingsParams and
* defines additional parameters specific to the PremEmbeddings class.
*/
export interface PremEmbeddingsParams extends EmbeddingsParams {
/**
* The Prem API key to use for requests.
* @default process.env.PREM_API_KEY
*/
apiKey?: string;
baseUrl?: string;
/**
* The ID of the project to use.
*/
project_id?: number | string;
/**
* The model to generate the embeddings.
*/
model: string;
encoding_format?: ("float" | "base64") & string;
batchSize?: number;
}
/**
* Class for generating embeddings using the Prem AI's API. Extends the
* Embeddings class and implements PremEmbeddingsParams and
*/
export class PremEmbeddings extends Embeddings implements PremEmbeddingsParams {
client: Prem;
batchSize = 128;
apiKey?: string;
project_id: number;
model: string;
encoding_format?: ("float" | "base64") & string;
constructor(fields: PremEmbeddingsParams) {
super(fields);
const apiKey = fields?.apiKey || getEnvironmentVariable("PREM_API_KEY");
if (!apiKey) {
throw new Error(
`Prem API key not found. Please set the PREM_API_KEY environment variable or provide the key into "apiKey"`
);
}
const projectId =
fields?.project_id ??
parseInt(getEnvironmentVariable("PREM_PROJECT_ID") ?? "-1", 10);
if (!projectId || projectId === -1 || typeof projectId !== "number") {
throw new Error(
`Prem project ID not found. Please set the PREM_PROJECT_ID environment variable or provide the key into "project_id"`
);
}
this.client = new Prem({
apiKey,
});
this.project_id = projectId;
this.model = fields.model ?? this.model;
this.encoding_format = fields.encoding_format ?? this.encoding_format;
}
/**
* Method to generate embeddings for an array of documents. Splits the
* documents into batches and makes requests to the Prem API to generate
* embeddings.
* @param texts Array of documents to generate embeddings for.
* @returns Promise that resolves to a 2D array of embeddings for each document.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
const mappedTexts = texts.map((text) => text);
const batches = chunkArray(mappedTexts, this.batchSize);
const batchRequests = batches.map((batch) =>
this.caller.call(async () =>
this.client.embeddings.create({
input: batch,
model: this.model,
encoding_format: this.encoding_format,
project_id: this.project_id,
})
)
);
const batchResponses = await Promise.all(batchRequests);
const embeddings: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batch = batches[i];
const { data: batchResponse } = batchResponses[i];
for (let j = 0; j < batch.length; j += 1) {
embeddings.push(batchResponse[j].embedding);
}
}
return embeddings;
}
/**
* Method to generate an embedding for a single document. Calls the
* embedDocuments method with the document as the input.
* @param text Document to generate an embedding for.
* @returns Promise that resolves to an embedding for the document.
*/
async embedQuery(text: string): Promise<number[]> {
const data = await this.embedDocuments([text]);
return data[0];
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tensorflow.ts
|
import { load } from "@tensorflow-models/universal-sentence-encoder";
import * as tf from "@tensorflow/tfjs-core";
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
/**
* Interface that extends EmbeddingsParams and defines additional
* parameters specific to the TensorFlowEmbeddings class.
*/
export interface TensorFlowEmbeddingsParams extends EmbeddingsParams {}
/**
* Class that extends the Embeddings class and provides methods for
* generating embeddings using the Universal Sentence Encoder model from
* TensorFlow.js.
* @example
* ```typescript
* const embeddings = new TensorFlowEmbeddings();
* const store = new MemoryVectorStore(embeddings);
*
* const documents = [
* "A document",
* "Some other piece of text",
* "One more",
* "And another",
* ];
*
* await store.addDocuments(
* documents.map((pageContent) => new Document({ pageContent }))
* );
* ```
*/
export class TensorFlowEmbeddings extends Embeddings {
constructor(fields?: TensorFlowEmbeddingsParams) {
super(fields ?? {});
try {
tf.backend();
} catch (e) {
throw new Error("No TensorFlow backend found, see instructions at ...");
}
}
_cached: ReturnType<typeof load>;
/**
* Private method that loads the Universal Sentence Encoder model if it
* hasn't been loaded already. It returns a promise that resolves to the
* loaded model.
* @returns Promise that resolves to the loaded Universal Sentence Encoder model.
*/
private async load() {
if (this._cached === undefined) {
this._cached = load();
}
return this._cached;
}
private _embed(texts: string[]) {
return this.caller.call(async () => {
const model = await this.load();
return model.embed(texts);
});
}
/**
* Method that takes a document as input and returns a promise that
* resolves to an embedding for the document. It calls the _embed method
* with the document as the input and processes the result to return a
* single embedding.
* @param document Document to generate an embedding for.
* @returns Promise that resolves to an embedding for the input document.
*/
embedQuery(document: string): Promise<number[]> {
return this._embed([document])
.then((embeddings) => embeddings.array())
.then((embeddings) => embeddings[0]);
}
/**
* Method that takes an array of documents as input and returns a promise
* that resolves to a 2D array of embeddings for each document. It calls
* the _embed method with the documents as the input and processes the
* result to return the embeddings.
* @param documents Array of documents to generate embeddings for.
* @returns Promise that resolves to a 2D array of embeddings for each input document.
*/
embedDocuments(documents: string[]): Promise<number[][]> {
return this._embed(documents).then((embeddings) => embeddings.array());
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/cohere.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
/**
* Interface that extends EmbeddingsParams and defines additional
* parameters specific to the CohereEmbeddings class.
* @deprecated Use `CohereEmbeddingsParams` from `@langchain/cohere` instead.
*/
export interface CohereEmbeddingsParams extends EmbeddingsParams {
modelName: string;
/**
* The maximum number of documents to embed in a single request. This is
* limited by the Cohere API to a maximum of 96.
*/
batchSize?: number;
}
/**
* A class for generating embeddings using the Cohere API.
* @example
* ```typescript
* // Embed a query using the CohereEmbeddings class
* const model = new ChatOpenAI();
* const res = await model.embedQuery(
* "What would be a good company name for a company that makes colorful socks?",
* );
* console.log({ res });
* ```
* @deprecated Use `CohereEmbeddings` from `@langchain/cohere` instead.
*/
export class CohereEmbeddings
extends Embeddings
implements CohereEmbeddingsParams
{
modelName = "small";
batchSize = 48;
private apiKey: string;
private client: typeof import("cohere-ai");
/**
* Constructor for the CohereEmbeddings class.
* @param fields - An optional object with properties to configure the instance.
*/
constructor(
fields?: Partial<CohereEmbeddingsParams> & {
verbose?: boolean;
apiKey?: string;
}
) {
const fieldsWithDefaults = { maxConcurrency: 2, ...fields };
super(fieldsWithDefaults);
const apiKey =
fieldsWithDefaults?.apiKey || getEnvironmentVariable("COHERE_API_KEY");
if (!apiKey) {
throw new Error("Cohere API key not found");
}
this.modelName = fieldsWithDefaults?.modelName ?? this.modelName;
this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize;
this.apiKey = apiKey;
}
/**
* Generates embeddings for an array of texts.
* @param texts - An array of strings to generate embeddings for.
* @returns A Promise that resolves to an array of embeddings.
*/
async embedDocuments(texts: string[]): Promise<number[][]> {
await this.maybeInitClient();
const batches = chunkArray(texts, this.batchSize);
const batchRequests = batches.map((batch) =>
this.embeddingWithRetry({
model: this.modelName,
texts: batch,
})
);
const batchResponses = await Promise.all(batchRequests);
const embeddings: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batch = batches[i];
const { body: batchResponse } = batchResponses[i];
for (let j = 0; j < batch.length; j += 1) {
embeddings.push(batchResponse.embeddings[j]);
}
}
return embeddings;
}
/**
* Generates an embedding for a single text.
* @param text - A string to generate an embedding for.
* @returns A Promise that resolves to an array of numbers representing the embedding.
*/
async embedQuery(text: string): Promise<number[]> {
await this.maybeInitClient();
const { body } = await this.embeddingWithRetry({
model: this.modelName,
texts: [text],
});
return body.embeddings[0];
}
/**
* Generates embeddings with retry capabilities.
* @param request - An object containing the request parameters for generating embeddings.
* @returns A Promise that resolves to the API response.
*/
private async embeddingWithRetry(
request: Parameters<typeof this.client.embed>[0]
) {
await this.maybeInitClient();
return this.caller.call(this.client.embed.bind(this.client), request);
}
/**
* Initializes the Cohere client if it hasn't been initialized already.
*/
private async maybeInitClient() {
if (!this.client) {
const { cohere } = await CohereEmbeddings.imports();
this.client = cohere;
this.client.init(this.apiKey);
}
}
/** @ignore */
static async imports(): Promise<{
cohere: typeof import("cohere-ai");
}> {
try {
const { default: cohere } = await import("cohere-ai");
return { cohere };
} catch (e) {
throw new Error(
"Please install cohere-ai as a dependency with, e.g. `yarn add cohere-ai`"
);
}
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/hf_transformers.ts
|
import type {
PretrainedOptions,
FeatureExtractionPipelineOptions,
FeatureExtractionPipeline,
} from "@xenova/transformers";
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
import { chunkArray } from "@langchain/core/utils/chunk_array";
export interface HuggingFaceTransformersEmbeddingsParams
extends EmbeddingsParams {
/**
* Model name to use
* Alias for `model`
*/
modelName: string;
/** Model name to use */
model: string;
/**
* Timeout to use when making requests to OpenAI.
*/
timeout?: number;
/**
* The maximum number of documents to embed in a single request.
*/
batchSize?: number;
/**
* Whether to strip new lines from the input text. This is recommended by
* OpenAI, but may not be suitable for all use cases.
*/
stripNewLines?: boolean;
/**
* Optional parameters for the pretrained model.
*/
pretrainedOptions?: PretrainedOptions;
/**
* Optional parameters for the pipeline.
*/
pipelineOptions?: FeatureExtractionPipelineOptions;
}
/**
* @example
* ```typescript
* const model = new HuggingFaceTransformersEmbeddings({
* model: "Xenova/all-MiniLM-L6-v2",
* });
*
* // Embed a single query
* const res = await model.embedQuery(
* "What would be a good company name for a company that makes colorful socks?"
* );
* console.log({ res });
*
* // Embed multiple documents
* const documentRes = await model.embedDocuments(["Hello world", "Bye bye"]);
* console.log({ documentRes });
* ```
*/
export class HuggingFaceTransformersEmbeddings
extends Embeddings
implements HuggingFaceTransformersEmbeddingsParams
{
modelName = "Xenova/all-MiniLM-L6-v2";
model = "Xenova/all-MiniLM-L6-v2";
batchSize = 512;
stripNewLines = true;
timeout?: number;
pretrainedOptions?: PretrainedOptions;
pipelineOptions?: FeatureExtractionPipelineOptions;
private pipelinePromise: Promise<FeatureExtractionPipeline>;
constructor(fields?: Partial<HuggingFaceTransformersEmbeddingsParams>) {
super(fields ?? {});
this.modelName = fields?.model ?? fields?.modelName ?? this.model;
this.model = this.modelName;
this.stripNewLines = fields?.stripNewLines ?? this.stripNewLines;
this.timeout = fields?.timeout;
this.pretrainedOptions = fields?.pretrainedOptions ?? {};
this.pipelineOptions = {
pooling: "mean",
normalize: true,
...fields?.pipelineOptions,
};
}
async embedDocuments(texts: string[]): Promise<number[][]> {
const batches = chunkArray(
this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts,
this.batchSize
);
const batchRequests = batches.map((batch) => this.runEmbedding(batch));
const batchResponses = await Promise.all(batchRequests);
const embeddings: number[][] = [];
for (let i = 0; i < batchResponses.length; i += 1) {
const batchResponse = batchResponses[i];
for (let j = 0; j < batchResponse.length; j += 1) {
embeddings.push(batchResponse[j]);
}
}
return embeddings;
}
async embedQuery(text: string): Promise<number[]> {
const data = await this.runEmbedding([
this.stripNewLines ? text.replace(/\n/g, " ") : text,
]);
return data[0];
}
private async runEmbedding(texts: string[]) {
const pipe = await (this.pipelinePromise ??= (
await import("@xenova/transformers")
).pipeline("feature-extraction", this.model, this.pretrainedOptions));
return this.caller.call(async () => {
const output = await pipe(texts, this.pipelineOptions);
return output.tolist();
});
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/zhipuai.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
import { encodeApiKey } from "../utils/zhipuai.js";
/**
* Interface that extends EmbeddingsParams and defines additional
* parameters specific to the ZhipuAIEmbeddingsParams class.
*/
export interface ZhipuAIEmbeddingsParams extends EmbeddingsParams {
/**
* Model Name to use
*/
modelName?: "embedding-2";
/**
* ZhipuAI API key to use
*/
apiKey?: string;
/**
* Whether to strip new lines from the input text.
*/
stripNewLines?: boolean;
}
interface EmbeddingData {
embedding: number[];
index: number;
object: string;
}
interface TokenUsage {
completion_tokens: number;
prompt_tokens: number;
total_tokens: number;
}
export interface ZhipuAIEmbeddingsResult {
model: string;
data: EmbeddingData[];
object: string;
usage: TokenUsage;
}
export class ZhipuAIEmbeddings
extends Embeddings
implements ZhipuAIEmbeddingsParams
{
modelName: ZhipuAIEmbeddingsParams["modelName"] = "embedding-2";
apiKey?: string;
stripNewLines = true;
private embeddingsAPIURL = "https://open.bigmodel.cn/api/paas/v4/embeddings";
constructor(fields?: ZhipuAIEmbeddingsParams) {
super(fields ?? {});
this.modelName = fields?.modelName ?? this.modelName;
this.stripNewLines = fields?.stripNewLines ?? this.stripNewLines;
this.apiKey = fields?.apiKey ?? getEnvironmentVariable("ZHIPUAI_API_KEY");
if (!this.apiKey) {
throw new Error("ZhipuAI API key not found");
}
}
/**
* Private method to make a request to the TogetherAI API to generate
* embeddings. Handles the retry logic and returns the response from the API.
* @param {string} input The input text to embed.
* @returns Promise that resolves to the response from the API.
* @TODO Figure out return type and statically type it.
*/
private async embeddingWithRetry(
input: string
): Promise<ZhipuAIEmbeddingsResult> {
const text = this.stripNewLines ? input.replace(/\n/g, " ") : input;
const body = JSON.stringify({ input: text, model: this.modelName });
const headers = {
Accept: "application/json",
"Content-Type": "application/json",
Authorization: encodeApiKey(this.apiKey),
};
return this.caller.call(async () => {
const fetchResponse = await fetch(this.embeddingsAPIURL, {
method: "POST",
headers,
body,
});
if (fetchResponse.status === 200) {
return fetchResponse.json();
}
throw new Error(
`Error getting embeddings from ZhipuAI. ${JSON.stringify(
await fetchResponse.json(),
null,
2
)}`
);
});
}
/**
* Method to generate an embedding for a single document. Calls the
* embeddingWithRetry method with the document as the input.
* @param {string} text Document to generate an embedding for.
* @returns {Promise<number[]>} Promise that resolves to an embedding for the document.
*/
async embedQuery(text: string): Promise<number[]> {
const { data } = await this.embeddingWithRetry(text);
return data[0].embedding;
}
/**
* Method that takes an array of documents as input and returns a promise
* that resolves to a 2D array of embeddings for each document. It calls
* the embedQuery method for each document in the array.
* @param documents Array of documents for which to generate embeddings.
* @returns Promise that resolves to a 2D array of embeddings for each input document.
*/
embedDocuments(documents: string[]): Promise<number[][]> {
return Promise.all(documents.map((doc) => this.embedQuery(doc)));
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/bedrock.int.test.ts
|
/* eslint-disable no-process-env */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { expect, test } from "@jest/globals";
import { BedrockRuntimeClient } from "@aws-sdk/client-bedrock-runtime";
import { HNSWLib } from "../../vectorstores/hnswlib.js";
import { BedrockEmbeddings } from "../bedrock.js";
const getClient = () => {
if (
!process.env.BEDROCK_AWS_REGION ||
!process.env.BEDROCK_AWS_ACCESS_KEY_ID ||
!process.env.BEDROCK_AWS_SECRET_ACCESS_KEY
) {
throw new Error("Missing environment variables for AWS");
}
const client = new BedrockRuntimeClient({
region: process.env.BEDROCK_AWS_REGION,
credentials: {
accessKeyId: process.env.BEDROCK_AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.BEDROCK_AWS_SECRET_ACCESS_KEY,
},
});
return client;
};
test("Test BedrockEmbeddings.embedQuery", async () => {
const client = getClient();
const embeddings = new BedrockEmbeddings({
maxRetries: 1,
client,
});
const res = await embeddings.embedQuery("Hello world");
// console.log(res);
expect(typeof res[0]).toBe("number");
});
test("Test BedrockEmbeddings.embedDocuments with passed region and credentials", async () => {
const client = getClient();
const embeddings = new BedrockEmbeddings({
maxRetries: 1,
client,
});
const res = await embeddings.embedDocuments([
"Hello world",
"Bye bye",
"we need",
"at least",
"six documents",
"to test pagination",
]);
// console.log(res);
expect(res).toHaveLength(6);
res.forEach((r) => {
expect(typeof r[0]).toBe("number");
});
});
test("Test end to end with HNSWLib", async () => {
const client = getClient();
const vectorStore = await HNSWLib.fromTexts(
["Hello world", "Bye bye", "hello nice world"],
[{ id: 2 }, { id: 1 }, { id: 3 }],
new BedrockEmbeddings({
maxRetries: 1,
client,
})
);
expect(vectorStore.index?.getCurrentCount()).toBe(3);
const resultOne = await vectorStore.similaritySearch("hello world", 1);
const resultOneMetadatas = resultOne.map(({ metadata }) => metadata);
expect(resultOneMetadatas).toEqual([{ id: 2 }]);
const resultTwo = await vectorStore.similaritySearch("hello world", 2);
const resultTwoMetadatas = resultTwo.map(({ metadata }) => metadata);
expect(resultTwoMetadatas).toEqual([{ id: 2 }, { id: 3 }]);
const resultThree = await vectorStore.similaritySearch("hello world", 3);
const resultThreeMetadatas = resultThree.map(({ metadata }) => metadata);
expect(resultThreeMetadatas).toEqual([{ id: 2 }, { id: 3 }, { id: 1 }]);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/ollama.int.test.ts
|
import { test, expect } from "@jest/globals";
import { OllamaEmbeddings } from "../ollama.js";
test.skip("Test OllamaEmbeddings.embedQuery", async () => {
const embeddings = new OllamaEmbeddings();
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
});
test.skip("Test OllamaEmbeddings.embedDocuments", async () => {
const embeddings = new OllamaEmbeddings();
const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/hf_transformers.int.test.ts
|
import { test, expect } from "@jest/globals";
import { HuggingFaceTransformersEmbeddings } from "../hf_transformers.js";
import { HNSWLib } from "../../vectorstores/hnswlib.js";
test("HuggingFaceTransformersEmbeddings", async () => {
const embeddings = new HuggingFaceTransformersEmbeddings();
const texts = [
"Hello world!",
"Hello bad world!",
"Hello nice world!",
"Hello good world!",
"1 + 1 = 2",
"1 + 1 = 3",
];
const queryEmbedding = await embeddings.embedQuery(texts[0]);
expect(queryEmbedding).toHaveLength(384);
expect(typeof queryEmbedding[0]).toBe("number");
const store = await HNSWLib.fromTexts(texts, {}, embeddings);
expect(await store.similaritySearch(texts[4], 2)).toMatchInlineSnapshot(`
[
Document {
"metadata": {},
"pageContent": "1 + 1 = 2",
},
Document {
"metadata": {},
"pageContent": "1 + 1 = 3",
},
]
`);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/llama_cpp.int.test.ts
|
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { test, expect } from "@jest/globals";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { LlamaCppEmbeddings } from "../llama_cpp.js";
const llamaPath = getEnvironmentVariable("LLAMA_PATH")!;
test.skip("Test LlamaCppEmbeddings.embedQuery", async () => {
const embeddings = await LlamaCppEmbeddings.initialize({
modelPath: llamaPath,
});
const res = await embeddings.embedQuery("Hello Llama");
expect(typeof res[0]).toBe("number");
});
test.skip("Test LlamaCppEmbeddings.embedDocuments", async () => {
const embeddings = await LlamaCppEmbeddings.initialize({
modelPath: llamaPath,
});
const res = await embeddings.embedDocuments(["Hello Llama", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
test.skip("Test LlamaCppEmbeddings concurrency", async () => {
const embeddings = await LlamaCppEmbeddings.initialize({
modelPath: llamaPath,
batchSize: 1,
});
const res = await embeddings.embedDocuments([
"Hello world",
"Bye bye",
"Hello Llama",
"Bye bye",
"Hello Panda",
"Bye bye",
]);
expect(res).toHaveLength(6);
expect(res.find((embedding) => typeof embedding[0] !== "number")).toBe(
undefined
);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/minimax.int.test.ts
|
import { test, expect } from "@jest/globals";
import { MinimaxEmbeddings } from "../minimax.js";
test.skip("Test MinimaxEmbeddings.embedQuery", async () => {
const embeddings = new MinimaxEmbeddings();
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
});
test.skip("Test MinimaxEmbeddings.embedDocuments", async () => {
const embeddings = new MinimaxEmbeddings();
const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
test.skip("Test MinimaxEmbeddings concurrency", async () => {
const embeddings = new MinimaxEmbeddings({
batchSize: 1,
maxConcurrency: 2,
});
const res = await embeddings.embedDocuments([
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
]);
expect(res).toHaveLength(6);
expect(res.find((embedding) => typeof embedding[0] !== "number")).toBe(
undefined
);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/hf.int.test.ts
|
import { test, expect } from "@jest/globals";
import { HuggingFaceInferenceEmbeddings } from "../hf.js";
import { HNSWLib } from "../../vectorstores/hnswlib.js";
test("HuggingFaceInferenceEmbeddings", async () => {
const embeddings = new HuggingFaceInferenceEmbeddings();
const texts = [
"Hello world!",
"Hello bad world!",
"Hello nice world!",
"Hello good world!",
"1 + 1 = 2",
"1 + 1 = 3",
];
const queryEmbedding = await embeddings.embedQuery(texts[0]);
expect(queryEmbedding).toHaveLength(768);
expect(typeof queryEmbedding[0]).toBe("number");
const store = await HNSWLib.fromTexts(texts, {}, embeddings);
expect(await store.similaritySearch(texts[4], 2)).toMatchInlineSnapshot(`
[
Document {
"metadata": {},
"pageContent": "1 + 1 = 2",
},
Document {
"metadata": {},
"pageContent": "1 + 1 = 3",
},
]
`);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/ibm.test.ts
|
/* eslint-disable no-process-env */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { testProperties } from "../../llms/tests/ibm.test.js";
import { WatsonxEmbeddings, WatsonxInputEmbeddings } from "../ibm.js";
const fakeAuthProp = {
watsonxAIAuthType: "iam",
watsonxAIApikey: "fake_key",
};
describe("Embeddings unit tests", () => {
describe("Positive tests", () => {
test("Basic properties", () => {
const testProps = {
model: "ibm/slate-125m-english-rtrvr",
version: "2024-05-31",
serviceUrl: process.env.WATSONX_AI_SERVICE_URL as string,
projectId: process.env.WATSONX_AI_PROJECT_ID || "testString",
};
const instance = new WatsonxEmbeddings({ ...testProps, ...fakeAuthProp });
testProperties(instance, testProps);
});
test("Basic properties", () => {
const testProps: WatsonxInputEmbeddings = {
model: "ibm/slate-125m-english-rtrvr",
version: "2024-05-31",
serviceUrl: process.env.WATSONX_AI_SERVICE_URL as string,
projectId: process.env.WATSONX_AI_PROJECT_ID || "testString",
truncateInputTokens: 10,
maxConcurrency: 2,
maxRetries: 2,
};
const instance = new WatsonxEmbeddings({ ...testProps, ...fakeAuthProp });
testProperties(instance, testProps);
});
});
describe("Negative tests", () => {
test("Missing id", async () => {
const testProps = {
model: "ibm/slate-125m-english-rtrvr",
version: "2024-05-31",
serviceUrl: process.env.WATSONX_AI_SERVICE_URL as string,
};
expect(
() =>
new WatsonxEmbeddings({
...testProps,
...fakeAuthProp,
})
).toThrowError();
});
test("Missing other props", async () => {
// @ts-expect-error Intentionally passing wrong value
const testPropsProjectId: WatsonxInputLLM = {
projectId: process.env.WATSONX_AI_PROJECT_ID || "testString",
};
expect(
() =>
new WatsonxEmbeddings({
...testPropsProjectId,
})
).toThrowError();
// @ts-expect-error //Intentionally passing wrong value
const testPropsServiceUrl: WatsonxInputLLM = {
serviceUrl: process.env.WATSONX_AI_SERVICE_URL as string,
};
expect(
() =>
new WatsonxEmbeddings({
...testPropsServiceUrl,
})
).toThrowError();
const testPropsVersion = {
version: "2024-05-31",
};
expect(
() =>
new WatsonxEmbeddings({
// @ts-expect-error Intentionally passing wrong props
testPropsVersion,
})
).toThrowError();
});
test("Passing more than one id", async () => {
const testProps = {
model: "ibm/slate-125m-english-rtrvr",
version: "2024-05-31",
serviceUrl: process.env.WATSONX_AI_SERVICE_URL as string,
projectId: process.env.WATSONX_AI_PROJECT_ID || "testString",
spaceId: process.env.WATSONX_AI_PROJECT_ID || "testString",
};
expect(
() =>
new WatsonxEmbeddings({
...testProps,
...fakeAuthProp,
})
).toThrowError();
});
test("Invalid properties", () => {
const testProps = {
model: "ibm/slate-125m-english-rtrvr",
version: "2024-05-31",
serviceUrl: process.env.WATSONX_AI_SERVICE_URL as string,
projectId: process.env.WATSONX_AI_PROJECT_ID || "testString",
};
const notExTestProps = {
notExisting: 12,
notExObj: {
notExProp: 12,
},
};
const instance = new WatsonxEmbeddings({
...testProps,
...notExTestProps,
...fakeAuthProp,
});
testProperties(instance, testProps, notExTestProps);
});
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/cohere.int.test.ts
|
import { test, expect } from "@jest/globals";
import { CohereEmbeddings } from "../cohere.js";
test("Test CohereEmbeddings.embedQuery", async () => {
const embeddings = new CohereEmbeddings();
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
});
test("Test CohereEmbeddings.embedDocuments", async () => {
const embeddings = new CohereEmbeddings();
const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
test("Test CohereEmbeddings concurrency", async () => {
const embeddings = new CohereEmbeddings({
batchSize: 1,
maxConcurrency: 2,
});
const res = await embeddings.embedDocuments([
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
]);
expect(res).toHaveLength(6);
expect(res.find((embedding) => typeof embedding[0] !== "number")).toBe(
undefined
);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/jina.int.test.ts
|
import { test, expect } from "@jest/globals";
import { JinaEmbeddings } from "../jina.js";
test("Test JinaEmbeddings.embedQuery", async () => {
const embeddings = new JinaEmbeddings();
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
});
test("Test JinaEmbeddings.embedDocuments", async () => {
const embeddings = new JinaEmbeddings();
const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
test("Test JinaEmbeddings concurrency", async () => {
const embeddings = new JinaEmbeddings();
const res = await embeddings.embedDocuments([
"Hello world",
"Bye bye",
"we need",
"at least",
"six documents",
"to test concurrency",
]);
expect(res).toHaveLength(6);
expect(res.find((embedding) => typeof embedding[0] !== "number")).toBe(
undefined
);
});
test("Test JinaEmbeddings.embedImages", async () => {
const embeddings = new JinaEmbeddings();
const res = await embeddings.embedImages([
"https://avatars.githubusercontent.com/u/126733545?v=4",
]);
expect(typeof res[0][0]).toBe("number");
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/deepinfra.int.test.ts
|
import { test, expect } from "@jest/globals";
import { DeepInfraEmbeddings } from "../deepinfra.js";
test("Test DeepInfraEmbeddings.embedQuery", async () => {
const embeddings = new DeepInfraEmbeddings();
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
});
test("Test DeepInfraEmbeddings.embedDocuments", async () => {
const embeddings = new DeepInfraEmbeddings();
const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
test("Test DeepInfraEmbeddings concurrency", async () => {
const embeddings = new DeepInfraEmbeddings({
batchSize: 1,
});
const res = await embeddings.embedDocuments([
"Hello world",
"Bye bye",
"we need",
"at least",
"six documents",
"to test concurrency",
]);
expect(res).toHaveLength(6);
expect(res.find((embedding) => typeof embedding[0] !== "number")).toBe(
undefined
);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/premai.int.test.ts
|
import { describe, test, expect } from "@jest/globals";
import { PremEmbeddings } from "../premai.js";
describe("EmbeddingsPrem", () => {
test.skip("Test embedQuery", async () => {
const client = new PremEmbeddings({ model: "@cf/baai/bge-small-en-v1.5" });
const res = await client.embedQuery("Hello world");
// console.log(res);
expect(typeof res[0]).toBe("number");
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/fireworks.int.test.ts
|
import { test, expect } from "@jest/globals";
import { FireworksEmbeddings } from "../fireworks.js";
test.skip("Test FireworksEmbeddings.embedQuery", async () => {
const embeddings = new FireworksEmbeddings();
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
});
test.skip("Test FireworksEmbeddings.embedDocuments", async () => {
const embeddings = new FireworksEmbeddings();
const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
test.skip("Test FireworksEmbeddings concurrency", async () => {
const embeddings = new FireworksEmbeddings({
batchSize: 1,
});
const res = await embeddings.embedDocuments([
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
]);
expect(res).toHaveLength(6);
expect(res.find((embedding) => typeof embedding[0] !== "number")).toBe(
undefined
);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/togetherai.int.test.ts
|
import { test, expect } from "@jest/globals";
import { TogetherAIEmbeddings } from "../togetherai.js";
test.skip("Test TogetherAIEmbeddings.embedQuery", async () => {
const embeddings = new TogetherAIEmbeddings();
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
expect(res.length).toBe(768);
});
test.skip("Test TogetherAIEmbeddings.embedDocuments", async () => {
const embeddings = new TogetherAIEmbeddings();
const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
expect(res[0].length).toBe(768);
expect(res[1].length).toBe(768);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/tensorflow.int.test.ts
|
import { test, expect } from "@jest/globals";
import "@tensorflow/tfjs-backend-cpu";
import { TensorFlowEmbeddings } from "../tensorflow.js";
import { HNSWLib } from "../../vectorstores/hnswlib.js";
test("TensorflowEmbeddings", async () => {
const embeddings = new TensorFlowEmbeddings();
const texts = [
"Hello world!",
"Hello bad world!",
"Hello nice world!",
"Hello good world!",
"1 + 1 = 2",
"1 + 1 = 3",
];
const queryEmbedding = await embeddings.embedQuery(texts[0]);
expect(queryEmbedding).toHaveLength(512);
expect(typeof queryEmbedding[0]).toBe("number");
const store = await HNSWLib.fromTexts(texts, {}, embeddings);
expect(await store.similaritySearch(texts[4], 2)).toMatchInlineSnapshot(`
[
Document {
"metadata": {},
"pageContent": "1 + 1 = 2",
},
Document {
"metadata": {},
"pageContent": "1 + 1 = 3",
},
]
`);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/voyage.int.test.ts
|
import { test, expect } from "@jest/globals";
import { VoyageEmbeddings } from "../voyage.js";
test.skip("Test VoyageEmbeddings.embedQuery with input_type", async () => {
const embeddings = new VoyageEmbeddings({ inputType: "document" });
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
});
test.skip("Test VoyageEmbeddings.embedDocuments with input_type", async () => {
const embeddings = new VoyageEmbeddings({ inputType: "document" });
const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
test.skip("Test VoyageEmbeddings concurrency with input_type", async () => {
const embeddings = new VoyageEmbeddings({
batchSize: 1,
maxConcurrency: 2,
inputType: "document",
});
const res = await embeddings.embedDocuments([
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
]);
expect(res).toHaveLength(6);
expect(res.find((embedding) => typeof embedding[0] !== "number")).toBe(
undefined
);
});
test.skip("Test VoyageEmbeddings without input_type", async () => {
const embeddings = new VoyageEmbeddings();
const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/baidu_qianfan.int.test.ts
|
import { test, expect } from "@jest/globals";
import { BaiduQianfanEmbeddings } from "../baidu_qianfan.js";
test.skip("Test BaiduQianfanEmbeddings.embedQuery", async () => {
const embeddings = new BaiduQianfanEmbeddings();
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
});
test.skip("Test BaiduQianfanEmbeddings.embedDocuments", async () => {
const embeddings = new BaiduQianfanEmbeddings();
const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
test.skip("Test BaiduQianfanEmbeddings concurrency", async () => {
const embeddings = new BaiduQianfanEmbeddings({
batchSize: 1,
});
const res = await embeddings.embedDocuments([
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
]);
expect(res).toHaveLength(6);
expect(res.find((embedding) => typeof embedding[0] !== "number")).toBe(
undefined
);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/tencent_hunyuan.test.ts
|
import { test, expect } from "@jest/globals";
import { TencentHunyuanEmbeddings } from "../tencent_hunyuan/index.js";
test.skip("Test TencentHunyuanEmbeddings.embedQuery", async () => {
const embeddings = new TencentHunyuanEmbeddings();
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
});
test.skip("Test TencentHunyuanEmbeddings.embedDocuments", async () => {
const embeddings = new TencentHunyuanEmbeddings();
const res = await embeddings.embedDocuments(["Hello world", "Bye bye"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
test.skip("Test TencentHunyuanEmbeddings concurrency", async () => {
const embeddings = new TencentHunyuanEmbeddings();
const res = await embeddings.embedDocuments([
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
"Hello world",
"Bye bye",
]);
expect(res).toHaveLength(6);
expect(res.find((embedding) => typeof embedding[0] !== "number")).toBe(
undefined
);
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tests/ibm.int.test.ts
|
/* eslint-disable no-process-env */
import { test } from "@jest/globals";
import { WatsonxEmbeddings } from "../ibm.js";
describe("Test embeddings", () => {
test("embedQuery method", async () => {
const embeddings = new WatsonxEmbeddings({
model: "ibm/slate-125m-english-rtrvr",
version: "2024-05-31",
serviceUrl: process.env.WATSONX_AI_SERVICE_URL as string,
projectId: process.env.WATSONX_AI_PROJECT_ID,
});
const res = await embeddings.embedQuery("Hello world");
expect(typeof res[0]).toBe("number");
});
test("embedDocuments", async () => {
const embeddings = new WatsonxEmbeddings({
model: "ibm/slate-125m-english-rtrvr",
version: "2024-05-31",
serviceUrl: process.env.WATSONX_AI_SERVICE_URL as string,
projectId: process.env.WATSONX_AI_PROJECT_ID,
});
const res = await embeddings.embedDocuments(["Hello world", "Bye world"]);
expect(res).toHaveLength(2);
expect(typeof res[0][0]).toBe("number");
expect(typeof res[1][0]).toBe("number");
});
test("Concurrency", async () => {
const embeddings = new WatsonxEmbeddings({
model: "ibm/slate-125m-english-rtrvr",
version: "2024-05-31",
serviceUrl: process.env.WATSONX_AI_SERVICE_URL as string,
projectId: process.env.WATSONX_AI_PROJECT_ID,
maxConcurrency: 4,
});
const res = await embeddings.embedDocuments([
"Hello world",
"Bye world",
"Hello world",
"Bye world",
"Hello world",
"Bye world",
"Hello world",
"Bye world",
]);
expect(res).toHaveLength(8);
expect(res.find((embedding) => typeof embedding[0] !== "number")).toBe(
undefined
);
});
test("List models", async () => {
const embeddings = new WatsonxEmbeddings({
model: "ibm/slate-125m-english-rtrvr",
version: "2024-05-31",
serviceUrl: process.env.WATSONX_AI_SERVICE_URL as string,
projectId: process.env.WATSONX_AI_PROJECT_ID,
maxConcurrency: 4,
});
const res = await embeddings.listModels();
expect(res?.length).toBeGreaterThan(0);
if (res) expect(typeof res[0]).toBe("string");
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tencent_hunyuan/web.ts
|
import { sign } from "../../utils/tencent_hunyuan/web.js";
import {
TencentHunyuanEmbeddings as BaseTencentHunyuanEmbeddings,
TencentHunyuanEmbeddingsParams,
} from "./base.js";
/**
* Class for generating embeddings using the Tencent Hunyuan API.
*/
export class TencentHunyuanEmbeddings extends BaseTencentHunyuanEmbeddings {
constructor(fields?: TencentHunyuanEmbeddingsParams) {
super({ ...fields, sign } ?? { sign });
}
}
export { type TencentHunyuanEmbeddingsParams } from "./base.js";
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tencent_hunyuan/index.ts
|
import { sign } from "../../utils/tencent_hunyuan/index.js";
import {
TencentHunyuanEmbeddings as BaseTencentHunyuanEmbeddings,
TencentHunyuanEmbeddingsParams,
} from "./base.js";
/**
* Class for generating embeddings using the Tencent Hunyuan API.
*/
export class TencentHunyuanEmbeddings extends BaseTencentHunyuanEmbeddings {
constructor(fields?: TencentHunyuanEmbeddingsParams) {
super({ ...fields, sign } ?? { sign });
}
}
export { type TencentHunyuanEmbeddingsParams } from "./base.js";
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings
|
lc_public_repos/langchainjs/libs/langchain-community/src/embeddings/tencent_hunyuan/base.ts
|
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { Embeddings, type EmbeddingsParams } from "@langchain/core/embeddings";
import { sign } from "../../utils/tencent_hunyuan/common.js";
/**
* Interface that extends EmbeddingsParams and defines additional
* parameters specific to the TencentHunyuanEmbeddingsParams class.
*/
export interface TencentHunyuanEmbeddingsParams extends EmbeddingsParams {
/**
* Tencent Cloud API Host.
* @default "hunyuan.tencentcloudapi.com"
*/
host?: string;
/**
* SecretID to use when making requests, can be obtained from https://console.cloud.tencent.com/cam/capi.
* Defaults to the value of `TENCENT_SECRET_ID` environment variable.
*/
tencentSecretId?: string;
/**
* Secret key to use when making requests, can be obtained from https://console.cloud.tencent.com/cam/capi.
* Defaults to the value of `TENCENT_SECRET_KEY` environment variable.
*/
tencentSecretKey?: string;
}
/**
* Interface that extends EmbeddingsParams and defines additional
* parameters specific to the TencentHunyuanEmbeddingsParams class.
*/
interface TencentHunyuanEmbeddingsParamsWithSign
extends TencentHunyuanEmbeddingsParams {
/**
* Tencent Cloud API v3 sign method.
*/
sign: sign;
}
/**
* Interface representing the embedding data.
* See https://cloud.tencent.com/document/api/1729/101838#EmbeddingData.
*/
interface EmbeddingData {
Embedding: number[];
Index: number;
Object: string;
}
/**
* Interface representing the usage of tokens in text embedding.
* See https://cloud.tencent.com/document/api/1729/101838#EmbeddingUsage.
*/
interface EmbeddingUsage {
TotalTokens: number;
PromptTokens: number;
CompletionTokens?: number;
}
/**
* Interface representing a error response from Tencent Hunyuan embedding.
* See https://cloud.tencent.com/document/product/1729/102832
*/
interface Error {
Code: string;
Message: string;
}
/**
* Interface representing a response from Tencent Hunyuan embedding.
* See https://cloud.tencent.com/document/product/1729/102832
*/
interface GetEmbeddingResponse {
Response: {
Error?: Error;
Data: EmbeddingData[];
Usage: EmbeddingUsage;
RequestId: string;
};
}
/**
* Class for generating embeddings using the Tencent Hunyuan API.
*/
export class TencentHunyuanEmbeddings
extends Embeddings
implements TencentHunyuanEmbeddingsParams
{
tencentSecretId?: string;
tencentSecretKey?: string;
host = "hunyuan.tencentcloudapi.com";
sign: sign;
constructor(fields?: TencentHunyuanEmbeddingsParamsWithSign) {
super(fields ?? {});
this.tencentSecretId =
fields?.tencentSecretId ?? getEnvironmentVariable("TENCENT_SECRET_ID");
if (!this.tencentSecretId) {
throw new Error("Tencent SecretID not found");
}
this.tencentSecretKey =
fields?.tencentSecretKey ?? getEnvironmentVariable("TENCENT_SECRET_KEY");
if (!this.tencentSecretKey) {
throw new Error("Tencent SecretKey not found");
}
this.host = fields?.host ?? this.host;
if (!fields?.sign) {
throw new Error("Sign method undefined");
}
this.sign = fields?.sign;
}
/**
* Private method to make a request to the TogetherAI API to generate
* embeddings. Handles the retry logic and returns the response from the API.
* @param {string} input The input text to embed.
* @returns Promise that resolves to the response from the API.
* @TODO Figure out return type and statically type it.
*/
private async embeddingWithRetry(
input: string
): Promise<GetEmbeddingResponse> {
const request = { Input: input };
const timestamp = Math.trunc(Date.now() / 1000);
const headers = {
"Content-Type": "application/json",
"X-TC-Action": "GetEmbedding",
"X-TC-Version": "2023-09-01",
"X-TC-Timestamp": timestamp.toString(),
Authorization: "",
};
headers.Authorization = this.sign(
this.host,
request,
timestamp,
this.tencentSecretId ?? "",
this.tencentSecretKey ?? "",
headers
);
return this.caller.call(async () => {
const response = await fetch(`https://${this.host}`, {
headers,
method: "POST",
body: JSON.stringify(request),
});
if (response.ok) {
return response.json();
}
throw new Error(
`Error getting embeddings from Tencent Hunyuan. ${JSON.stringify(
await response.json(),
null,
2
)}`
);
});
}
/**
* Method to generate an embedding for a single document. Calls the
* embeddingWithRetry method with the document as the input.
* @param {string} text Document to generate an embedding for.
* @returns {Promise<number[]>} Promise that resolves to an embedding for the document.
*/
async embedQuery(text: string): Promise<number[]> {
const { Response } = await this.embeddingWithRetry(text);
if (Response?.Error?.Message) {
throw new Error(`[${Response.RequestId}] ${Response.Error.Message}`);
}
return Response.Data[0].Embedding;
}
/**
* Method that takes an array of documents as input and returns a promise
* that resolves to a 2D array of embeddings for each document. It calls
* the embedQuery method for each document in the array.
* @param documents Array of documents for which to generate embeddings.
* @returns Promise that resolves to a 2D array of embeddings for each input document.
*/
embedDocuments(documents: string[]): Promise<number[][]> {
return Promise.all(documents.map((doc) => this.embedQuery(doc)));
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite/googlemakersuitehub.ts
|
import type { protos } from "@google-ai/generativelanguage";
import type { google } from "@google-ai/generativelanguage/build/protos/protos.js";
import { GoogleAuth, GoogleAuthOptions } from "google-auth-library";
import type { BaseLanguageModel } from "@langchain/core/language_models/base";
import { Runnable } from "@langchain/core/runnables";
import { PromptTemplate } from "@langchain/core/prompts";
import {
AsyncCaller,
AsyncCallerCallOptions,
} from "@langchain/core/utils/async_caller";
import { ChatGooglePaLM } from "./chat_models.js";
import { GooglePaLM } from "./llms.js";
import {
GoogleAbstractedClientOpsMethod,
GoogleResponse,
GoogleVertexAIConnectionParams,
} from "../../../types/googlevertexai-types.js";
import { GoogleConnection } from "../../../utils/googlevertexai-connection.js";
/**
* Configuration that allows us to load or pull a prompt that has been created
* by the Google MakerSuite site and saved in Google Drive.
*
* There is a simple in-memory cache of these prompts that is refreshed
* after the cacheTimeout specified in the configuration.
*/
export interface MakerSuiteHubConfig {
/**
* How long, in milliseconds, before a prompt is assumed stale and should
* be refreshed from the copy in Google Drive.
*/
cacheTimeout: number;
caller?: AsyncCaller;
}
type MakerSuitePromptType = "text" | "data" | "chat";
export interface MakerSuitePromptVariable {
variableId: string;
displayName: string;
}
export interface MakerSuiteRunSettings {
temperature?: number;
model: string;
candidateCount?: number;
topP?: number;
topK?: number;
maxOutputTokens: number;
safetySettings?: protos.google.ai.generativelanguage.v1beta2.ISafetySetting[];
}
export interface MakerSuiteTextPromptData {
textPrompt: {
value?: string;
variables?: MakerSuitePromptVariable[];
};
runSettings?: MakerSuiteRunSettings;
testExamples?: unknown;
}
export interface MakerSuiteDataPromptColumn {
columnId: string;
displayName: string;
isInput?: boolean;
}
export interface MakerSuiteDataPromptRow {
rowId: string;
columnBindings: Record<string, string>;
}
export interface MakerSuiteDataPromptData {
dataPrompt: {
preamble: string;
columns: MakerSuiteDataPromptColumn[];
rows: MakerSuiteDataPromptRow[];
rowsUsed: string[];
};
runSettings?: MakerSuiteRunSettings;
testExamples?: unknown;
}
export interface MakerSuiteChatExchange {
request?: string;
response?: string;
source: string;
id: string;
}
export interface MakerSuiteChatPromptData {
multiturnPrompt: {
preamble: string;
primingExchanges: MakerSuiteChatExchange[];
sessions: {
sessionExchanges: MakerSuiteChatExchange[];
}[];
};
runSettings?: MakerSuiteRunSettings;
}
/**
* These are the possible formats that the JSON generated by MakerSuite
* and saved in Google Drive can be.
*/
export type MakerSuitePromptData =
| MakerSuiteTextPromptData
| MakerSuiteDataPromptData
| MakerSuiteChatPromptData;
/**
* A class that represents the Prompt that has been created by MakerSuite
* and loaded from Google Drive. It exposes methods to turn this prompt
* into a Template, a Model, and into a chain consisting of these two elements.
* In general, this class should be created by the MakerSuiteHub class and
* not instantiated manually.
*/
export class MakerSuitePrompt {
promptType: MakerSuitePromptType;
promptData: MakerSuitePromptData;
constructor(promptData: MakerSuitePromptData) {
this.promptData = promptData;
this._determinePromptType();
}
_determinePromptType() {
if (Object.hasOwn(this.promptData, "textPrompt")) {
this.promptType = "text";
} else if (Object.hasOwn(this.promptData, "dataPrompt")) {
this.promptType = "data";
} else if (Object.hasOwn(this.promptData, "multiturnPrompt")) {
this.promptType = "chat";
} else {
const error = new Error("Unable to identify prompt type.");
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(error as any).promptData = this.promptData;
throw error;
}
}
_promptValueText(): string {
return (
(this.promptData as MakerSuiteTextPromptData)?.textPrompt?.value ?? ""
);
}
_promptValueData(): string {
const promptData: MakerSuiteDataPromptData = this
.promptData as MakerSuiteDataPromptData;
const dataPrompt = promptData?.dataPrompt;
let prompt = `${dataPrompt?.preamble}\n` || "";
dataPrompt?.rows.forEach((row) => {
// Add the data for each row, as long as it is listed as used
if (dataPrompt?.rowsUsed.includes(row.rowId)) {
// Add each input column
dataPrompt?.columns.forEach((column) => {
if (column.isInput) {
prompt += `${column.displayName} ${
row.columnBindings[column.columnId]
}\n`;
}
});
// Add each output column
dataPrompt?.columns.forEach((column) => {
if (!column.isInput) {
prompt += `${column.displayName} ${
row.columnBindings[column.columnId]
}\n`;
}
});
}
});
// Add the input column prompts
dataPrompt?.columns.forEach((column) => {
if (column.isInput) {
prompt += `${column.displayName} {${column.displayName.replace(
":",
""
)}}\n`;
}
});
// Add just the first output column
const firstOutput = dataPrompt?.columns.find((column) => !column.isInput);
prompt += `${firstOutput?.displayName} `;
return prompt;
}
_promptValueChat(): string {
return (
(this.promptData as MakerSuiteChatPromptData)?.multiturnPrompt
?.preamble ?? ""
);
}
_promptValue(): string {
switch (this.promptType) {
case "text":
return this._promptValueText();
case "data":
return this._promptValueData();
case "chat":
return this._promptValueChat();
default:
throw new Error(`Invalid promptType: ${this.promptType}`);
}
}
/**
* Create a template from the prompt, including any "test input" specified
* in MakerSuite as a template parameter.
*/
toTemplate(): PromptTemplate {
const value = this._promptValue();
const promptString = value.replaceAll(/{{.*:(.+):.*}}/g, "{$1}");
return PromptTemplate.fromTemplate(promptString);
}
_modelName(): string {
let ret = this.promptData?.runSettings?.model;
if (!ret) {
ret =
this.promptType === "chat"
? "models/chat-bison-001"
: "models/text-bison-001";
}
return ret;
}
_examples(): google.ai.generativelanguage.v1beta2.IExample[] {
const promptData: MakerSuiteChatPromptData = this
.promptData as MakerSuiteChatPromptData;
const ret: google.ai.generativelanguage.v1beta2.IExample[] =
promptData?.multiturnPrompt?.primingExchanges
.map((exchange) => {
const example: google.ai.generativelanguage.v1beta2.IExample = {};
if (exchange?.request) {
example.input = {
content: exchange.request,
};
}
if (exchange?.response) {
example.output = {
content: exchange.response,
};
}
return example;
})
.filter((value) => Object.keys(value).length);
return ret;
}
/**
* Create a model from the prompt with all the parameters (model name,
* temperature, etc) set as they were in MakerSuite.
*/
toModel(): BaseLanguageModel {
const modelName = this._modelName();
const modelSettings = {
modelName,
...this.promptData?.runSettings,
};
if (this.promptType === "chat") {
const examples = this._examples();
return new ChatGooglePaLM({
examples,
...modelSettings,
});
} else {
return new GooglePaLM(modelSettings);
}
}
/**
* Create a RunnableSequence based on the template and model that can
* be created from this prompt. The template will have parameters available
* based on the "test input" that was set in MakerSuite, and the model
* will have the parameters (model name, temperature, etc) from those in
* MakerSuite.
*/
toChain() {
return this.toTemplate().pipe(this.toModel() as Runnable);
}
}
interface DriveFileReadParams
extends GoogleVertexAIConnectionParams<GoogleAuthOptions> {
fileId: string;
}
interface DriveCallOptions extends AsyncCallerCallOptions {
// Empty, I think
}
interface DriveFileMakerSuiteResponse extends GoogleResponse {
data: MakerSuitePromptData;
}
export class DriveFileReadConnection
extends GoogleConnection<DriveCallOptions, DriveFileMakerSuiteResponse>
implements DriveFileReadParams
{
endpoint: string;
apiVersion: string;
fileId: string;
constructor(fields: DriveFileReadParams, caller: AsyncCaller) {
super(
caller,
new GoogleAuth({
scopes: "https://www.googleapis.com/auth/drive.readonly",
...fields.authOptions,
})
);
this.endpoint = fields.endpoint ?? "www.googleapis.com";
this.apiVersion = fields.apiVersion ?? "v3";
this.fileId = fields.fileId;
}
async buildUrl(): Promise<string> {
return `https://${this.endpoint}/drive/${this.apiVersion}/files/${this.fileId}?alt=media`;
}
buildMethod(): GoogleAbstractedClientOpsMethod {
return "GET";
}
async request(
options?: DriveCallOptions
): Promise<DriveFileMakerSuiteResponse> {
return this._request(undefined, options ?? {});
}
}
export interface CacheEntry {
updated: number;
prompt: MakerSuitePrompt;
}
/**
* A class allowing access to MakerSuite prompts that have been saved in
* Google Drive.
* MakerSuite prompts are pulled based on their Google Drive ID (which is available
* from Google Drive or as part of the URL when the prompt is open in MakerSuite).
* There is a basic cache that will store the prompt in memory for a time specified
* in milliseconds. This defaults to 0, indicating the prompt should always be
* pulled from Google Drive.
*/
export class MakerSuiteHub {
cache: Record<string, CacheEntry> = {};
cacheTimeout: number;
caller: AsyncCaller;
constructor(config?: MakerSuiteHubConfig) {
this.cacheTimeout = config?.cacheTimeout ?? 0;
this.caller = config?.caller ?? new AsyncCaller({});
}
/**
* Is the current cache entry valid, or does it need to be refreshed.
* It will need to be refreshed under any of the following conditions:
* - It does not currently exist in the cache
* - The cacheTimeout is 0
* - The cache was last updated longer ago than the cacheTimeout allows
* @param entry - The cache entry, including when this prompt was last refreshed
*/
isValid(entry: CacheEntry): boolean {
// If we don't have a record, it can't be valid
// And if the cache timeout is 0, we will always refresh, so the cache is invalid
if (!entry || this.cacheTimeout === 0) {
return false;
}
const now = Date.now();
const expiration = entry.updated + this.cacheTimeout;
return expiration > now;
}
/**
* Get a MakerSuitePrompt that is specified by the Google Drive ID.
* This will always be loaded from Google Drive.
* @param id
* @return A MakerSuitePrompt which can be used to create a template, model, or chain.
*/
async forcePull(id: string): Promise<MakerSuitePrompt> {
const fields: DriveFileReadParams = {
fileId: id,
};
const connection = new DriveFileReadConnection(fields, this.caller);
const result = await connection.request();
const ret = new MakerSuitePrompt(result.data);
this.cache[id] = {
prompt: ret,
updated: Date.now(),
};
return ret;
}
/**
* Get a MakerSuitePrompt that is specified by the Google Drive ID. This may be
* loaded from Google Drive or, if there is a valid copy in the cache, the cached
* copy will be returned.
* @param id
* @return A MakerSuitePrompt which can be used to create a template, model, or chain.
*/
async pull(id: string): Promise<MakerSuitePrompt> {
const entry = this.cache[id];
const ret = this.isValid(entry) ? entry.prompt : await this.forcePull(id);
return ret;
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite/llms.ts
|
import { TextServiceClient, protos } from "@google-ai/generativelanguage";
import { GoogleAuth } from "google-auth-library";
import { type BaseLLMParams, LLM } from "@langchain/core/language_models/llms";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
/**
* @deprecated - Deprecated by Google. Will be removed in 0.3.0
*
* Input for Text generation for Google Palm
*/
export interface GooglePaLMTextInput extends BaseLLMParams {
/**
* Model Name to use
*
* Alias for `model`
*
* Note: The format must follow the pattern - `models/{model}`
*/
modelName?: string;
/**
* Model Name to use
*
* Note: The format must follow the pattern - `models/{model}`
*/
model?: string;
/**
* Controls the randomness of the output.
*
* Values can range from [0.0,1.0], inclusive. A value closer to 1.0
* will produce responses that are more varied and creative, while
* a value closer to 0.0 will typically result in more straightforward
* responses from the model.
*
* Note: The default value varies by model
*/
temperature?: number;
/**
* Maximum number of tokens to generate in the completion.
*/
maxOutputTokens?: number;
/**
* Top-p changes how the model selects tokens for output.
*
* Tokens are selected from most probable to least until the sum
* of their probabilities equals the top-p value.
*
* For example, if tokens A, B, and C have a probability of
* .3, .2, and .1 and the top-p value is .5, then the model will
* select either A or B as the next token (using temperature).
*
* Note: The default value varies by model
*/
topP?: number;
/**
* Top-k changes how the model selects tokens for output.
*
* A top-k of 1 means the selected token is the most probable among
* all tokens in the model’s vocabulary (also called greedy decoding),
* while a top-k of 3 means that the next token is selected from
* among the 3 most probable tokens (using temperature).
*
* Note: The default value varies by model
*/
topK?: number;
/**
* The set of character sequences (up to 5) that will stop output generation.
* If specified, the API will stop at the first appearance of a stop
* sequence.
*
* Note: The stop sequence will not be included as part of the response.
*/
stopSequences?: string[];
/**
* A list of unique `SafetySetting` instances for blocking unsafe content. The API will block
* any prompts and responses that fail to meet the thresholds set by these settings. If there
* is no `SafetySetting` for a given `SafetyCategory` provided in the list, the API will use
* the default safety setting for that category.
*/
safetySettings?: protos.google.ai.generativelanguage.v1beta2.ISafetySetting[];
/**
* Google Palm API key to use
*/
apiKey?: string;
}
/**
* @deprecated - Deprecated by Google. Will be removed in 0.3.0
*
* Google Palm 2 Language Model Wrapper to generate texts
*/
export class GooglePaLM extends LLM implements GooglePaLMTextInput {
lc_serializable = true;
get lc_secrets(): { [key: string]: string } | undefined {
return {
apiKey: "GOOGLE_PALM_API_KEY",
};
}
modelName = "models/text-bison-001";
model = "models/text-bison-001";
temperature?: number; // default value chosen based on model
maxOutputTokens?: number; // defaults to 64
topP?: number; // default value chosen based on model
topK?: number; // default value chosen based on model
stopSequences: string[] = [];
safetySettings?: protos.google.ai.generativelanguage.v1beta2.ISafetySetting[]; // default safety setting for that category
apiKey?: string;
private client: TextServiceClient;
constructor(fields?: GooglePaLMTextInput) {
super(fields ?? {});
this.modelName = fields?.model ?? fields?.modelName ?? this.model;
this.model = this.modelName;
this.temperature = fields?.temperature ?? this.temperature;
if (this.temperature && (this.temperature < 0 || this.temperature > 1)) {
throw new Error("`temperature` must be in the range of [0.0,1.0]");
}
this.maxOutputTokens = fields?.maxOutputTokens ?? this.maxOutputTokens;
if (this.maxOutputTokens && this.maxOutputTokens < 0) {
throw new Error("`maxOutputTokens` must be a positive integer");
}
this.topP = fields?.topP ?? this.topP;
if (this.topP && this.topP < 0) {
throw new Error("`topP` must be a positive integer");
}
if (this.topP && this.topP > 1) {
throw new Error("Google PaLM `topP` must in the range of [0,1]");
}
this.topK = fields?.topK ?? this.topK;
if (this.topK && this.topK < 0) {
throw new Error("`topK` must be a positive integer");
}
this.stopSequences = fields?.stopSequences ?? this.stopSequences;
this.safetySettings = fields?.safetySettings ?? this.safetySettings;
if (this.safetySettings && this.safetySettings.length > 0) {
const safetySettingsSet = new Set(
this.safetySettings.map((s) => s.category)
);
if (safetySettingsSet.size !== this.safetySettings.length) {
throw new Error(
"The categories in `safetySettings` array must be unique"
);
}
}
this.apiKey =
fields?.apiKey ?? getEnvironmentVariable("GOOGLE_PALM_API_KEY");
if (!this.apiKey) {
throw new Error(
"Please set an API key for Google Palm 2 in the environment variable GOOGLE_PALM_API_KEY or in the `apiKey` field of the GooglePalm constructor"
);
}
this.client = new TextServiceClient({
authClient: new GoogleAuth().fromAPIKey(this.apiKey),
});
}
_llmType(): string {
return "googlepalm";
}
async _call(
prompt: string,
options: this["ParsedCallOptions"]
): Promise<string> {
const res = await this.caller.callWithOptions(
{ signal: options.signal },
this._generateText.bind(this),
prompt
);
return res ?? "";
}
protected async _generateText(
prompt: string
): Promise<string | null | undefined> {
const res = await this.client.generateText({
model: this.model,
temperature: this.temperature,
candidateCount: 1,
topK: this.topK,
topP: this.topP,
maxOutputTokens: this.maxOutputTokens,
stopSequences: this.stopSequences,
safetySettings: this.safetySettings,
prompt: {
text: prompt,
},
});
return res[0].candidates && res[0].candidates.length > 0
? res[0].candidates[0].output
: undefined;
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite/chat_models.ts
|
import { DiscussServiceClient } from "@google-ai/generativelanguage";
import type { protos } from "@google-ai/generativelanguage";
import { GoogleAuth } from "google-auth-library";
import { CallbackManagerForLLMRun } from "@langchain/core/callbacks/manager";
import {
AIMessage,
BaseMessage,
ChatMessage,
isBaseMessage,
} from "@langchain/core/messages";
import { ChatResult } from "@langchain/core/outputs";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import {
BaseChatModel,
type BaseChatModelParams,
} from "@langchain/core/language_models/chat_models";
export type BaseMessageExamplePair = {
input: BaseMessage;
output: BaseMessage;
};
/**
* @deprecated - Deprecated by Google. Will be removed in 0.3.0
*
* An interface defining the input to the ChatGooglePaLM class.
*/
export interface GooglePaLMChatInput extends BaseChatModelParams {
/**
* Model Name to use
*
* Note: The format must follow the pattern - `models/{model}`
* Alias for `model`
*/
modelName?: string;
/**
* Model Name to use
*
* Note: The format must follow the pattern - `models/{model}`
*/
model?: string;
/**
* Controls the randomness of the output.
*
* Values can range from [0.0,1.0], inclusive. A value closer to 1.0
* will produce responses that are more varied and creative, while
* a value closer to 0.0 will typically result in less surprising
* responses from the model.
*
* Note: The default value varies by model
*/
temperature?: number;
/**
* Top-p changes how the model selects tokens for output.
*
* Tokens are selected from most probable to least until the sum
* of their probabilities equals the top-p value.
*
* For example, if tokens A, B, and C have a probability of
* .3, .2, and .1 and the top-p value is .5, then the model will
* select either A or B as the next token (using temperature).
*
* Note: The default value varies by model
*/
topP?: number;
/**
* Top-k changes how the model selects tokens for output.
*
* A top-k of 1 means the selected token is the most probable among
* all tokens in the model’s vocabulary (also called greedy decoding),
* while a top-k of 3 means that the next token is selected from
* among the 3 most probable tokens (using temperature).
*
* Note: The default value varies by model
*/
topK?: number;
examples?:
| protos.google.ai.generativelanguage.v1beta2.IExample[]
| BaseMessageExamplePair[];
/**
* Google Palm API key to use
*/
apiKey?: string;
}
function getMessageAuthor(message: BaseMessage) {
const type = message._getType();
if (ChatMessage.isInstance(message)) {
return message.role;
}
return message.name ?? type;
}
/**
* @deprecated - Deprecated by Google. Will be removed in 0.3.0
*
* A class that wraps the Google Palm chat model.
*
* @example
* ```typescript
* const model = new ChatGooglePaLM({
* apiKey: "<YOUR API KEY>",
* temperature: 0.7,
* model: "models/chat-bison-001",
* topK: 40,
* topP: 1,
* examples: [
* {
* input: new HumanMessage("What is your favorite sock color?"),
* output: new AIMessage("My favorite sock color be arrrr-ange!"),
* },
* ],
* });
* const questions = [
* new SystemMessage(
* "You are a funny assistant that answers in pirate language."
* ),
* new HumanMessage("What is your favorite food?"),
* ];
* const res = await model.invoke(questions);
* console.log({ res });
* ```
*/
export class ChatGooglePaLM
extends BaseChatModel
implements GooglePaLMChatInput
{
static lc_name() {
return "ChatGooglePaLM";
}
lc_serializable = true;
get lc_secrets(): { [key: string]: string } | undefined {
return {
apiKey: "GOOGLE_PALM_API_KEY",
};
}
modelName = "models/chat-bison-001";
model = "models/chat-bison-001";
temperature?: number; // default value chosen based on model
topP?: number; // default value chosen based on model
topK?: number; // default value chosen based on model
examples: protos.google.ai.generativelanguage.v1beta2.IExample[] = [];
apiKey?: string;
private client: DiscussServiceClient;
constructor(fields?: GooglePaLMChatInput) {
super(fields ?? {});
this.modelName = fields?.model ?? fields?.modelName ?? this.model;
this.model = this.modelName;
this.temperature = fields?.temperature ?? this.temperature;
if (this.temperature && (this.temperature < 0 || this.temperature > 1)) {
throw new Error("`temperature` must be in the range of [0.0,1.0]");
}
this.topP = fields?.topP ?? this.topP;
if (this.topP && this.topP < 0) {
throw new Error("`topP` must be a positive integer");
}
this.topK = fields?.topK ?? this.topK;
if (this.topK && this.topK < 0) {
throw new Error("`topK` must be a positive integer");
}
this.examples =
fields?.examples?.map((example) => {
if (
(isBaseMessage(example.input) &&
typeof example.input.content !== "string") ||
(isBaseMessage(example.output) &&
typeof example.output.content !== "string")
) {
throw new Error(
"GooglePaLM example messages may only have string content."
);
}
return {
input: {
...example.input,
content: example.input?.content as string,
},
output: {
...example.output,
content: example.output?.content as string,
},
};
}) ?? this.examples;
this.apiKey =
fields?.apiKey ?? getEnvironmentVariable("GOOGLE_PALM_API_KEY");
if (!this.apiKey) {
throw new Error(
"Please set an API key for Google Palm 2 in the environment variable GOOGLE_PALM_API_KEY or in the `apiKey` field of the GooglePalm constructor"
);
}
this.client = new DiscussServiceClient({
authClient: new GoogleAuth().fromAPIKey(this.apiKey),
});
}
_combineLLMOutput() {
return [];
}
_llmType() {
return "googlepalm";
}
async _generate(
messages: BaseMessage[],
options: this["ParsedCallOptions"],
runManager?: CallbackManagerForLLMRun
): Promise<ChatResult> {
const palmMessages = await this.caller.callWithOptions(
{ signal: options.signal },
this._generateMessage.bind(this),
this._mapBaseMessagesToPalmMessages(messages),
this._getPalmContextInstruction(messages),
this.examples
);
const chatResult = this._mapPalmMessagesToChatResult(palmMessages);
// Google Palm doesn't provide streaming as of now. But to support streaming handlers
// we call the handler with entire response text
void runManager?.handleLLMNewToken(
chatResult.generations.length > 0 ? chatResult.generations[0].text : ""
);
return chatResult;
}
protected async _generateMessage(
messages: protos.google.ai.generativelanguage.v1beta2.IMessage[],
context?: string,
examples?: protos.google.ai.generativelanguage.v1beta2.IExample[]
): Promise<protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse> {
const [palmMessages] = await this.client.generateMessage({
candidateCount: 1,
model: this.model,
temperature: this.temperature,
topK: this.topK,
topP: this.topP,
prompt: {
context,
examples,
messages,
},
});
return palmMessages;
}
protected _getPalmContextInstruction(
messages: BaseMessage[]
): string | undefined {
// get the first message and checks if it's a system 'system' messages
const systemMessage =
messages.length > 0 && getMessageAuthor(messages[0]) === "system"
? messages[0]
: undefined;
if (
systemMessage?.content !== undefined &&
typeof systemMessage.content !== "string"
) {
throw new Error("Non-string system message content is not supported.");
}
return systemMessage?.content;
}
protected _mapBaseMessagesToPalmMessages(
messages: BaseMessage[]
): protos.google.ai.generativelanguage.v1beta2.IMessage[] {
// remove all 'system' messages
const nonSystemMessages = messages.filter(
(m) => getMessageAuthor(m) !== "system"
);
// requires alternate human & ai messages. Throw error if two messages are consecutive
nonSystemMessages.forEach((msg, index) => {
if (index < 1) return;
if (
getMessageAuthor(msg) === getMessageAuthor(nonSystemMessages[index - 1])
) {
throw new Error(
`Google PaLM requires alternate messages between authors`
);
}
});
return nonSystemMessages.map((m) => {
if (typeof m.content !== "string") {
throw new Error(
"ChatGooglePaLM does not support non-string message content."
);
}
return {
author: getMessageAuthor(m),
content: m.content,
citationMetadata: {
citationSources: m.additional_kwargs.citationSources as
| protos.google.ai.generativelanguage.v1beta2.ICitationSource[]
| undefined,
},
};
});
}
protected _mapPalmMessagesToChatResult(
msgRes: protos.google.ai.generativelanguage.v1beta2.IGenerateMessageResponse
): ChatResult {
if (
msgRes.candidates &&
msgRes.candidates.length > 0 &&
msgRes.candidates[0]
) {
const message = msgRes.candidates[0];
return {
generations: [
{
text: message.content ?? "",
message: new AIMessage({
content: message.content ?? "",
name: message.author === null ? undefined : message.author,
additional_kwargs: {
citationSources: message.citationMetadata?.citationSources,
filters: msgRes.filters, // content filters applied
},
}),
},
],
};
}
// if rejected or error, return empty generations with reason in filters
return {
generations: [],
llmOutput: {
filters: msgRes.filters,
},
};
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite/tests/googlemakersuitehub.int.test.ts
|
// noinspection DuplicatedCode
import fs from "fs";
import { fileURLToPath } from "node:url";
import * as path from "path";
import { describe, test } from "@jest/globals";
import { HumanMessage } from "@langchain/core/messages";
import { AsyncCaller } from "@langchain/core/utils/async_caller";
import { ChatGooglePaLM } from "../chat_models.js";
import { GooglePaLM } from "../llms.js";
import {
DriveFileReadConnection,
MakerSuiteHub,
MakerSuitePrompt,
} from "../googlemakersuitehub.js";
describe.skip("Google Maker Suite Hub Integration", () => {
describe("Prompt", () => {
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const chatFile = JSON.parse(
fs.readFileSync(
`${__dirname}/googlemakersuite-files/chatPrompt.json`,
"utf8"
)
);
const dataFile = JSON.parse(
fs.readFileSync(
`${__dirname}/googlemakersuite-files/dataPrompt.json`,
"utf8"
)
);
const textFile = JSON.parse(
fs.readFileSync(
`${__dirname}/googlemakersuite-files/textPrompt.json`,
"utf8"
)
);
test("text chain", async () => {
const prompt = new MakerSuitePrompt(textFile);
const chain = prompt.toChain();
const result = await chain.invoke({
product: "shoes",
});
// console.log("text chain result", result);
expect(result).toBeTruthy();
});
test("data chain", async () => {
const prompt = new MakerSuitePrompt(dataFile);
const chain = prompt.toChain();
const result = await chain.invoke({
description: "shoes",
});
// console.log("data chain result", result);
expect(result).toBeTruthy();
});
test("chat model", async () => {
const prompt = new MakerSuitePrompt(chatFile);
const model = prompt.toModel() as ChatGooglePaLM;
const message = new HumanMessage("Hello!");
const result = await model.invoke([message]);
expect(result).toBeTruthy();
// console.log({ result });
});
});
describe("Drive", () => {
test("file get media", async () => {
const fileId = "1IAWobj3BYvbj5X3JOAKaoXTcNJlZLdpK";
const caller = new AsyncCaller({});
const connection = new DriveFileReadConnection({ fileId }, caller);
// console.log("connection client", connection?.client);
// @eslint-disable-next-line/@typescript-eslint/ban-ts-comment
// @ts-expect-error unused var
const result = await connection.request();
// console.log(result);
});
});
describe("Hub", () => {
const hub = new MakerSuiteHub();
test("text model", async () => {
const prompt = await hub.pull("1gxLasQIeQdwR4wxtV_nb93b_g9f0GaMm");
const model = prompt.toModel() as GooglePaLM;
const result = await model.invoke(
"What would be a good name for a company that makes socks"
);
// console.log("text chain result", result);
expect(result).toBeTruthy();
});
test("text chain", async () => {
const prompt = await hub.pull("1gxLasQIeQdwR4wxtV_nb93b_g9f0GaMm");
const result = await prompt.toChain().invoke({ product: "socks" });
// console.log("text chain result", result);
expect(result).toBeTruthy();
});
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite/tests/googlemakersuitehub.test.ts
|
import fs from "fs";
import { fileURLToPath } from "node:url";
import * as path from "path";
import { describe, expect, test } from "@jest/globals";
import { ChatGooglePaLM } from "../chat_models.js";
import { MakerSuiteHub, MakerSuitePrompt } from "../googlemakersuitehub.js";
describe("Google Maker Suite Hub", () => {
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const chatFile = JSON.parse(
fs.readFileSync(
`${__dirname}/googlemakersuite-files/chatPrompt.json`,
"utf8"
)
);
const dataFile = JSON.parse(
fs.readFileSync(
`${__dirname}/googlemakersuite-files/dataPrompt.json`,
"utf8"
)
);
const textFile = JSON.parse(
fs.readFileSync(
`${__dirname}/googlemakersuite-files/textPrompt.json`,
"utf8"
)
);
// We don't need a real key
// eslint-disable-next-line no-process-env
process.env.GOOGLE_PALM_API_KEY = "test";
describe("Prompt", () => {
test("text type", () => {
const prompt = new MakerSuitePrompt(textFile);
expect(prompt.promptType).toEqual("text");
});
test("text template", () => {
const prompt = new MakerSuitePrompt(textFile);
const template = prompt.toTemplate();
expect(template.template).toEqual(
"What would be a good name for a company that makes {product}?"
);
});
test("text model", () => {
const prompt = new MakerSuitePrompt(textFile);
const model = prompt.toModel();
// console.log(model.lc_namespace);
expect(model.lc_namespace).toEqual(["langchain", "llms", "googlepalm"]);
});
test("data type", () => {
const prompt = new MakerSuitePrompt(dataFile);
expect(prompt.promptType).toEqual("data");
});
test("data template", () => {
const prompt = new MakerSuitePrompt(dataFile);
const template = prompt.toTemplate();
// console.log("data template", template.template);
expect(template.template).toEqual(
"Given a product description, you should return a name for that product that includes something about rainbows.\n" +
"description: socks\n" +
"product: spectrum socks\n" +
"description: hair ties\n" +
"product: rainbows^2\n" +
"description: {description}\n" +
"product: "
);
});
test("data model", () => {
const prompt = new MakerSuitePrompt(dataFile);
const model = prompt.toModel();
expect(model.lc_namespace).toEqual(["langchain", "llms", "googlepalm"]);
});
test("chat type", () => {
const prompt = new MakerSuitePrompt(chatFile);
expect(prompt.promptType).toEqual("chat");
});
test("chat model", () => {
const prompt = new MakerSuitePrompt(chatFile);
const model = prompt.toModel();
expect(model.lc_namespace).toEqual([
"langchain",
"chat_models",
"googlepalm",
]);
expect((model as ChatGooglePaLM).examples).toEqual([
{
input: { content: "What time is it?" },
output: { content: "2023-09-16T02:03:04-0500" },
},
]);
});
});
describe("MakerSuiteHub", () => {
test("isValid no entry", () => {
const nonexistentId = "nonexistent";
const hub = new MakerSuiteHub({ cacheTimeout: 1000 });
const entry = hub.cache[nonexistentId];
const isValid = hub.isValid(entry);
expect(isValid).toEqual(false);
});
test("isValid timeout 0", () => {
// This should never be valid because the cache timeout will be 0
const fakeId = "fake";
const hub = new MakerSuiteHub({ cacheTimeout: 0 });
const entry = {
updated: Date.now(),
prompt: new MakerSuitePrompt({
textPrompt: {
value: "test",
},
}),
};
hub.cache[fakeId] = entry;
const isValid = hub.isValid(entry);
expect(isValid).toEqual(false);
});
test("isValid valid", () => {
const fakeId = "fake";
const hub = new MakerSuiteHub({ cacheTimeout: 60000 });
const entry = {
updated: Date.now(),
prompt: new MakerSuitePrompt({
textPrompt: {
value: "test",
},
}),
};
hub.cache[fakeId] = entry;
const isValid = hub.isValid(entry);
expect(isValid).toEqual(true);
});
test("isValid timeout", () => {
const fakeId = "fake";
const hub = new MakerSuiteHub({ cacheTimeout: 60000 });
const entry = {
updated: Date.now() - 100000,
prompt: new MakerSuitePrompt({
textPrompt: {
value: "test",
},
}),
};
hub.cache[fakeId] = entry;
const isValid = hub.isValid(entry);
expect(isValid).toEqual(false);
});
});
});
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite/tests
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite/tests/googlemakersuite-files/chatPrompt.json
|
{
"runSettings": {
"temperature": 0.25,
"model": "models/chat-bison-001",
"candidateCount": 1,
"topP": 0.95,
"topK": 40,
"maxOutputTokens": 1024
},
"multiturnPrompt": {
"preamble": "You are responsible for returning date and time information based on the user\u0027s input. All your date and time responses should be as an ISO8601 formatted response that include the year, month, day, hour, minute, second, and time zone offset. You should only return this time information and nothing else.\n",
"primingExchanges": [
{
"request": "What time is it?",
"response": "2023-09-16T02:03:04-0500",
"source": "MODEL_EDITED",
"id": "4B26EE6A-6171-4626-80B6-207491D106BF"
},
{
"source": "USER",
"id": "36D72C06-423E-4E00-BA27-DEC44CBA5A13"
}
],
"sessions": [
{
"sessionExchanges": [
{
"request": "What time is it?",
"response": "The time is 2023-09-16T02:04:05-0500.",
"source": "MODEL",
"id": "9E4D6C9A-81D2-4EE9-BE8B-96C84F1FDA64"
},
{
"request": "What time was it one week ago?",
"response": "The time one week ago was 2023-09-09T02:04:05-0500.",
"source": "MODEL",
"id": "EA76CED1-F626-46F3-8CCA-4C9C821B2003"
}
]
}
]
}
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite/tests
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite/tests/googlemakersuite-files/textPrompt.json
|
{
"textPrompt": {
"value": "What would be a good name for a company that makes {{30E275F8-0B60-4E71-843D-9865F4D4EFD4:product:}}?",
"variables": [
{
"variableId": "30E275F8-0B60-4E71-843D-9865F4D4EFD4",
"displayName": "product"
}
]
},
"runSettings": {
"temperature": 0.7,
"model": "models/text-bison-001",
"candidateCount": 1,
"topP": 0.95,
"topK": 40,
"maxOutputTokens": 1024,
"safetySettings": [
{
"category": "HARM_CATEGORY_DEROGATORY",
"threshold": "BLOCK_LOW_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_TOXICITY",
"threshold": "BLOCK_LOW_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_VIOLENCE",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_SEXUAL",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_MEDICAL",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_DANGEROUS",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
}
]
},
"testExamples": [
{
"inputBindings": {
"30E275F8-0B60-4E71-843D-9865F4D4EFD4": ""
},
"modelResponses": [{}]
}
]
}
|
0
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite/tests
|
lc_public_repos/langchainjs/libs/langchain-community/src/experimental/hubs/makersuite/tests/googlemakersuite-files/dataPrompt.json
|
{
"dataPrompt": {
"preamble": "Given a product description, you should return a name for that product that includes something about rainbows.",
"columns": [
{
"columnId": "CFA438B7-313B-4A50-AF74-3ACBC9216A4B",
"displayName": "description:",
"isInput": true
},
{
"columnId": "7D38B937-6636-4AAC-9DFD-B4A60D98C011",
"displayName": "product:"
}
],
"rows": [
{
"columnBindings": {
"CFA438B7-313B-4A50-AF74-3ACBC9216A4B": "socks",
"7D38B937-6636-4AAC-9DFD-B4A60D98C011": "spectrum socks"
},
"rowId": "D412F0BE-5C81-401D-917C-758A6F14EEC4"
},
{
"columnBindings": {
"CFA438B7-313B-4A50-AF74-3ACBC9216A4B": "hair ties",
"7D38B937-6636-4AAC-9DFD-B4A60D98C011": "rainbows^2"
},
"rowId": "C77A45B4-74B4-41F3-AD8E-06F0C1D9D820"
}
],
"rowsUsed": [
"D412F0BE-5C81-401D-917C-758A6F14EEC4",
"C77A45B4-74B4-41F3-AD8E-06F0C1D9D820"
]
},
"runSettings": {
"temperature": 0.7,
"model": "models/text-bison-001",
"candidateCount": 1,
"topP": 0.95,
"topK": 40,
"maxOutputTokens": 1024,
"safetySettings": [
{
"category": "HARM_CATEGORY_DEROGATORY",
"threshold": "BLOCK_LOW_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_TOXICITY",
"threshold": "BLOCK_LOW_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_VIOLENCE",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_SEXUAL",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_MEDICAL",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
},
{
"category": "HARM_CATEGORY_DANGEROUS",
"threshold": "BLOCK_MEDIUM_AND_ABOVE"
}
]
},
"testExamples": [
{
"inputBindings": {
"CFA438B7-313B-4A50-AF74-3ACBC9216A4B": "condoms"
},
"modelResponses": [
{
"response": "rainbow rhapsody",
"safetyRatings": [
{
"category": "HARM_CATEGORY_DEROGATORY",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_TOXICITY",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_VIOLENCE",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_SEXUAL",
"probability": "LOW"
},
{
"category": "HARM_CATEGORY_MEDICAL",
"probability": "NEGLIGIBLE"
},
{
"category": "HARM_CATEGORY_DANGEROUS",
"probability": "NEGLIGIBLE"
}
]
}
]
}
]
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.