index int64 0 0 | repo_id stringclasses 596 values | file_path stringlengths 31 168 | content stringlengths 1 6.2M |
|---|---|---|---|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/load/serializable.ts | export * from "@langchain/core/load/serializable";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/load/import_constants.ts | // Auto-generated by `scripts/create-entrypoints.js`. Do not edit manually.
export const optionalImportEntrypoints: string[] = [
"langchain/agents/load",
"langchain/agents/toolkits/sql",
"langchain/tools/sql",
"langchain/tools/webbrowser",
"langchain/chains/load",
"langchain/chains/query_constructor",
"langchain/chains/query_constructor/ir",
"langchain/chains/sql_db",
"langchain/chains/graph_qa/cypher",
"langchain/chat_models/universal",
"langchain/document_loaders/fs/buffer",
"langchain/document_loaders/fs/directory",
"langchain/document_loaders/fs/json",
"langchain/document_loaders/fs/multi_file",
"langchain/document_loaders/fs/text",
"langchain/sql_db",
"langchain/output_parsers/expression",
"langchain/retrievers/self_query",
"langchain/retrievers/self_query/functional",
"langchain/cache/file_system",
"langchain/stores/file/node",
"langchain/storage/file_system",
"langchain/hub",
"langchain/experimental/prompts/handlebars",
];
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/load/map_keys.ts | export interface SerializedFields {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/load/import_type.ts | // Auto-generated by `scripts/create-entrypoints.js`. Do not edit manually.
export interface OptionalImportMap {}
export interface SecretMap {
OPENAI_API_KEY?: string;
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/load/import_map.ts | // Auto-generated by build script. Do not edit manually.
export * as agents from "../agents/index.js";
export * as agents__toolkits from "../agents/toolkits/index.js";
export * as agents__format_scratchpad from "../agents/format_scratchpad/openai_functions.js";
export * as agents__format_scratchpad__openai_tools from "../agents/format_scratchpad/openai_tools.js";
export * as agents__format_scratchpad__log from "../agents/format_scratchpad/log.js";
export * as agents__format_scratchpad__xml from "../agents/format_scratchpad/xml.js";
export * as agents__format_scratchpad__log_to_message from "../agents/format_scratchpad/log_to_message.js";
export * as agents__react__output_parser from "../agents/react/output_parser.js";
export * as agents__xml__output_parser from "../agents/xml/output_parser.js";
export * as agents__openai__output_parser from "../agents/openai/output_parser.js";
export * as tools from "../tools/index.js";
export * as tools__chain from "../tools/chain.js";
export * as tools__render from "../tools/render.js";
export * as tools__retriever from "../tools/retriever.js";
export * as chains from "../chains/index.js";
export * as chains__combine_documents from "../chains/combine_documents/index.js";
export * as chains__combine_documents__reduce from "../chains/combine_documents/reduce.js";
export * as chains__history_aware_retriever from "../chains/history_aware_retriever.js";
export * as chains__openai_functions from "../chains/openai_functions/index.js";
export * as chains__retrieval from "../chains/retrieval.js";
export * as embeddings__cache_backed from "../embeddings/cache_backed.js";
export * as embeddings__fake from "../embeddings/fake.js";
export * as vectorstores__memory from "../vectorstores/memory.js";
export * as text_splitter from "../text_splitter.js";
export * as memory from "../memory/index.js";
export * as memory__chat_memory from "../memory/chat_memory.js";
export * as document_loaders__base from "../document_loaders/base.js";
export * as document_transformers__openai_functions from "../document_transformers/openai_functions.js";
export * as callbacks from "../callbacks/index.js";
export * as output_parsers from "../output_parsers/index.js";
export * as retrievers__contextual_compression from "../retrievers/contextual_compression.js";
export * as retrievers__document_compressors from "../retrievers/document_compressors/index.js";
export * as retrievers__ensemble from "../retrievers/ensemble.js";
export * as retrievers__multi_query from "../retrievers/multi_query.js";
export * as retrievers__multi_vector from "../retrievers/multi_vector.js";
export * as retrievers__parent_document from "../retrievers/parent_document.js";
export * as retrievers__time_weighted from "../retrievers/time_weighted.js";
export * as retrievers__document_compressors__chain_extract from "../retrievers/document_compressors/chain_extract.js";
export * as retrievers__document_compressors__embeddings_filter from "../retrievers/document_compressors/embeddings_filter.js";
export * as retrievers__hyde from "../retrievers/hyde.js";
export * as retrievers__score_threshold from "../retrievers/score_threshold.js";
export * as retrievers__matryoshka_retriever from "../retrievers/matryoshka_retriever.js";
export * as stores__doc__base from "../stores/doc/base.js";
export * as stores__doc__in_memory from "../stores/doc/in_memory.js";
export * as stores__file__in_memory from "../stores/file/in_memory.js";
export * as stores__message__in_memory from "../stores/message/in_memory.js";
export * as storage__encoder_backed from "../storage/encoder_backed.js";
export * as storage__in_memory from "../storage/in_memory.js";
export * as util__document from "../util/document.js";
export * as util__math from "../util/math.js";
export * as util__time from "../util/time.js";
export * as experimental__autogpt from "../experimental/autogpt/index.js";
export * as experimental__openai_assistant from "../experimental/openai_assistant/index.js";
export * as experimental__openai_files from "../experimental/openai_files/index.js";
export * as experimental__babyagi from "../experimental/babyagi/index.js";
export * as experimental__generative_agents from "../experimental/generative_agents/index.js";
export * as experimental__plan_and_execute from "../experimental/plan_and_execute/index.js";
export * as experimental__chains__violation_of_expectations from "../experimental/chains/violation_of_expectations/index.js";
export * as experimental__masking from "../experimental/masking/index.js";
export * as experimental__prompts__custom_format from "../experimental/prompts/custom_format.js";
export * as evaluation from "../evaluation/index.js";
export * as smith from "../smith/index.js";
export * as runnables__remote from "../runnables/remote.js";
export * as indexes from "../indexes/index.js";
export * as schema__query_constructor from "../schema/query_constructor.js";
export * as schema__prompt_template from "../schema/prompt_template.js";
import {
ChatOpenAI,
OpenAI,
OpenAIEmbeddings
} from "@langchain/openai";
import {
PromptTemplate,
AIMessagePromptTemplate,
ChatMessagePromptTemplate,
ChatPromptTemplate,
HumanMessagePromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate,
ImagePromptTemplate,
PipelinePromptTemplate
} from "@langchain/core/prompts";
import {
AIMessage,
AIMessageChunk,
BaseMessage,
BaseMessageChunk,
ChatMessage,
ChatMessageChunk,
FunctionMessage,
FunctionMessageChunk,
HumanMessage,
HumanMessageChunk,
SystemMessage,
SystemMessageChunk,
ToolMessage,
ToolMessageChunk
} from "@langchain/core/messages";
import {
StringPromptValue
} from "@langchain/core/prompt_values";
import {
RouterRunnable,
RunnableAssign,
RunnableBinding,
RunnableBranch,
RunnableEach,
RunnableMap,
RunnableParallel,
RunnablePassthrough,
RunnablePick,
RunnableRetry,
RunnableSequence,
RunnableWithFallbacks,
RunnableWithMessageHistory
} from "@langchain/core/runnables";
import {
StringOutputParser
} from "@langchain/core/output_parsers";
import {
ChatGenerationChunk,
GenerationChunk
} from "@langchain/core/outputs";
const chat_models__openai = {
ChatOpenAI
};
export { chat_models__openai };
const llms__openai = {
OpenAI
};
export { llms__openai };
const embeddings__openai = {
OpenAIEmbeddings
};
export { embeddings__openai };
const prompts__prompt = {
PromptTemplate
};
export { prompts__prompt };
const schema__messages = {
AIMessage,
AIMessageChunk,
BaseMessage,
BaseMessageChunk,
ChatMessage,
ChatMessageChunk,
FunctionMessage,
FunctionMessageChunk,
HumanMessage,
HumanMessageChunk,
SystemMessage,
SystemMessageChunk,
ToolMessage,
ToolMessageChunk
};
export { schema__messages };
const schema = {
AIMessage,
AIMessageChunk,
BaseMessage,
BaseMessageChunk,
ChatMessage,
ChatMessageChunk,
FunctionMessage,
FunctionMessageChunk,
HumanMessage,
HumanMessageChunk,
SystemMessage,
SystemMessageChunk,
ToolMessage,
ToolMessageChunk
};
export { schema };
const prompts__chat = {
AIMessagePromptTemplate,
ChatMessagePromptTemplate,
ChatPromptTemplate,
HumanMessagePromptTemplate,
MessagesPlaceholder,
SystemMessagePromptTemplate
};
export { prompts__chat };
const prompts__image = {
ImagePromptTemplate
};
export { prompts__image };
const prompts__pipeline = {
PipelinePromptTemplate
};
export { prompts__pipeline };
const prompts__base = {
StringPromptValue
};
export { prompts__base };
const schema__runnable = {
RouterRunnable,
RunnableAssign,
RunnableBinding,
RunnableBranch,
RunnableEach,
RunnableMap,
RunnableParallel,
RunnablePassthrough,
RunnablePick,
RunnableRetry,
RunnableSequence,
RunnableWithFallbacks,
RunnableWithMessageHistory
};
export { schema__runnable };
const schema__output_parser = {
StringOutputParser
};
export { schema__output_parser };
const schema__output = {
ChatGenerationChunk,
GenerationChunk
};
export { schema__output };
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/load/index.ts | import { load as coreLoad } from "@langchain/core/load";
import { optionalImportEntrypoints } from "./import_constants.js";
import * as importMap from "./import_map.js";
import { OptionalImportMap } from "./import_type.js";
/**
* Load a LangChain module from a serialized text representation.
* NOTE: This functionality is currently in beta.
* Loaded classes may change independently of semver.
* @param text Serialized text representation of the module.
* @param secretsMap
* @param optionalImportsMap
* @returns A loaded instance of a LangChain module.
*/
export async function load<T>(
text: string,
// eslint-disable-next-line @typescript-eslint/no-explicit-any
secretsMap: Record<string, any> = {},
// eslint-disable-next-line @typescript-eslint/no-explicit-any
optionalImportsMap: OptionalImportMap & Record<string, any> = {}
): Promise<T> {
return coreLoad(text, {
secretsMap,
optionalImportsMap,
optionalImportEntrypoints,
importMap,
});
}
|
0 | lc_public_repos/langchainjs/langchain/src/load | lc_public_repos/langchainjs/langchain/src/load/tests/load.test.ts | import { test, expect } from "@jest/globals";
import { stringify } from "yaml";
import { z } from "zod";
import { RunnableSequence } from "@langchain/core/runnables";
import { OpenAI, ChatOpenAI } from "@langchain/openai";
import {
HumanMessagePromptTemplate,
SystemMessagePromptTemplate,
ChatPromptTemplate,
FewShotPromptTemplate,
PromptTemplate,
} from "@langchain/core/prompts";
import { LengthBasedExampleSelector } from "@langchain/core/example_selectors";
import { Serializable } from "@langchain/core/load/serializable";
import { ConsoleCallbackHandler } from "@langchain/core/tracers/console";
import { CommaSeparatedListOutputParser } from "@langchain/core/output_parsers";
import { LLMChain } from "../../chains/llm_chain.js";
import { initializeAgentExecutorWithOptions } from "../../agents/initialize.js";
import { Calculator } from "../../util/testing/tools/calculator.js";
import { RequestsGetTool } from "../../tools/requests.js";
import { JsonListKeysTool, JsonSpec } from "../../tools/json.js";
import { AgentExecutor } from "../../agents/executor.js";
import { StructuredOutputParser } from "../../output_parsers/structured.js";
import { RegexParser } from "../../output_parsers/regex.js";
import { load } from "../index.js";
test("serialize + deserialize custom classes", async () => {
class Person extends Serializable {
lc_namespace = ["langchain", "tests"];
get lc_secrets(): { [key: string]: string } | undefined {
return { apiKey: "PERSON_API_KEY" };
}
get lc_attributes(): { [key: string]: unknown } | undefined {
return { hello: this.hello };
}
lc_serializable = true;
hello = 3;
constructor(fields: { aField: string; apiKey: string; hello?: number }) {
super(fields);
}
}
class SpecialPerson extends Person {
get lc_secrets(): { [key: string]: string } | undefined {
return {
anotherApiKey: "SPECIAL_PERSON_API_KEY",
inherited: "SPECIAL_PERSON_INHERITED_API_KEY",
"nested.api.key": "SPECIAL_PERSON_NESTED_API_KEY",
};
}
get lc_attributes(): { [key: string]: unknown } | undefined {
return { by: this.bye };
}
bye = 4;
inherited: string;
nested: { api: { key: string } };
constructor(fields: {
aField: string;
apiKey: string;
anotherApiKey: string;
inehrited?: string;
nested?: { api: { key: string } };
hello?: number;
bye?: number;
}) {
super(fields);
this.inherited = fields.inehrited ?? "i-key";
this.nested = fields.nested ?? { api: { key: "n-key" } };
}
}
const person = new Person({ aField: "hello", apiKey: "a-key" });
const lc_argumentsBefore = person.lc_kwargs;
const str = JSON.stringify(person, null, 2);
expect(person.lc_kwargs).toEqual(lc_argumentsBefore);
expect(stringify(JSON.parse(str))).toMatchSnapshot();
const person2 = await load<Person>(
str,
{
PERSON_API_KEY: "a-key",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any,
{
"langchain/tests": { Person },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
);
expect(person2).toBeInstanceOf(Person);
expect(JSON.stringify(person2, null, 2)).toBe(str);
const sperson = new SpecialPerson({
aField: "hello",
apiKey: "a-key",
anotherApiKey: "b-key",
// We explicitly do not provide the inherited and nested key
// to test that it has been extracted during serialisation
// simulating obtaining value from environment value
// inherited: "i-key",
// nested: { api: { key: "n-key" } },
});
const sstr = JSON.stringify(sperson, null, 2);
expect(stringify(JSON.parse(sstr))).toMatchSnapshot();
const sperson2 = await load<Person>(
sstr,
{
PERSON_API_KEY: "a-key",
SPECIAL_PERSON_API_KEY: "b-key",
SPECIAL_PERSON_NESTED_API_KEY: "n-key",
SPECIAL_PERSON_INHERITED_API_KEY: "i-key",
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any,
{
"langchain/tests": { SpecialPerson },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} as any
);
expect(sperson2).toBeInstanceOf(SpecialPerson);
expect(JSON.stringify(sperson2, null, 2)).toBe(sstr);
});
test("serialize + deserialize llm", async () => {
// eslint-disable-next-line no-process-env
process.env.OPENAI_API_KEY = "openai-key";
const llm = new OpenAI({
temperature: 0.5,
modelName: "davinci",
});
llm.temperature = 0.7;
const lc_argumentsBefore = llm.lc_kwargs;
const str = JSON.stringify(llm, null, 2);
expect(llm.lc_kwargs).toEqual(lc_argumentsBefore);
expect(stringify(JSON.parse(str))).toMatchSnapshot();
expect(JSON.parse(str).kwargs.temperature).toBe(0.7);
expect(JSON.parse(str).kwargs.model).toBe("davinci");
expect(JSON.parse(str).kwargs.openai_api_key.type).toBe("secret");
// Accept secret in secret map
const llm2 = await load<OpenAI>(str, {
OPENAI_API_KEY: "openai-key",
});
expect(llm2).toBeInstanceOf(OpenAI);
expect(JSON.stringify(llm2, null, 2)).toBe(str);
// Accept secret as env var
const llm3 = await load<OpenAI>(str);
expect(llm3).toBeInstanceOf(OpenAI);
expect(llm.openAIApiKey).toBe(llm3.openAIApiKey);
expect(JSON.stringify(llm3, null, 2)).toBe(str);
});
test("serialize + deserialize llm chain string prompt", async () => {
const llm = new OpenAI({
temperature: 0.5,
modelName: "davinci",
openAIApiKey: "openai-key",
verbose: true,
callbacks: [
new ConsoleCallbackHandler(),
{
handleLLMEnd(_output) {
// console.log(output);
},
},
],
});
const prompt = PromptTemplate.fromTemplate("Hello, {name}!");
const chain = new LLMChain({ llm, prompt });
const str = JSON.stringify(chain, null, 2);
expect(JSON.parse(str).kwargs.callbacks).toBeUndefined();
expect(JSON.parse(str).kwargs.verbose).toBeUndefined();
expect(stringify(JSON.parse(str))).toMatchSnapshot();
const chain2 = await load<LLMChain>(str, {
OPENAI_API_KEY: "openai-key",
});
expect(chain2).toBeInstanceOf(LLMChain);
expect(JSON.stringify(chain2, null, 2)).toBe(str);
});
test("serialize + deserialize with new and old ids", async () => {
const prompt = PromptTemplate.fromTemplate("Hello, {name}!");
const strWithNewId = JSON.stringify(prompt, null, 2);
expect(stringify(JSON.parse(strWithNewId))).toMatchSnapshot();
expect(JSON.parse(strWithNewId).id).toEqual([
"langchain_core",
"prompts",
"prompt",
"PromptTemplate",
]);
const strWithOldId = JSON.stringify({
...JSON.parse(strWithNewId),
id: ["langchain", "prompts", "prompt", "PromptTemplate"],
});
const prompt2 = await load<PromptTemplate>(strWithOldId);
expect(prompt2).toBeInstanceOf(PromptTemplate);
const prompt3 = await load<PromptTemplate>(strWithNewId);
expect(prompt3).toBeInstanceOf(PromptTemplate);
});
test("serialize + deserialize runnable sequence with new and old ids", async () => {
const runnable = RunnableSequence.from([
ChatPromptTemplate.fromTemplate("hi there"),
new ChatOpenAI(),
]);
const strWithNewId = JSON.stringify(runnable, null, 2);
expect(stringify(JSON.parse(strWithNewId))).toMatchSnapshot();
expect(JSON.parse(strWithNewId).id).toEqual([
"langchain_core",
"runnables",
"RunnableSequence",
]);
const strWithOldId = JSON.stringify({
...JSON.parse(strWithNewId),
id: ["langchain", "schema", "runnable", "RunnableSequence"],
});
const runnable2 = await load<RunnableSequence>(strWithOldId);
expect(runnable2).toBeInstanceOf(RunnableSequence);
const runnable3 = await load<RunnableSequence>(strWithNewId);
expect(runnable3).toBeInstanceOf(RunnableSequence);
});
test("serialize + deserialize llm chain chat prompt", async () => {
// eslint-disable-next-line no-process-env
process.env.OPENAI_API_KEY = undefined;
const llm = new ChatOpenAI({
temperature: 0.5,
modelName: "gpt-4",
streaming: true,
azureOpenAIApiKey: "openai-key",
azureOpenAIApiInstanceName: "openai-instance",
azureOpenAIApiDeploymentName: "openai-deployment",
azureOpenAIApiVersion: "openai-version",
prefixMessages: [
{
role: "system",
content: "You're a nice assistant",
},
],
});
const prompt = ChatPromptTemplate.fromMessages([
SystemMessagePromptTemplate.fromTemplate("You are talking to {name}."),
HumanMessagePromptTemplate.fromTemplate("Hello, nice model."),
]);
const chain = new LLMChain({ llm, prompt });
const str = JSON.stringify(chain, null, 2);
expect(stringify(JSON.parse(str))).toMatchSnapshot();
const chain2 = await load<LLMChain>(str, {
AZURE_OPENAI_API_KEY: "openai-key",
});
expect(chain2).toBeInstanceOf(LLMChain);
expect(JSON.stringify(chain2, null, 2)).toBe(str);
});
test("serialize + deserialize llm chain few shot prompt w/ examples", async () => {
const llm = new OpenAI({
temperature: 0.5,
modelName: "davinci",
openAIApiKey: "openai-key",
callbacks: [new ConsoleCallbackHandler()],
});
const prompt = new FewShotPromptTemplate({
examples: [{ yo: "1" }, { yo: "2" }],
prefix: "You are a nice assistant",
examplePrompt: PromptTemplate.fromTemplate("An example about {yo}"),
suffix: "My name is {name}",
inputVariables: ["yo", "name"],
});
const chain = new LLMChain({ llm, prompt });
const str = JSON.stringify(chain, null, 2);
expect(stringify(JSON.parse(str))).toMatchSnapshot();
await expect(
load<LLMChain>(str, {
OPENAI_API_KEY: "openai-key",
})
).rejects.toThrowError(
'Trying to load an object that doesn\'t implement serialization: $.kwargs.prompt -> {"lc":1,"type":"not_implemented","id":["langchain_core","prompts","few_shot","FewShotPromptTemplate"]}'
);
});
test("serialize + deserialize llm chain few shot prompt w/ selector", async () => {
const llm = new OpenAI({
temperature: 0.5,
modelName: "davinci",
openAIApiKey: "openai-key",
});
const examplePrompt = PromptTemplate.fromTemplate("An example about {yo}");
const prompt = new FewShotPromptTemplate({
exampleSelector: await LengthBasedExampleSelector.fromExamples(
[{ yo: "1" }, { yo: "2" }],
{ examplePrompt }
),
prefix: "You are a nice assistant",
examplePrompt,
suffix: "My name is {name}",
inputVariables: ["yo", "name"],
});
const chain = new LLMChain({ llm, prompt });
const str = JSON.stringify(chain, null, 2);
expect(stringify(JSON.parse(str))).toMatchSnapshot();
await expect(
load<LLMChain>(str, {
OPENAI_API_KEY: "openai-key",
})
).rejects.toThrow(
'Trying to load an object that doesn\'t implement serialization: $.kwargs.prompt -> {"lc":1,"type":"not_implemented","id":["langchain_core","prompts","few_shot","FewShotPromptTemplate"]}'
);
});
test("serialize + deserialize llmchain with list output parser", async () => {
const llm = new OpenAI({
temperature: 0.5,
modelName: "davinci",
openAIApiKey: "openai-key",
callbacks: [new ConsoleCallbackHandler()],
});
const prompt = PromptTemplate.fromTemplate(
"An example about {yo} {format_instructions}"
);
const outputParser = new CommaSeparatedListOutputParser();
const chain = new LLMChain({ llm, prompt, outputParser });
const str = JSON.stringify(chain, null, 2);
expect(stringify(JSON.parse(str))).toMatchSnapshot();
const chain2 = await load<LLMChain>(str, {
OPENAI_API_KEY: "openai-key",
});
expect(chain2).toBeInstanceOf(LLMChain);
expect(JSON.stringify(chain2, null, 2)).toBe(str);
expect(await chain2.outputParser?.parseResult([{ text: "a, b, c" }])).toEqual(
["a", "b", "c"]
);
});
test("serialize + deserialize llmchain with regex output parser", async () => {
const llm = new OpenAI({
temperature: 0.5,
modelName: "davinci",
openAIApiKey: "openai-key",
callbacks: [new ConsoleCallbackHandler()],
});
const prompt = PromptTemplate.fromTemplate(
"An example about {yo} {format_instructions}"
);
const outputParser = new RegexParser({
regex: /Confidence: (A|B|C), Explanation: (.*)/,
outputKeys: ["confidence", "explanation"],
});
const chain = new LLMChain({ llm, prompt, outputParser });
const str = JSON.stringify(chain, null, 2);
expect(stringify(JSON.parse(str))).toMatchSnapshot();
const chain2 = await load<LLMChain>(str, {
OPENAI_API_KEY: "openai-key",
});
expect(chain2).toBeInstanceOf(LLMChain);
expect(JSON.stringify(chain2, null, 2)).toBe(str);
expect(
await chain2.outputParser?.parseResult([
{
text: "Confidence: A, Explanation: Because it is the capital of France.",
},
])
).toEqual({
confidence: "A",
explanation: "Because it is the capital of France.",
});
});
test("serialize + deserialize llmchain with struct output parser throws", async () => {
const llm = new OpenAI({
temperature: 0.5,
modelName: "davinci",
openAIApiKey: "openai-key",
callbacks: [new ConsoleCallbackHandler({})],
});
const prompt = PromptTemplate.fromTemplate(
"An example about {yo} {format_instructions}"
);
const outputParser = new StructuredOutputParser(
z.object({
a: z.string(),
})
);
const chain = new LLMChain({ llm, prompt, outputParser });
const str = JSON.stringify(chain, null, 2);
expect(stringify(JSON.parse(str))).toMatchSnapshot();
await expect(
load<LLMChain>(str, {
OPENAI_API_KEY: "openai-key",
})
).rejects.toThrow(
'Trying to load an object that doesn\'t implement serialization: $.kwargs.output_parser -> {"lc":1,"type":"not_implemented","id":["langchain","output_parsers","structured","StructuredOutputParser"]}'
);
});
test.skip("serialize + deserialize agent", async () => {
const llm = new ChatOpenAI({
temperature: 0,
modelName: "gpt-4",
openAIApiKey: "openai-key",
});
const executor = await initializeAgentExecutorWithOptions(
[
new Calculator(),
new RequestsGetTool(),
new JsonListKeysTool(new JsonSpec({ a: "b" })),
],
llm,
{
agentType: "chat-conversational-react-description",
}
);
const str = JSON.stringify(executor, null, 2);
expect(stringify(JSON.parse(str))).toMatchSnapshot();
const executor2 = await load<AgentExecutor>(
str,
{ OPENAI_API_KEY: "openai-key" },
{
"langchain/tools/calculator": { Calculator },
}
);
expect(executor2).toBeInstanceOf(AgentExecutor);
expect(JSON.stringify(executor2, null, 2)).toBe(str);
});
test("override name of objects when serialising", async () => {
const llm = new OpenAI({ temperature: 0.5, apiKey: "openai-key" });
const str = JSON.stringify(llm, null, 2);
class MangledName extends OpenAI {}
const llm2 = await load<OpenAI>(
str,
{ OPENAI_API_KEY: "openai-key" },
{ "langchain/llms/openai": { OpenAI: MangledName } }
);
expect(JSON.stringify(llm2, null, 2)).toBe(str);
});
test("Should load traces even if the constructor name changes (minified environments)", async () => {
const llm = new OpenAI({ temperature: 0.5, apiKey: "openai-key" });
Object.defineProperty(llm.constructor, "name", {
value: "x",
});
const str = JSON.stringify(llm, null, 2);
// console.log(str);
const llm2 = await load<OpenAI>(
str,
{ COHERE_API_KEY: "cohere-key" },
{ "langchain/llms/openai": { OpenAI } }
);
// console.log(JSON.stringify(llm2, null, 2));
expect(JSON.stringify(llm2, null, 2)).toBe(str);
});
test("Should load a real-world serialized chain", async () => {
const serializedValue = `{"lc": 1, "type": "constructor", "id": ["langchain_core", "runnables", "RunnableSequence"], "kwargs": {"first": {"lc": 1, "type": "constructor", "id": ["langchain_core", "runnables", "RunnableParallel"], "kwargs": {"steps": {"equation_statement": {"lc": 1, "type": "constructor", "id": ["langchain_core", "runnables", "RunnablePassthrough"], "kwargs": {"func": null, "afunc": null, "input_type": null}}}}}, "middle": [{"lc": 1, "type": "constructor", "id": ["langchain_core", "prompts", "chat", "ChatPromptTemplate"], "kwargs": {"input_variables": ["equation_statement"], "messages": [{"lc": 1, "type": "constructor", "id": ["langchain_core", "prompts", "chat", "SystemMessagePromptTemplate"], "kwargs": {"prompt": {"lc": 1, "type": "constructor", "id": ["langchain_core", "prompts", "prompt", "PromptTemplate"], "kwargs": {"input_variables": [], "template": "Write out the following equation using algebraic symbols then solve it. Use the format\\n\\nEQUATION:...\\nSOLUTION:...\\n\\n", "template_format": "f-string", "partial_variables": {}}}}}, {"lc": 1, "type": "constructor", "id": ["langchain_core", "prompts", "chat", "HumanMessagePromptTemplate"], "kwargs": {"prompt": {"lc": 1, "type": "constructor", "id": ["langchain_core", "prompts", "prompt", "PromptTemplate"], "kwargs": {"input_variables": ["equation_statement"], "template": "{equation_statement}", "template_format": "f-string", "partial_variables": {}}}}}]}}, {"lc": 1, "type": "constructor", "id": ["langchain", "chat_models", "openai", "ChatOpenAI"], "kwargs": {"temperature": 0.0, "openai_api_key": {"lc": 1, "type": "secret", "id": ["OPENAI_API_KEY"]}}}], "last": {"lc": 1, "type": "constructor", "id": ["langchain_core", "output_parsers", "string", "StrOutputParser"], "kwargs": {}}}}`;
const chain = await load<RunnableSequence>(serializedValue, {
OPENAI_API_KEY: "openai-key",
});
// @ts-expect-error testing
expect(chain.first.constructor.lc_name()).toBe("RunnableMap");
// @ts-expect-error testing
expect(chain.middle.length).toBe(2);
// @ts-expect-error testing
expect(chain.middle[0].constructor.lc_name()).toBe(`ChatPromptTemplate`);
// @ts-expect-error testing
expect(chain.middle[1].constructor.lc_name()).toBe(`ChatOpenAI`);
// @ts-expect-error testing
expect(chain.last.constructor.lc_name()).toBe(`StrOutputParser`);
});
|
0 | lc_public_repos/langchainjs/langchain/src/load | lc_public_repos/langchainjs/langchain/src/load/tests/load.int.test.ts | import { test, expect } from "@jest/globals";
import { RunnableSequence } from "@langchain/core/runnables";
import { load } from "../index.js";
test("Should load and invoke real-world serialized chain", async () => {
const serializedValue = `{"lc": 1, "type": "constructor", "id": ["langchain_core", "runnables", "RunnableSequence"], "kwargs": {"first": {"lc": 1, "type": "constructor", "id": ["langchain_core", "runnables", "RunnableParallel"], "kwargs": {"steps": {"equation_statement": {"lc": 1, "type": "constructor", "id": ["langchain_core", "runnables", "RunnablePassthrough"], "kwargs": {"func": null, "afunc": null, "input_type": null}}}}}, "middle": [{"lc": 1, "type": "constructor", "id": ["langchain_core", "prompts", "chat", "ChatPromptTemplate"], "kwargs": {"input_variables": ["equation_statement"], "messages": [{"lc": 1, "type": "constructor", "id": ["langchain_core", "prompts", "chat", "SystemMessagePromptTemplate"], "kwargs": {"prompt": {"lc": 1, "type": "constructor", "id": ["langchain_core", "prompts", "prompt", "PromptTemplate"], "kwargs": {"input_variables": [], "template": "Write out the following equation using algebraic symbols then solve it. Use the format\\n\\nEQUATION:...\\nSOLUTION:...\\n\\n", "template_format": "f-string", "partial_variables": {}}}}}, {"lc": 1, "type": "constructor", "id": ["langchain_core", "prompts", "chat", "HumanMessagePromptTemplate"], "kwargs": {"prompt": {"lc": 1, "type": "constructor", "id": ["langchain_core", "prompts", "prompt", "PromptTemplate"], "kwargs": {"input_variables": ["equation_statement"], "template": "{equation_statement}", "template_format": "f-string", "partial_variables": {}}}}}]}}, {"lc": 1, "type": "constructor", "id": ["langchain", "chat_models", "openai", "ChatOpenAI"], "kwargs": {"temperature": 0.0, "openai_api_key": {"lc": 1, "type": "secret", "id": ["OPENAI_API_KEY"]}}}], "last": {"lc": 1, "type": "constructor", "id": ["langchain_core", "output_parsers", "string", "StrOutputParser"], "kwargs": {}}}}`;
const chain = await load<RunnableSequence>(serializedValue);
const result = await chain.invoke(
"x raised to the third plus seven equals 12"
);
// console.log(result);
expect(typeof result).toBe("string");
});
|
0 | lc_public_repos/langchainjs/langchain/src/load | lc_public_repos/langchainjs/langchain/src/load/tests/cross_language.test.ts | import { test } from "@jest/globals";
import { fileURLToPath } from "node:url";
import { readFileSync } from "node:fs";
import * as path from "node:path";
import { load } from "../index.js";
const IMPORTANT_IMPORTS = JSON.parse(
readFileSync(
path.join(
path.dirname(fileURLToPath(import.meta.url)),
"data",
"important_imports.json"
)
).toString()
);
const CURRENT_KNOWN_FAILURES = [
"langchain/schema/agent/AgentAction",
"langchain/schema/agent/AgentFinish",
"langchain/schema/prompt_template/BasePromptTemplate",
"langchain/schema/agent/AgentActionMessageLog",
"langchain/schema/agent/OpenAIToolAgentAction",
"langchain/prompts/chat/BaseMessagePromptTemplate",
"langchain/schema/output/ChatGeneration",
"langchain/schema/output/Generation",
"langchain/schema/document/Document",
"langchain/schema/runnable/DynamicRunnable",
"langchain/schema/prompt/PromptValue",
"langchain/llms/openai/BaseOpenAI",
"langchain/llms/openai/AzureOpenAI",
"langchain/llms/vertexai/VertexAI",
"langchain/llms/google_palm/GooglePalm",
"langchain/chat_models/azure_openai/AzureChatOpenAI",
"langchain/chat_models/google_palm/ChatGooglePalm",
"langchain/chat_models/vertexai/ChatVertexAI",
"langchain/schema/prompt_template/BaseChatPromptTemplate",
"langchain/prompts/few_shot_with_templates/FewShotPromptWithTemplates",
"langchain/prompts/base/StringPromptTemplate",
"langchain/prompts/chat/BaseStringMessagePromptTemplate",
"langchain/prompts/chat/ChatPromptValue",
"langchain/prompts/chat/ChatPromptValueConcrete",
"langchain/schema/runnable/HubRunnable",
"langchain/schema/runnable/RunnableBindingBase",
"langchain/schema/runnable/OpenAIFunctionsRouter",
"langchain/schema/runnable/RunnableEachBase",
"langchain/schema/runnable/RunnableConfigurableAlternatives",
"langchain/schema/runnable/RunnableConfigurableFields",
"langchain_core/agents/AgentAction",
"langchain_core/agents/AgentFinish",
"langchain_core/agents/AgentActionMessageLog",
"langchain/agents/output_parsers/openai_tools/OpenAIToolAgentAction",
"langchain_core/outputs/chat_generation/ChatGeneration",
"langchain_core/outputs/generation/Generation",
"langchain_core/runnables/configurable/DynamicRunnable",
"langchain_core/prompt_values/PromptValue",
"langchain/llms/openai/BaseOpenAI",
"langchain/llms/openai/AzureOpenAI",
"langchain_core/prompts/few_shot_with_templates/FewShotPromptWithTemplates",
"langchain_core/prompts/string/StringPromptTemplate",
"langchain_core/prompts/chat/BaseStringMessagePromptTemplate",
"langchain_core/prompt_values/ChatPromptValueConcrete",
"langchain/runnables/hub/HubRunnable",
"langchain_core/runnables/base/RunnableBindingBase",
"langchain/runnables/openai_functions/OpenAIFunctionsRouter",
"langchain_core/runnables/base/RunnableEachBase",
"langchain_core/runnables/configurable/RunnableConfigurableAlternatives",
"langchain_core/runnables/configurable/RunnableConfigurableFields",
];
const CROSS_LANGUAGE_ENTRYPOINTS = Object.keys(IMPORTANT_IMPORTS)
.concat(Object.values(IMPORTANT_IMPORTS))
.filter((v) => !CURRENT_KNOWN_FAILURES.includes(v));
describe("Test cross language serialization of important modules", () => {
// https://github.com/langchain-ai/langchain/blob/master/libs/core/langchain_core/load/mapping.py
test.each(CROSS_LANGUAGE_ENTRYPOINTS)(
"Test matching serialization names for: %s",
async (item) => {
const idComponents = item.split("/");
const mockItem = {
lc: 1,
type: "constructor",
id: idComponents,
kwargs: {},
};
try {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const result = (await load(JSON.stringify(mockItem))) as any;
expect(result.constructor.name).toEqual(
idComponents[idComponents.length - 1]
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
} catch (e: any) {
expect(e.message).not.toContain("Invalid identifer: $");
expect(e.message).not.toContain("Invalid namespace: $");
}
}
);
});
|
0 | lc_public_repos/langchainjs/langchain/src/load/tests | lc_public_repos/langchainjs/langchain/src/load/tests/__snapshots__/load.test.ts.snap | // Jest Snapshot v1, https://goo.gl/fbAQLP
exports[`serialize + deserialize custom classes 1`] = `
"lc: 1
type: constructor
id:
- langchain
- tests
- Person
kwargs:
a_field: hello
api_key:
lc: 1
type: secret
id:
- PERSON_API_KEY
hello: 3
"
`;
exports[`serialize + deserialize custom classes 2`] = `
"lc: 1
type: constructor
id:
- langchain
- tests
- SpecialPerson
kwargs:
a_field: hello
api_key:
lc: 1
type: secret
id:
- PERSON_API_KEY
another_api_key:
lc: 1
type: secret
id:
- SPECIAL_PERSON_API_KEY
by: 4
hello: 3
inherited:
lc: 1
type: secret
id:
- SPECIAL_PERSON_INHERITED_API_KEY
nested:
api:
key:
lc: 1
type: secret
id:
- SPECIAL_PERSON_NESTED_API_KEY
"
`;
exports[`serialize + deserialize llm 1`] = `
"lc: 1
type: constructor
id:
- langchain
- llms
- openai
- OpenAI
kwargs:
temperature: 0.7
model: davinci
openai_api_key:
lc: 1
type: secret
id:
- OPENAI_API_KEY
"
`;
exports[`serialize + deserialize llm chain chat prompt 1`] = `
"lc: 1
type: constructor
id:
- langchain
- chains
- llm
- LLMChain
kwargs:
llm:
lc: 1
type: constructor
id:
- langchain
- chat_models
- openai
- ChatOpenAI
kwargs:
temperature: 0.5
model: gpt-4
streaming: true
azure_openai_api_key:
lc: 1
type: secret
id:
- AZURE_OPENAI_API_KEY
azure_openai_api_instance_name: openai-instance
azure_openai_api_deployment_name: openai-deployment
azure_openai_api_version: openai-version
prefix_messages:
- role: system
content: You're a nice assistant
openai_api_key:
lc: 1
type: secret
id:
- OPENAI_API_KEY
prompt:
lc: 1
type: constructor
id:
- langchain_core
- prompts
- chat
- ChatPromptTemplate
kwargs:
input_variables:
- name
messages:
- lc: 1
type: constructor
id:
- langchain_core
- prompts
- chat
- SystemMessagePromptTemplate
kwargs:
prompt:
lc: 1
type: constructor
id:
- langchain_core
- prompts
- prompt
- PromptTemplate
kwargs:
input_variables:
- name
template_format: f-string
template: You are talking to {name}.
- lc: 1
type: constructor
id:
- langchain_core
- prompts
- chat
- HumanMessagePromptTemplate
kwargs:
prompt:
lc: 1
type: constructor
id:
- langchain_core
- prompts
- prompt
- PromptTemplate
kwargs:
input_variables: []
template_format: f-string
template: Hello, nice model.
"
`;
exports[`serialize + deserialize llm chain few shot prompt w/ examples 1`] = `
"lc: 1
type: constructor
id:
- langchain
- chains
- llm
- LLMChain
kwargs:
llm:
lc: 1
type: constructor
id:
- langchain
- llms
- openai
- OpenAI
kwargs:
temperature: 0.5
model: davinci
openai_api_key:
lc: 1
type: secret
id:
- OPENAI_API_KEY
prompt:
lc: 1
type: not_implemented
id:
- langchain_core
- prompts
- few_shot
- FewShotPromptTemplate
"
`;
exports[`serialize + deserialize llm chain few shot prompt w/ selector 1`] = `
"lc: 1
type: constructor
id:
- langchain
- chains
- llm
- LLMChain
kwargs:
llm:
lc: 1
type: constructor
id:
- langchain
- llms
- openai
- OpenAI
kwargs:
temperature: 0.5
model: davinci
openai_api_key:
lc: 1
type: secret
id:
- OPENAI_API_KEY
prompt:
lc: 1
type: not_implemented
id:
- langchain_core
- prompts
- few_shot
- FewShotPromptTemplate
"
`;
exports[`serialize + deserialize llm chain string prompt 1`] = `
"lc: 1
type: constructor
id:
- langchain
- chains
- llm
- LLMChain
kwargs:
llm:
lc: 1
type: constructor
id:
- langchain
- llms
- openai
- OpenAI
kwargs:
temperature: 0.5
model: davinci
openai_api_key:
lc: 1
type: secret
id:
- OPENAI_API_KEY
prompt:
lc: 1
type: constructor
id:
- langchain_core
- prompts
- prompt
- PromptTemplate
kwargs:
input_variables:
- name
template_format: f-string
template: Hello, {name}!
"
`;
exports[`serialize + deserialize llmchain with list output parser 1`] = `
"lc: 1
type: constructor
id:
- langchain
- chains
- llm
- LLMChain
kwargs:
llm:
lc: 1
type: constructor
id:
- langchain
- llms
- openai
- OpenAI
kwargs:
temperature: 0.5
model: davinci
openai_api_key:
lc: 1
type: secret
id:
- OPENAI_API_KEY
prompt:
lc: 1
type: constructor
id:
- langchain_core
- prompts
- prompt
- PromptTemplate
kwargs:
input_variables:
- yo
- format_instructions
template_format: f-string
template: An example about {yo} {format_instructions}
output_parser:
lc: 1
type: constructor
id:
- langchain_core
- output_parsers
- list
- CommaSeparatedListOutputParser
kwargs: {}
"
`;
exports[`serialize + deserialize llmchain with regex output parser 1`] = `
"lc: 1
type: constructor
id:
- langchain
- chains
- llm
- LLMChain
kwargs:
llm:
lc: 1
type: constructor
id:
- langchain
- llms
- openai
- OpenAI
kwargs:
temperature: 0.5
model: davinci
openai_api_key:
lc: 1
type: secret
id:
- OPENAI_API_KEY
prompt:
lc: 1
type: constructor
id:
- langchain_core
- prompts
- prompt
- PromptTemplate
kwargs:
input_variables:
- yo
- format_instructions
template_format: f-string
template: An example about {yo} {format_instructions}
output_parser:
lc: 1
type: constructor
id:
- langchain
- output_parsers
- regex
- RegexParser
kwargs:
regex:
pattern: "Confidence: (A|B|C), Explanation: (.*)"
flags: ""
output_keys:
- confidence
- explanation
"
`;
exports[`serialize + deserialize llmchain with struct output parser throws 1`] = `
"lc: 1
type: constructor
id:
- langchain
- chains
- llm
- LLMChain
kwargs:
llm:
lc: 1
type: constructor
id:
- langchain
- llms
- openai
- OpenAI
kwargs:
temperature: 0.5
model: davinci
openai_api_key:
lc: 1
type: secret
id:
- OPENAI_API_KEY
prompt:
lc: 1
type: constructor
id:
- langchain_core
- prompts
- prompt
- PromptTemplate
kwargs:
input_variables:
- yo
- format_instructions
template_format: f-string
template: An example about {yo} {format_instructions}
output_parser:
lc: 1
type: not_implemented
id:
- langchain
- output_parsers
- structured
- StructuredOutputParser
"
`;
exports[`serialize + deserialize runnable sequence with new and old ids 1`] = `
"lc: 1
type: constructor
id:
- langchain_core
- runnables
- RunnableSequence
kwargs:
first:
lc: 1
type: constructor
id:
- langchain_core
- prompts
- chat
- ChatPromptTemplate
kwargs:
input_variables: []
messages:
- lc: 1
type: constructor
id:
- langchain_core
- prompts
- chat
- HumanMessagePromptTemplate
kwargs:
prompt:
lc: 1
type: constructor
id:
- langchain_core
- prompts
- prompt
- PromptTemplate
kwargs:
input_variables: []
template_format: f-string
template: hi there
middle: []
last:
lc: 1
type: constructor
id:
- langchain
- chat_models
- openai
- ChatOpenAI
kwargs:
openai_api_key:
lc: 1
type: secret
id:
- OPENAI_API_KEY
"
`;
exports[`serialize + deserialize with new and old ids 1`] = `
"lc: 1
type: constructor
id:
- langchain_core
- prompts
- prompt
- PromptTemplate
kwargs:
input_variables:
- name
template_format: f-string
template: Hello, {name}!
"
`;
|
0 | lc_public_repos/langchainjs/langchain/src/load/tests | lc_public_repos/langchainjs/langchain/src/load/tests/data/important_imports.json | {
"langchain/schema/messages/AIMessage": "langchain_core/messages/ai/AIMessage",
"langchain/schema/messages/AIMessageChunk": "langchain_core/messages/ai/AIMessageChunk",
"langchain/schema/messages/BaseMessage": "langchain_core/messages/base/BaseMessage",
"langchain/schema/messages/BaseMessageChunk": "langchain_core/messages/base/BaseMessageChunk",
"langchain/schema/messages/ChatMessage": "langchain_core/messages/chat/ChatMessage",
"langchain/schema/messages/FunctionMessage": "langchain_core/messages/function/FunctionMessage",
"langchain/schema/messages/HumanMessage": "langchain_core/messages/human/HumanMessage",
"langchain/schema/messages/SystemMessage": "langchain_core/messages/system/SystemMessage",
"langchain/schema/messages/ToolMessage": "langchain_core/messages/tool/ToolMessage",
"langchain/schema/AIMessage": "langchain_core/messages/ai/AIMessage",
"langchain/schema/AIMessageChunk": "langchain_core/messages/ai/AIMessageChunk",
"langchain/schema/BaseMessage": "langchain_core/messages/base/BaseMessage",
"langchain/schema/BaseMessageChunk": "langchain_core/messages/base/BaseMessageChunk",
"langchain/schema/ChatMessage": "langchain_core/messages/chat/ChatMessage",
"langchain/schema/FunctionMessage": "langchain_core/messages/function/FunctionMessage",
"langchain/schema/HumanMessage": "langchain_core/messages/human/HumanMessage",
"langchain/schema/SystemMessage": "langchain_core/messages/system/SystemMessage",
"langchain/schema/ToolMessage": "langchain_core/messages/tool/ToolMessage",
"langchain/schema/ChatMessageChunk": "langchain_core/messages/chat/ChatMessageChunk",
"langchain/schema/HumanMessageChunk": "langchain_core/messages/human/HumanMessageChunk",
"langchain/schema/FunctionMessageChunk": "langchain_core/messages/function/FunctionMessageChunk",
"langchain/schema/SystemMessageChunk": "langchain_core/messages/system/SystemMessageChunk",
"langchain/schema/ToolMessageChunk": "langchain_core/messages/tool/ToolMessageChunk",
"langchain/schema/agent/AgentAction": "langchain_core/agents/AgentAction",
"langchain/schema/agent/AgentFinish": "langchain_core/agents/AgentFinish",
"langchain/schema/prompt_template/BasePromptTemplate": "langchain_core/prompts/base/BasePromptTemplate",
"langchain/prompts/prompt/PromptTemplate": "langchain_core/prompts/prompt/PromptTemplate",
"langchain/prompts/chat/MessagesPlaceholder": "langchain_core/prompts/chat/MessagesPlaceholder",
"langchain/prompts/chat/ChatPromptTemplate": "langchain_core/prompts/chat/ChatPromptTemplate",
"langchain/prompts/chat/HumanMessagePromptTemplate": "langchain_core/prompts/chat/HumanMessagePromptTemplate",
"langchain/prompts/chat/SystemMessagePromptTemplate": "langchain_core/prompts/chat/SystemMessagePromptTemplate",
"langchain/prompts/image/ImagePromptTemplate": "langchain_core/prompts/image/ImagePromptTemplate",
"langchain/schema/agent/AgentActionMessageLog": "langchain_core/agents/AgentActionMessageLog",
"langchain/prompts/chat/BaseMessagePromptTemplate": "langchain_core/prompts/chat/BaseMessagePromptTemplate",
"langchain/schema/output/ChatGeneration": "langchain_core/outputs/chat_generation/ChatGeneration",
"langchain/schema/output/Generation": "langchain_core/outputs/generation/Generation",
"langchain/schema/document/Document": "langchain_core/documents/base/Document",
"langchain/prompts/chat/AIMessagePromptTemplate": "langchain_core/prompts/chat/AIMessagePromptTemplate",
"langchain/schema/runnable/DynamicRunnable": "langchain_core/runnables/configurable/DynamicRunnable",
"langchain/schema/prompt/PromptValue": "langchain_core/prompt_values/PromptValue",
"langchain/schema/runnable/RunnableBinding": "langchain_core/runnables/base/RunnableBinding",
"langchain/schema/runnable/RunnableBranch": "langchain_core/runnables/branch/RunnableBranch",
"langchain/schema/runnable/RunnableWithFallbacks": "langchain_core/runnables/fallbacks/RunnableWithFallbacks",
"langchain/schema/output_parser/StrOutputParser": "langchain_core/output_parsers/string/StrOutputParser",
"langchain/output_parsers/list/CommaSeparatedListOutputParser": "langchain_core/output_parsers/list/CommaSeparatedListOutputParser",
"langchain/schema/runnable/RunnableParallel": "langchain_core/runnables/base/RunnableParallel",
"langchain/schema/output/ChatGenerationChunk": "langchain_core/outputs/chat_generation/ChatGenerationChunk",
"langchain/schema/messages/ChatMessageChunk": "langchain_core/messages/chat/ChatMessageChunk",
"langchain/schema/messages/HumanMessageChunk": "langchain_core/messages/human/HumanMessageChunk",
"langchain/schema/messages/FunctionMessageChunk": "langchain_core/messages/function/FunctionMessageChunk",
"langchain/schema/messages/SystemMessageChunk": "langchain_core/messages/system/SystemMessageChunk",
"langchain/schema/messages/ToolMessageChunk": "langchain_core/messages/tool/ToolMessageChunk",
"langchain/schema/output/GenerationChunk": "langchain_core/outputs/generation/GenerationChunk",
"langchain/schema/prompt_template/BaseChatPromptTemplate": "langchain_core/prompts/chat/BaseChatPromptTemplate",
"langchain/prompts/chat/ChatMessagePromptTemplate": "langchain_core/prompts/chat/ChatMessagePromptTemplate",
"langchain/prompts/few_shot_with_templates/FewShotPromptWithTemplates": "langchain_core/prompts/few_shot_with_templates/FewShotPromptWithTemplates",
"langchain/prompts/pipeline/PipelinePromptTemplate": "langchain_core/prompts/pipeline/PipelinePromptTemplate",
"langchain/prompts/base/StringPromptTemplate": "langchain_core/prompts/string/StringPromptTemplate",
"langchain/prompts/base/StringPromptValue": "langchain_core/prompt_values/StringPromptValue",
"langchain/prompts/chat/BaseStringMessagePromptTemplate": "langchain_core/prompts/chat/BaseStringMessagePromptTemplate",
"langchain/prompts/chat/ChatPromptValue": "langchain_core/prompt_values/ChatPromptValue",
"langchain/prompts/chat/ChatPromptValueConcrete": "langchain_core/prompt_values/ChatPromptValueConcrete",
"langchain/schema/runnable/RunnableBindingBase": "langchain_core/runnables/base/RunnableBindingBase",
"langchain/schema/runnable/RouterRunnable": "langchain_core/runnables/router/RouterRunnable",
"langchain/schema/runnable/RunnablePassthrough": "langchain_core/runnables/passthrough/RunnablePassthrough",
"langchain/schema/runnable/RunnableSequence": "langchain_core/runnables/base/RunnableSequence",
"langchain/schema/runnable/RunnableEach": "langchain_core/runnables/base/RunnableEach",
"langchain/schema/runnable/RunnableEachBase": "langchain_core/runnables/base/RunnableEachBase",
"langchain/schema/runnable/RunnableConfigurableAlternatives": "langchain_core/runnables/configurable/RunnableConfigurableAlternatives",
"langchain/schema/runnable/RunnableConfigurableFields": "langchain_core/runnables/configurable/RunnableConfigurableFields",
"langchain/schema/runnable/RunnableWithMessageHistory": "langchain_core/runnables/history/RunnableWithMessageHistory",
"langchain/schema/runnable/RunnableAssign": "langchain_core/runnables/base/RunnableAssign",
"langchain/schema/runnable/RunnablePick": "langchain_core/runnables/base/RunnablePick",
"langchain/schema/runnable/RunnableRetry": "langchain_core/runnables/retry/RunnableRetry"
}
|
0 | lc_public_repos/langchainjs/langchain/src/stores | lc_public_repos/langchainjs/langchain/src/stores/doc/in_memory.ts | import { Document } from "@langchain/core/documents";
import { BaseStoreInterface } from "@langchain/core/stores";
import { Docstore } from "./base.js";
/**
* Class for storing and retrieving documents in memory asynchronously.
* Extends the Docstore class.
*/
export class InMemoryDocstore
extends Docstore
implements BaseStoreInterface<string, Document>
{
_docs: Map<string, Document>;
constructor(docs?: Map<string, Document>) {
super();
this._docs = docs ?? new Map();
}
/**
* Searches for a document in the store based on its ID.
* @param search The ID of the document to search for.
* @returns The document with the given ID.
*/
async search(search: string): Promise<Document> {
const result = this._docs.get(search);
if (!result) {
throw new Error(`ID ${search} not found.`);
} else {
return result;
}
}
/**
* Adds new documents to the store.
* @param texts An object where the keys are document IDs and the values are the documents themselves.
* @returns Void
*/
async add(texts: Record<string, Document>): Promise<void> {
const keys = [...this._docs.keys()];
const overlapping = Object.keys(texts).filter((x) => keys.includes(x));
if (overlapping.length > 0) {
throw new Error(`Tried to add ids that already exist: ${overlapping}`);
}
for (const [key, value] of Object.entries(texts)) {
this._docs.set(key, value);
}
}
async mget(keys: string[]): Promise<Document[]> {
return Promise.all(keys.map((key) => this.search(key)));
}
async mset(keyValuePairs: [string, Document][]): Promise<void> {
await Promise.all(
keyValuePairs.map(([key, value]) => this.add({ [key]: value }))
);
}
async mdelete(_keys: string[]): Promise<void> {
throw new Error("Not implemented.");
}
// eslint-disable-next-line require-yield
async *yieldKeys(_prefix?: string): AsyncGenerator<string> {
throw new Error("Not implemented");
}
}
/**
* Class for storing and retrieving documents in memory synchronously.
*/
export class SynchronousInMemoryDocstore {
_docs: Map<string, Document>;
constructor(docs?: Map<string, Document>) {
this._docs = docs ?? new Map();
}
/**
* Searches for a document in the store based on its ID.
* @param search The ID of the document to search for.
* @returns The document with the given ID.
*/
search(search: string): Document {
const result = this._docs.get(search);
if (!result) {
throw new Error(`ID ${search} not found.`);
} else {
return result;
}
}
/**
* Adds new documents to the store.
* @param texts An object where the keys are document IDs and the values are the documents themselves.
* @returns Void
*/
add(texts: Record<string, Document>): void {
const keys = [...this._docs.keys()];
const overlapping = Object.keys(texts).filter((x) => keys.includes(x));
if (overlapping.length > 0) {
throw new Error(`Tried to add ids that already exist: ${overlapping}`);
}
for (const [key, value] of Object.entries(texts)) {
this._docs.set(key, value);
}
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/stores | lc_public_repos/langchainjs/langchain/src/stores/doc/base.ts | import { Document } from "@langchain/core/documents";
/**
* Abstract class for a document store. All document stores should extend
* this class.
*/
export abstract class Docstore {
abstract search(search: string): Promise<Document>;
abstract add(texts: Record<string, Document>): Promise<void>;
}
|
0 | lc_public_repos/langchainjs/langchain/src/stores | lc_public_repos/langchainjs/langchain/src/stores/file/in_memory.ts | import { BaseFileStore } from "./base.js";
/**
* Class that provides an in-memory file storage system. It extends the
* BaseFileStore class and implements its readFile and writeFile methods.
* This class is typically used in scenarios where temporary, in-memory
* file storage is needed, such as during testing or for caching files in
* memory for quick access.
*/
export class InMemoryFileStore extends BaseFileStore {
lc_namespace = ["langchain", "stores", "file", "in_memory"];
private files: Map<string, string> = new Map();
/**
* Retrieves the contents of a file given its path. If the file does not
* exist, it throws an error.
* @param path The path of the file to read.
* @returns The contents of the file as a string.
*/
async readFile(path: string): Promise<string> {
const contents = this.files.get(path);
if (contents === undefined) {
throw new Error(`File not found: ${path}`);
}
return contents;
}
/**
* Writes contents to a file at a given path. If the file already exists,
* it overwrites the existing contents.
* @param path The path of the file to write.
* @param contents The contents to write to the file.
* @returns Void
*/
async writeFile(path: string, contents: string): Promise<void> {
this.files.set(path, contents);
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/stores | lc_public_repos/langchainjs/langchain/src/stores/file/base.ts | import { Serializable } from "@langchain/core/load/serializable";
/**
* Base class for all file stores. All file stores should extend this
* class.
*/
export abstract class BaseFileStore extends Serializable {
abstract readFile(path: string): Promise<string>;
abstract writeFile(path: string, contents: string): Promise<void>;
}
|
0 | lc_public_repos/langchainjs/langchain/src/stores | lc_public_repos/langchainjs/langchain/src/stores/file/node.ts | import * as fs from "node:fs/promises";
import { mkdtempSync } from "node:fs";
import { join } from "node:path";
import { BaseFileStore } from "./base.js";
/**
* Specific implementation of the `BaseFileStore` class for Node.js.
* Provides methods to read and write files in a specific base path.
*/
export class NodeFileStore extends BaseFileStore {
lc_namespace = ["langchain", "stores", "file", "node"];
constructor(public basePath: string = mkdtempSync("langchain-")) {
super();
}
/**
* Reads the contents of a file at the given path.
* @param path Path of the file to read.
* @returns The contents of the file as a string.
*/
async readFile(path: string): Promise<string> {
return await fs.readFile(join(this.basePath, path), "utf8");
}
/**
* Writes the given contents to a file at the specified path.
* @param path Path of the file to write to.
* @param contents Contents to write to the file.
* @returns Promise that resolves when the file has been written.
*/
async writeFile(path: string, contents: string): Promise<void> {
await fs.writeFile(join(this.basePath, path), contents, "utf8");
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/stores | lc_public_repos/langchainjs/langchain/src/stores/message/in_memory.ts | export { InMemoryChatMessageHistory as ChatMessageHistory } from "@langchain/core/chat_history";
|
0 | lc_public_repos/langchainjs/langchain/src/stores | lc_public_repos/langchainjs/langchain/src/stores/message/utils.ts | export {
mapStoredMessagesToChatMessages,
mapChatMessagesToStoredMessages,
} from "@langchain/core/messages";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/schema/prompt_template.ts | import { Document } from "@langchain/core/documents";
import { BasePromptTemplate } from "@langchain/core/prompts";
/**
* @deprecated
* Formats a document using a given prompt template.
*
* @async
* @param {Document} document - The document to format.
* @param {BasePromptTemplate} prompt - The prompt template to use for formatting.
* @returns {Promise<string>} A Promise that resolves to the formatted document as a string.
* @throws {Error} If the document is missing required metadata variables specified in the prompt template.
*/
export const formatDocument = async (
document: Document,
prompt: BasePromptTemplate
): Promise<string> => {
const baseInfo = {
pageContent: document.pageContent,
...document.metadata,
};
const variables = new Set(prompt.inputVariables);
const requiredMetadata = new Set(
prompt.inputVariables
.map((v) => (v !== "pageContent" ? v : null))
.filter((v) => v !== null)
);
const missingMetadata = [];
for (const variable of variables) {
if (!(variable in baseInfo) && variable !== "pageContent") {
missingMetadata.push(variable);
}
}
if (missingMetadata.length) {
throw new Error(
`Document prompt requires documents to have metadata variables: ${JSON.stringify(
requiredMetadata
)}. Received document with missing metadata: ${JSON.stringify(
missingMetadata
)}`
);
}
return prompt.format(baseInfo);
};
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/schema/query_constructor.ts | /**
* A simple data structure that holds information about an attribute. It
* is typically used to provide metadata about attributes in other classes
* or data structures within the LangChain framework.
* @deprecated
*/
export class AttributeInfo {
constructor(
public name: string,
public type: string,
public description: string
) {}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/prompts/chat.ts | export {
BaseMessagePromptTemplate,
type MessagesPlaceholderFields as MessagePlaceholderFields,
MessagesPlaceholder,
type MessageStringPromptTemplateFields,
BaseMessageStringPromptTemplate,
BaseChatPromptTemplate,
type ChatMessagePromptTemplateFields,
ChatMessagePromptTemplate,
HumanMessagePromptTemplate,
AIMessagePromptTemplate,
SystemMessagePromptTemplate,
type ChatPromptTemplateInput,
type BaseMessagePromptTemplateLike,
ChatPromptTemplate,
} from "@langchain/core/prompts";
export {
type ChatPromptValueFields,
ChatPromptValue,
} from "@langchain/core/prompt_values";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/prompts/template.ts | export {
type TemplateFormat,
parseFString,
interpolateFString,
DEFAULT_FORMATTER_MAPPING,
DEFAULT_PARSER_MAPPING,
renderTemplate,
parseTemplate,
checkValidTemplate,
} from "@langchain/core/prompts";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/prompts/serde.ts | export {
type SerializedPromptTemplate,
type SerializedFewShotTemplate,
type SerializedBasePromptTemplate,
} from "@langchain/core/prompts";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/prompts/index.ts | /* #__PURE__ */ console.warn(
[
`[ERROR]: The "langchain/prompts" entrypoint was removed in LangChain version 0.2.0.`,
``,
`Instead, please import from "@langchain/core/prompts".`,
].join("\n")
);
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/prompts/few_shot.ts | export {
type FewShotPromptTemplateInput,
FewShotPromptTemplate,
type FewShotChatMessagePromptTemplateInput,
FewShotChatMessagePromptTemplate,
} from "@langchain/core/prompts";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/prompts/base.ts | export {
type TypedPromptInputValues,
BaseStringPromptTemplate,
type BasePromptTemplateInput,
BasePromptTemplate,
} from "@langchain/core/prompts";
export { StringPromptValue } from "@langchain/core/prompt_values";
export { BaseExampleSelector } from "@langchain/core/example_selectors";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/prompts/pipeline.ts | export {
type PipelinePromptParams,
type PipelinePromptTemplateInput,
PipelinePromptTemplate,
} from "@langchain/core/prompts";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/prompts/prompt.ts | export {
type PromptTemplateInput,
type ParamsFromFString,
PromptTemplate,
} from "@langchain/core/prompts";
|
0 | lc_public_repos/langchainjs/langchain/src/prompts | lc_public_repos/langchainjs/langchain/src/prompts/tests/selectors.test.ts | import { expect, test } from "@jest/globals";
import {
LengthBasedExampleSelector,
SemanticSimilarityExampleSelector,
} from "@langchain/core/example_selectors";
import { PromptTemplate } from "@langchain/core/prompts";
import { FakeEmbeddings } from "@langchain/core/utils/testing";
import { MemoryVectorStore } from "../../vectorstores/memory.js";
test("Test using LengthBasedExampleSelector", async () => {
const prompt = new PromptTemplate({
template: "{foo} {bar}",
inputVariables: ["foo"],
partialVariables: { bar: "baz" },
});
const selector = await LengthBasedExampleSelector.fromExamples(
[{ foo: "one one one" }],
{
examplePrompt: prompt,
maxLength: 10,
}
);
await selector.addExample({ foo: "one two three" });
await selector.addExample({ foo: "four five six" });
await selector.addExample({ foo: "seven eight nine" });
await selector.addExample({ foo: "ten eleven twelve" });
const chosen = await selector.selectExamples({ foo: "hello", bar: "world" });
expect(chosen).toStrictEqual([
{ foo: "one one one" },
{ foo: "one two three" },
]);
});
test("Test using SemanticSimilarityExampleSelector", async () => {
const vectorStore = await MemoryVectorStore.fromTexts(
["Hello world", "Bye bye", "hello nice world", "bye", "hi"],
[{ id: 2 }, { id: 1 }, { id: 3 }, { id: 4 }, { id: 5 }],
new FakeEmbeddings() // not using OpenAIEmbeddings() because would be extra dependency
);
const selector = new SemanticSimilarityExampleSelector({
vectorStore,
});
const chosen = await selector.selectExamples({ id: 1 });
expect(chosen).toEqual([{ id: 2 }, { id: 1 }, { id: 3 }, { id: 4 }]);
});
test("Test using SemanticSimilarityExampleSelector with metadata filtering", async () => {
const vectorStore = await MemoryVectorStore.fromTexts(
["Hello world", "Bye bye", "hello nice world", "bye", "hi"],
[{ id: 2 }, { id: 1 }, { id: 3 }, { id: 4 }, { id: 5 }],
new FakeEmbeddings() // not using OpenAIEmbeddings() because would be extra dependency
);
const selector = new SemanticSimilarityExampleSelector({
vectorStore,
filter: (doc) => doc.metadata.id === 2,
});
const chosen = await selector.selectExamples({ id: 1 });
expect(chosen).toEqual([{ id: 2 }]);
});
test("Test using SemanticSimilarityExampleSelector with a passed in retriever", async () => {
const vectorStore = await MemoryVectorStore.fromTexts(
["Hello world", "Bye bye", "hello nice world", "bye", "hi"],
[{ id: 2 }, { id: 1 }, { id: 3 }, { id: 4 }, { id: 5 }],
new FakeEmbeddings() // not using OpenAIEmbeddings() because would be extra dependency
);
const selector = new SemanticSimilarityExampleSelector({
vectorStoreRetriever: vectorStore.asRetriever({ k: 5 }),
});
const chosen = await selector.selectExamples({ id: 1 });
expect(chosen).toEqual([
{ id: 2 },
{ id: 1 },
{ id: 3 },
{ id: 4 },
{ id: 5 },
]);
});
|
0 | lc_public_repos/langchainjs/langchain/src/prompts/tests | lc_public_repos/langchainjs/langchain/src/prompts/tests/prompts/hello_world.yaml | input_variables: []
output_parser: null
template: "Say hello world."
template_format: f-string
|
0 | lc_public_repos/langchainjs/langchain/src/prompts | lc_public_repos/langchainjs/langchain/src/prompts/selectors/SemanticSimilarityExampleSelector.ts | export * from "@langchain/core/example_selectors";
|
0 | lc_public_repos/langchainjs/langchain/src/prompts | lc_public_repos/langchainjs/langchain/src/prompts/selectors/conditional.ts | export {
type BaseGetPromptAsyncOptions,
BasePromptSelector,
ConditionalPromptSelector,
isLLM,
isChatModel,
} from "@langchain/core/example_selectors";
|
0 | lc_public_repos/langchainjs/langchain/src/prompts | lc_public_repos/langchainjs/langchain/src/prompts/selectors/LengthBasedExampleSelector.ts | export {
type LengthBasedExampleSelectorInput,
LengthBasedExampleSelector,
} from "@langchain/core/example_selectors";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/cache/file_system.ts | import path from "node:path";
import fs from "node:fs/promises";
import {
BaseCache,
getCacheKey,
serializeGeneration,
deserializeStoredGeneration,
} from "@langchain/core/caches";
import { Generation } from "@langchain/core/outputs";
/**
* A cache that uses the local filesystem as the backing store.
* This is useful for local development and testing. But it is not recommended for production use.
*/
export class LocalFileCache extends BaseCache {
private cacheDir: string;
private constructor(cacheDir: string) {
super();
this.cacheDir = cacheDir;
}
/**
* Create a new cache backed by the local filesystem.
* It ensures that the cache directory exists before returning.
* @param cacheDir
*/
public static async create(cacheDir?: string): Promise<LocalFileCache> {
if (!cacheDir) {
// eslint-disable-next-line no-param-reassign
cacheDir = await fs.mkdtemp("langchain-cache-");
} else {
// ensure the cache directory exists
await fs.mkdir(cacheDir, { recursive: true });
}
return new LocalFileCache(cacheDir);
}
/**
* Retrieves data from the cache. It constructs a cache key from the given
* `prompt` and `llmKey`, and retrieves the corresponding value from the
* cache files.
* @param prompt The prompt used to construct the cache key.
* @param llmKey The LLM key used to construct the cache key.
* @returns An array of Generations if found, null otherwise.
*/
public async lookup(prompt: string, llmKey: string) {
const key = `${getCacheKey(prompt, llmKey)}.json`;
try {
const content = await fs.readFile(path.join(this.cacheDir, key));
return JSON.parse(content.toString()).map(deserializeStoredGeneration);
} catch {
return null;
}
}
/**
* Updates the cache with new data. It constructs a cache key from the
* given `prompt` and `llmKey`, and stores the `value` in a specific
* file in the cache directory.
* @param prompt The prompt used to construct the cache key.
* @param llmKey The LLM key used to construct the cache key.
* @param generations The value to be stored in the cache.
*/
public async update(
prompt: string,
llmKey: string,
generations: Generation[]
) {
const key = `${getCacheKey(prompt, llmKey)}.json`;
await fs.writeFile(
path.join(this.cacheDir, key),
JSON.stringify(generations.map(serializeGeneration))
);
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/cache/base.ts | export * from "@langchain/core/caches";
|
0 | lc_public_repos/langchainjs/langchain/src/cache | lc_public_repos/langchainjs/langchain/src/cache/tests/file_system.int.test.ts | import { test, expect } from "@jest/globals";
import fs from "node:fs/promises";
import path from "node:path";
import * as os from "node:os";
import { OpenAI, ChatOpenAI } from "@langchain/openai";
import { LocalFileCache } from "../file_system.js";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let tmpDir: string;
describe("Test LocalFileCache", () => {
beforeAll(async () => {
tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), "langchain-"));
});
afterAll(async () => {
await fs.rm(tmpDir, { recursive: true });
});
test("FSCache with an LLM", async () => {
const cache = await LocalFileCache.create(tmpDir);
const model = new OpenAI({ cache });
const response1 = await model.invoke("What is something random?");
const response2 = await model.invoke("What is something random?");
expect(response1).toEqual(response2);
});
test("FSCache with a chat model", async () => {
const cache = await LocalFileCache.create(tmpDir);
const model = new ChatOpenAI({ cache });
const response1 = await model.invoke("What is something random?");
const response2 = await model.invoke("What is something random?");
expect(response1).not.toBeUndefined();
// console.log(response1, response2);
expect(response1).toEqual(response2);
});
});
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/dynamic.ts | export {
type BaseDynamicToolInput,
type DynamicToolInput,
type DynamicStructuredToolInput,
DynamicTool,
DynamicStructuredTool,
} from "@langchain/core/tools";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/chain.ts | import { DynamicTool, DynamicToolInput } from "@langchain/core/tools";
import { BaseChain } from "../chains/base.js";
/**
* @deprecated Wrap in a DynamicTool instead.
* Interface for the input parameters of the ChainTool constructor.
* Extends the DynamicToolInput interface, replacing the 'func' property
* with a 'chain' property.
*/
export interface ChainToolInput extends Omit<DynamicToolInput, "func"> {
chain: BaseChain;
}
/**
* @deprecated Wrap in a DynamicTool instead.
* Class that extends DynamicTool for creating tools that can run chains.
* Takes an instance of a class that extends BaseChain as a parameter in
* its constructor and uses it to run the chain when its 'func' method is
* called.
*/
export class ChainTool extends DynamicTool {
static lc_name() {
return "ChainTool";
}
chain: BaseChain;
constructor({ chain, ...rest }: ChainToolInput) {
super({
...rest,
func: async (input, runManager) =>
chain.run(input, runManager?.getChild()),
});
this.chain = chain;
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/retriever.ts | import type { BaseRetrieverInterface } from "@langchain/core/retrievers";
import { z } from "zod";
import { CallbackManagerForToolRun } from "@langchain/core/callbacks/manager";
import {
DynamicStructuredTool,
type DynamicStructuredToolInput,
} from "@langchain/core/tools";
import { formatDocumentsAsString } from "../util/document.js";
export function createRetrieverTool(
retriever: BaseRetrieverInterface,
input: Omit<DynamicStructuredToolInput, "func" | "schema">
) {
const func = async (
{ query }: { query: string },
runManager?: CallbackManagerForToolRun
) => {
const docs = await retriever.getRelevantDocuments(
query,
runManager?.getChild("retriever")
);
return formatDocumentsAsString(docs);
};
const schema = z.object({
query: z.string().describe("query to look up in retriever"),
});
return new DynamicStructuredTool({ ...input, func, schema });
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/requests.ts | import { Tool } from "@langchain/core/tools";
export interface Headers {
[key: string]: string;
}
/**
* Interface for HTTP request tools. Contains properties for headers and
* maximum output length.
*/
export interface RequestTool {
headers: Headers;
maxOutputLength: number;
}
/**
* Class for making GET requests. Extends the Tool class and implements
* the RequestTool interface. The input should be a URL string, and the
* output will be the text response of the GET request.
*/
export class RequestsGetTool extends Tool implements RequestTool {
static lc_name() {
return "RequestsGetTool";
}
name = "requests_get";
maxOutputLength = 2000;
constructor(
public headers: Headers = {},
{ maxOutputLength }: { maxOutputLength?: number } = {}
) {
super(...arguments);
this.maxOutputLength = maxOutputLength ?? this.maxOutputLength;
}
/** @ignore */
async _call(input: string) {
const res = await fetch(input, {
headers: this.headers,
});
const text = await res.text();
return text.slice(0, this.maxOutputLength);
}
description = `A portal to the internet. Use this when you need to get specific content from a website.
Input should be a url string (i.e. "https://www.google.com"). The output will be the text response of the GET request.`;
}
/**
* Class for making POST requests. Extends the Tool class and implements
* the RequestTool interface. The input should be a JSON string with two
* keys: 'url' and 'data'. The output will be the text response of the
* POST request.
*/
export class RequestsPostTool extends Tool implements RequestTool {
static lc_name() {
return "RequestsPostTool";
}
name = "requests_post";
maxOutputLength = Infinity;
constructor(
public headers: Headers = {},
{ maxOutputLength }: { maxOutputLength?: number } = {}
) {
super(...arguments);
this.maxOutputLength = maxOutputLength ?? this.maxOutputLength;
}
/** @ignore */
async _call(input: string) {
try {
const { url, data } = JSON.parse(input);
const res = await fetch(url, {
method: "POST",
headers: this.headers,
body: JSON.stringify(data),
});
const text = await res.text();
return text.slice(0, this.maxOutputLength);
} catch (error) {
return `${error}`;
}
}
description = `Use this when you want to POST to a website.
Input should be a json string with two keys: "url" and "data".
The value of "url" should be a string, and the value of "data" should be a dictionary of
key-value pairs you want to POST to the url as a JSON body.
Be careful to always use double quotes for strings in the json string
The output will be the text response of the POST request.`;
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/sql.ts | import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base";
import { OpenAI } from "@langchain/openai";
import { Tool } from "@langchain/core/tools";
import { PromptTemplate } from "@langchain/core/prompts";
import { LLMChain } from "../chains/llm_chain.js";
import type { SqlDatabase } from "../sql_db.js";
import { SqlTable } from "../util/sql_utils.js";
/**
* Interface for SQL tools. It has a `db` property which is a SQL
* database.
*/
interface SqlTool {
db: SqlDatabase;
}
/**
* A tool for executing SQL queries. It takes a SQL database as a
* parameter and assigns it to the `db` property. The `_call` method is
* used to run the SQL query and return the result. If the query is
* incorrect, an error message is returned.
*/
export class QuerySqlTool extends Tool implements SqlTool {
static lc_name() {
return "QuerySqlTool";
}
name = "query-sql";
db: SqlDatabase;
constructor(db: SqlDatabase) {
super(...arguments);
this.db = db;
}
/** @ignore */
async _call(input: string) {
try {
return await this.db.run(input);
} catch (error) {
return `${error}`;
}
}
description = `Input to this tool is a detailed and correct SQL query, output is a result from the database.
If the query is not correct, an error message will be returned.
If an error is returned, rewrite the query, check the query, and try again.`;
}
/**
* A tool for retrieving information about SQL tables. It takes a SQL
* database as a parameter and assigns it to the `db` property. The
* `_call` method is used to retrieve the schema and sample rows for the
* specified tables. If the tables do not exist, an error message is
* returned.
*/
export class InfoSqlTool extends Tool implements SqlTool {
static lc_name() {
return "InfoSqlTool";
}
name = "info-sql";
db: SqlDatabase;
constructor(db: SqlDatabase) {
super();
this.db = db;
}
/** @ignore */
async _call(input: string) {
try {
const tables = input.split(",").map((table) => table.trim());
return await this.db.getTableInfo(tables);
} catch (error) {
return `${error}`;
}
}
description = `Input to this tool is a comma-separated list of tables, output is the schema and sample rows for those tables.
Be sure that the tables actually exist by calling list-tables-sql first!
Example Input: "table1, table2, table3.`;
}
/**
* A tool for listing all tables in a SQL database. It takes a SQL
* database as a parameter and assigns it to the `db` property. The
* `_call` method is used to return a comma-separated list of all tables
* in the database.
*/
export class ListTablesSqlTool extends Tool implements SqlTool {
static lc_name() {
return "ListTablesSqlTool";
}
name = "list-tables-sql";
db: SqlDatabase;
constructor(db: SqlDatabase) {
super();
this.db = db;
}
async _call(_: string) {
try {
let selectedTables: SqlTable[] = this.db.allTables;
if (this.db.includesTables.length > 0) {
selectedTables = selectedTables.filter((currentTable) =>
this.db.includesTables.includes(currentTable.tableName)
);
}
if (this.db.ignoreTables.length > 0) {
selectedTables = selectedTables.filter(
(currentTable) =>
!this.db.ignoreTables.includes(currentTable.tableName)
);
}
const tables = selectedTables.map((table: SqlTable) => table.tableName);
return tables.join(", ");
} catch (error) {
return `${error}`;
}
}
description = `Input is an empty string, output is a comma-separated list of tables in the database.`;
}
/**
* Arguments for the QueryCheckerTool class.
*/
type QueryCheckerToolArgs = {
llmChain?: LLMChain;
llm?: BaseLanguageModelInterface;
_chainType?: never;
};
/**
* A tool for checking SQL queries for common mistakes. It takes a
* LLMChain or QueryCheckerToolArgs as a parameter. The `_call` method is
* used to check the input query for common mistakes and returns a
* prediction.
*/
export class QueryCheckerTool extends Tool {
static lc_name() {
return "QueryCheckerTool";
}
name = "query-checker";
template = `
{query}
Double check the SQL query above for common mistakes, including:
- Using NOT IN with NULL values
- Using UNION when UNION ALL should have been used
- Using BETWEEN for exclusive ranges
- Data type mismatch in predicates
- Properly quoting identifiers
- Using the correct number of arguments for functions
- Casting to the correct data type
- Using the proper columns for joins
If there are any of the above mistakes, rewrite the query. If there are no mistakes, just reproduce the original query.`;
llmChain: LLMChain;
constructor(llmChainOrOptions?: LLMChain | QueryCheckerToolArgs) {
super();
if (typeof llmChainOrOptions?._chainType === "function") {
this.llmChain = llmChainOrOptions as LLMChain;
} else {
const options = llmChainOrOptions as QueryCheckerToolArgs;
if (options?.llmChain !== undefined) {
this.llmChain = options.llmChain;
} else {
const prompt = new PromptTemplate({
template: this.template,
inputVariables: ["query"],
});
const llm = options?.llm ?? new OpenAI({ temperature: 0 });
this.llmChain = new LLMChain({ llm, prompt });
}
}
}
/** @ignore */
async _call(input: string) {
return this.llmChain.predict({ query: input });
}
description = `Use this tool to double check if your query is correct before executing it.
Always use this tool before executing a query with query-sql!`;
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/fs.ts | import { z } from "zod";
import { StructuredTool, ToolParams } from "@langchain/core/tools";
import { BaseFileStore } from "../stores/file/base.js";
/**
* Interface for parameters required by the ReadFileTool class.
*/
interface ReadFileParams extends ToolParams {
store: BaseFileStore;
}
/**
* Class for reading files from the disk. Extends the StructuredTool
* class.
*/
export class ReadFileTool extends StructuredTool {
static lc_name() {
return "ReadFileTool";
}
schema = z.object({
file_path: z.string().describe("name of file"),
});
name = "read_file";
description = "Read file from disk";
store: BaseFileStore;
constructor({ store }: ReadFileParams) {
super(...arguments);
this.store = store;
}
async _call({ file_path }: z.infer<typeof this.schema>) {
return await this.store.readFile(file_path);
}
}
/**
* Interface for parameters required by the WriteFileTool class.
*/
interface WriteFileParams extends ToolParams {
store: BaseFileStore;
}
/**
* Class for writing data to files on the disk. Extends the StructuredTool
* class.
*/
export class WriteFileTool extends StructuredTool {
static lc_name() {
return "WriteFileTool";
}
schema = z.object({
file_path: z.string().describe("name of file"),
text: z.string().describe("text to write to file"),
});
name = "write_file";
description = "Write file from disk";
store: BaseFileStore;
constructor({ store, ...rest }: WriteFileParams) {
super(rest);
this.store = store;
}
async _call({ file_path, text }: z.infer<typeof this.schema>) {
await this.store.writeFile(file_path, text);
return "File written to successfully.";
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/webbrowser.ts | import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base";
import { Document } from "@langchain/core/documents";
import type { EmbeddingsInterface } from "@langchain/core/embeddings";
import axiosMod, { AxiosRequestConfig, AxiosStatic } from "axios";
import * as cheerio from "cheerio";
import {
CallbackManager,
CallbackManagerForToolRun,
} from "@langchain/core/callbacks/manager";
import { isNode } from "@langchain/core/utils/env";
import { Tool, ToolParams } from "@langchain/core/tools";
import { RunnableSequence } from "@langchain/core/runnables";
import { StringOutputParser } from "@langchain/core/output_parsers";
import {
RecursiveCharacterTextSplitter,
TextSplitter,
} from "../text_splitter.js";
import { MemoryVectorStore } from "../vectorstores/memory.js";
import fetchAdapter from "../util/axios-fetch-adapter.js";
import { formatDocumentsAsString } from "../util/document.js";
export const parseInputs = (inputs: string): [string, string] => {
const [baseUrl, task] = inputs.split(",").map((input) => {
let t = input.trim();
t = t.startsWith('"') ? t.slice(1) : t;
t = t.endsWith('"') ? t.slice(0, -1) : t;
// it likes to put / at the end of urls, wont matter for task
t = t.endsWith("/") ? t.slice(0, -1) : t;
return t.trim();
});
return [baseUrl, task];
};
export const getText = (
html: string,
baseUrl: string,
summary: boolean
): string => {
// scriptingEnabled so noscript elements are parsed
const $ = cheerio.load(html, { scriptingEnabled: true });
let text = "";
// lets only get the body if its a summary, dont need to summarize header or footer etc
const rootElement = summary ? "body " : "*";
// eslint-disable-next-line @typescript-eslint/no-explicit-any
$(`${rootElement}:not(style):not(script):not(svg)`).each((_i, elem: any) => {
// we dont want duplicated content as we drill down so remove children
let content = $(elem).clone().children().remove().end().text().trim();
const $el = $(elem);
// if its an ahref, print the content and url
let href = $el.attr("href");
if ($el.prop("tagName")?.toLowerCase() === "a" && href) {
if (!href.startsWith("http")) {
try {
href = new URL(href, baseUrl).toString();
} catch {
// if this fails thats fine, just no url for this
href = "";
}
}
const imgAlt = $el.find("img[alt]").attr("alt")?.trim();
if (imgAlt) {
content += ` ${imgAlt}`;
}
text += ` [${content}](${href})`;
}
// otherwise just print the content
else if (content !== "") {
text += ` ${content}`;
}
});
return text.trim().replace(/\n+/g, " ");
};
const getHtml = async (
baseUrl: string,
h: Headers,
config: AxiosRequestConfig
) => {
const axios = (
"default" in axiosMod ? axiosMod.default : axiosMod
) as AxiosStatic;
const domain = new URL(baseUrl).hostname;
const headers = { ...h };
// these appear to be positional, which means they have to exist in the headers passed in
headers.Host = domain;
headers["Alt-Used"] = domain;
let htmlResponse;
try {
htmlResponse = await axios.get(baseUrl, {
...config,
headers,
});
} catch (e) {
if (axios.isAxiosError(e) && e.response && e.response.status) {
throw new Error(`http response ${e.response.status}`);
}
throw e;
}
const allowedContentTypes = [
"text/html",
"application/json",
"application/xml",
"application/javascript",
"text/plain",
];
const contentType = htmlResponse.headers["content-type"];
const contentTypeArray = contentType.split(";");
if (
contentTypeArray[0] &&
!allowedContentTypes.includes(contentTypeArray[0])
) {
throw new Error("returned page was not utf8");
}
return htmlResponse.data;
};
const DEFAULT_HEADERS = {
Accept:
"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
"Accept-Encoding": "gzip, deflate",
"Accept-Language": "en-US,en;q=0.5",
"Alt-Used": "LEAVE-THIS-KEY-SET-BY-TOOL",
Connection: "keep-alive",
Host: "LEAVE-THIS-KEY-SET-BY-TOOL",
Referer: "https://www.google.com/",
"Sec-Fetch-Dest": "document",
"Sec-Fetch-Mode": "navigate",
"Sec-Fetch-Site": "cross-site",
"Upgrade-Insecure-Requests": "1",
"User-Agent":
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/111.0",
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type Headers = Record<string, any>;
/**
* Defines the arguments that can be passed to the WebBrowser constructor.
* It extends the ToolParams interface and includes properties for a
* language model, embeddings, HTTP headers, an Axios configuration, a
* callback manager, and a text splitter.
*/
export interface WebBrowserArgs extends ToolParams {
model: BaseLanguageModelInterface;
embeddings: EmbeddingsInterface;
headers?: Headers;
axiosConfig?: Omit<AxiosRequestConfig, "url">;
/** @deprecated */
callbackManager?: CallbackManager;
textSplitter?: TextSplitter;
}
/**
* A class designed to interact with web pages, either to extract
* information from them or to summarize their content. It uses the axios
* library to send HTTP requests and the cheerio library to parse the
* returned HTML.
* @example
* ```typescript
* const browser = new WebBrowser({
* model: new ChatOpenAI({ temperature: 0 }),
* embeddings: new OpenAIEmbeddings({}),
* });
* const result = await browser.invoke("https:exampleurl.com");
* ```
*/
export class WebBrowser extends Tool {
static lc_name() {
return "WebBrowser";
}
get lc_namespace() {
return [...super.lc_namespace, "webbrowser"];
}
private model: BaseLanguageModelInterface;
private embeddings: EmbeddingsInterface;
private headers: Headers;
private axiosConfig: Omit<AxiosRequestConfig, "url">;
private textSplitter: TextSplitter;
constructor({
model,
headers,
embeddings,
axiosConfig,
textSplitter,
}: WebBrowserArgs) {
super(...arguments);
this.model = model;
this.embeddings = embeddings;
this.headers = headers ?? DEFAULT_HEADERS;
this.axiosConfig = {
withCredentials: true,
adapter: isNode() ? undefined : fetchAdapter,
...axiosConfig,
};
this.textSplitter =
textSplitter ??
new RecursiveCharacterTextSplitter({
chunkSize: 2000,
chunkOverlap: 200,
});
}
/** @ignore */
async _call(inputs: string, runManager?: CallbackManagerForToolRun) {
const [baseUrl, task] = parseInputs(inputs);
const doSummary = !task;
let text;
try {
const html = await getHtml(baseUrl, this.headers, this.axiosConfig);
text = getText(html, baseUrl, doSummary);
} catch (e) {
if (e) {
return e.toString();
}
return "There was a problem connecting to the site";
}
const texts = await this.textSplitter.splitText(text);
let context;
// if we want a summary grab first 4
if (doSummary) {
context = texts.slice(0, 4).join("\n");
}
// search term well embed and grab top 4
else {
const docs = texts.map(
(pageContent) =>
new Document({
pageContent,
metadata: [],
})
);
const vectorStore = await MemoryVectorStore.fromDocuments(
docs,
this.embeddings
);
const results = await vectorStore.similaritySearch(
task,
4,
undefined,
runManager?.getChild("vectorstore")
);
context = formatDocumentsAsString(results);
}
const input = `Text:${context}\n\nI need ${
doSummary ? "a summary" : task
} from the above text, also provide up to 5 markdown links from within that would be of interest (always including URL and text). Links should be provided, if present, in markdown syntax as a list under the heading "Relevant Links:".`;
const chain = RunnableSequence.from([this.model, new StringOutputParser()]);
return chain.invoke(input, runManager?.getChild());
}
name = "web-browser";
description = `useful for when you need to find something on or summarize a webpage. input should be a comma separated list of "ONE valid http URL including protocol","what you want to find on the page or empty string for a summary".`;
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/index.ts | export { Tool, type ToolParams, StructuredTool } from "./base.js";
export {
DynamicTool,
type DynamicToolInput,
DynamicStructuredTool,
type DynamicStructuredToolInput,
} from "./dynamic.js";
export { ChainTool, type ChainToolInput } from "./chain.js";
export {
JsonSpec,
JsonListKeysTool,
JsonGetValueTool,
type JsonObject,
type Json,
} from "./json.js";
export { RequestsGetTool, RequestsPostTool } from "./requests.js";
export { VectorStoreQATool } from "./vectorstore.js";
export { ReadFileTool, WriteFileTool } from "./fs.js";
export {
formatToOpenAIFunction,
formatToOpenAITool,
} from "./convert_to_openai.js";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/render.ts | import { zodToJsonSchema, JsonSchema7ObjectType } from "zod-to-json-schema";
import { StructuredToolInterface } from "@langchain/core/tools";
import {
ToolDefinition,
isOpenAITool,
} from "@langchain/core/language_models/base";
/**
* Render the tool name and description in plain text.
*
* Output will be in the format of:
* ```
* search: This tool is used for search
* calculator: This tool is used for math
* ```
* @param tools
* @returns a string of all tools and their descriptions
*/
export function renderTextDescription(
tools: StructuredToolInterface[] | ToolDefinition[]
): string {
if ((tools as unknown[]).every(isOpenAITool)) {
return (tools as ToolDefinition[])
.map(
(tool) =>
`${tool.function.name}${
tool.function.description ? `: ${tool.function.description}` : ""
}`
)
.join("\n");
}
return (tools as StructuredToolInterface[])
.map((tool) => `${tool.name}: ${tool.description}`)
.join("\n");
}
/**
* Render the tool name, description, and args in plain text.
* Output will be in the format of:'
* ```
* search: This tool is used for search, args: {"query": {"type": "string"}}
* calculator: This tool is used for math,
* args: {"expression": {"type": "string"}}
* ```
* @param tools
* @returns a string of all tools, their descriptions and a stringified version of their schemas
*/
export function renderTextDescriptionAndArgs(
tools: StructuredToolInterface[] | ToolDefinition[]
): string {
if ((tools as unknown[]).every(isOpenAITool)) {
return (tools as ToolDefinition[])
.map(
(tool) =>
`${tool.function.name}${
tool.function.description ? `: ${tool.function.description}` : ""
}, args: ${JSON.stringify(tool.function.parameters)}`
)
.join("\n");
}
return (tools as StructuredToolInterface[])
.map(
(tool) =>
`${tool.name}: ${tool.description}, args: ${JSON.stringify(
(zodToJsonSchema(tool.schema) as JsonSchema7ObjectType).properties
)}`
)
.join("\n");
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/json.ts | import jsonpointer from "jsonpointer";
import { Serializable } from "@langchain/core/load/serializable";
import { Tool, ToolParams } from "@langchain/core/tools";
export type Json =
| string
| number
| boolean
| null
| { [key: string]: Json }
| Json[];
export type JsonObject = { [key: string]: Json };
/**
* Represents a JSON object in the LangChain framework. Provides methods
* to get keys and values from the JSON object.
*/
export class JsonSpec extends Serializable {
lc_namespace = ["langchain", "tools", "json"];
obj: JsonObject;
maxValueLength = 4000;
constructor(obj: JsonObject, max_value_length = 4000) {
super(...arguments);
this.obj = obj;
this.maxValueLength = max_value_length;
}
/**
* Retrieves all keys at a given path in the JSON object.
* @param input The path to the keys in the JSON object, provided as a string in JSON pointer syntax.
* @returns A string containing all keys at the given path, separated by commas.
*/
public getKeys(input: string): string {
const pointer = jsonpointer.compile(input);
const res = pointer.get(this.obj) as Json;
if (typeof res === "object" && !Array.isArray(res) && res !== null) {
return Object.keys(res)
.map((i) => i.replaceAll("~", "~0").replaceAll("/", "~1"))
.join(", ");
}
throw new Error(
`Value at ${input} is not a dictionary, get the value directly instead.`
);
}
/**
* Retrieves the value at a given path in the JSON object.
* @param input The path to the value in the JSON object, provided as a string in JSON pointer syntax.
* @returns The value at the given path in the JSON object, as a string. If the value is a large dictionary or exceeds the maximum length, a message is returned instead.
*/
public getValue(input: string): string {
const pointer = jsonpointer.compile(input);
const res = pointer.get(this.obj) as Json;
if (res === null || res === undefined) {
throw new Error(`Value at ${input} is null or undefined.`);
}
const str = typeof res === "object" ? JSON.stringify(res) : res.toString();
if (
typeof res === "object" &&
!Array.isArray(res) &&
str.length > this.maxValueLength
) {
return `Value is a large dictionary, should explore its keys directly.`;
}
if (str.length > this.maxValueLength) {
return `${str.slice(0, this.maxValueLength)}...`;
}
return str;
}
}
export interface JsonToolFields extends ToolParams {
jsonSpec: JsonSpec;
}
/**
* A tool in the LangChain framework that lists all keys at a given path
* in a JSON object.
*/
export class JsonListKeysTool extends Tool {
static lc_name() {
return "JsonListKeysTool";
}
name = "json_list_keys";
jsonSpec: JsonSpec;
constructor(jsonSpec: JsonSpec);
constructor(fields: JsonToolFields);
constructor(fields: JsonSpec | JsonToolFields) {
if (!("jsonSpec" in fields)) {
// eslint-disable-next-line no-param-reassign
fields = { jsonSpec: fields };
}
super(fields);
this.jsonSpec = fields.jsonSpec;
}
/** @ignore */
async _call(input: string) {
try {
return this.jsonSpec.getKeys(input);
} catch (error) {
return `${error}`;
}
}
description = `Can be used to list all keys at a given path.
Before calling this you should be SURE that the path to this exists.
The input is a text representation of the path to the json as json pointer syntax (e.g. /key1/0/key2).`;
}
/**
* A tool in the LangChain framework that retrieves the value at a given
* path in a JSON object.
*/
export class JsonGetValueTool extends Tool {
static lc_name() {
return "JsonGetValueTool";
}
name = "json_get_value";
constructor(public jsonSpec: JsonSpec) {
super();
}
/** @ignore */
async _call(input: string) {
try {
return this.jsonSpec.getValue(input);
} catch (error) {
return `${error}`;
}
}
description = `Can be used to see value in string format at a given path.
Before calling this you should be SURE that the path to this exists.
The input is a text representation of the path to the json as json pointer syntax (e.g. /key1/0/key2).`;
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/base.ts | export {
type ToolParams,
ToolInputParsingException,
StructuredTool,
Tool,
} from "@langchain/core/tools";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/vectorstore.ts | import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base";
import type { VectorStoreInterface } from "@langchain/core/vectorstores";
import { Tool } from "@langchain/core/tools";
import { VectorDBQAChain } from "../chains/vector_db_qa.js";
/**
* Interface for tools that interact with a Vector Store.
*/
interface VectorStoreTool {
vectorStore: VectorStoreInterface;
llm: BaseLanguageModelInterface;
}
/**
* A tool for the VectorDBQA chain to interact with a Vector Store. It is
* used to answer questions about a specific topic. The input to this tool
* should be a fully formed question.
*/
export class VectorStoreQATool extends Tool implements VectorStoreTool {
static lc_name() {
return "VectorStoreQATool";
}
vectorStore: VectorStoreInterface;
llm: BaseLanguageModelInterface;
name: string;
description: string;
chain: VectorDBQAChain;
constructor(name: string, description: string, fields: VectorStoreTool) {
super(...arguments);
this.name = name;
this.description = description;
this.vectorStore = fields.vectorStore;
this.llm = fields.llm;
this.chain = VectorDBQAChain.fromLLM(this.llm, this.vectorStore);
}
/**
* Returns a string that describes what the tool does.
* @param name The name of the tool.
* @param description A description of what the tool does.
* @returns A string that describes what the tool does.
*/
static getDescription(name: string, description: string): string {
return `Useful for when you need to answer questions about ${name}. Whenever you need information about ${description} you should ALWAYS use this. Input should be a fully formed question.`;
}
/** @ignore */
async _call(input: string) {
return this.chain.run(input);
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tools/convert_to_openai.ts | import { zodToJsonSchema } from "zod-to-json-schema";
import type { StructuredToolInterface } from "@langchain/core/tools";
import {
convertToOpenAIFunction,
convertToOpenAITool,
} from "@langchain/core/utils/function_calling";
export {
convertToOpenAIFunction as formatToOpenAIFunction,
convertToOpenAITool as formatToOpenAITool,
};
export function formatToOpenAIAssistantTool(tool: StructuredToolInterface) {
return {
type: "function",
function: {
name: tool.name,
description: tool.description,
parameters: zodToJsonSchema(tool.schema),
},
};
}
|
0 | lc_public_repos/langchainjs/langchain/src/tools | lc_public_repos/langchainjs/langchain/src/tools/tests/chain.test.ts | import { test, expect, jest } from "@jest/globals";
import { LLM } from "@langchain/core/language_models/llms";
import { PromptTemplate } from "@langchain/core/prompts";
import { FakeEmbeddings } from "@langchain/core/utils/testing";
import { ChainTool } from "../chain.js";
import { LLMChain } from "../../chains/llm_chain.js";
import { VectorDBQAChain } from "../../chains/vector_db_qa.js";
import { MemoryVectorStore } from "../../vectorstores/memory.js";
class FakeLLM extends LLM {
_llmType() {
return "fake";
}
async _call(prompt: string): Promise<string> {
return prompt;
}
}
test("chain tool with llm chain and local callback", async () => {
const calls: string[] = [];
const handleToolStart = jest.fn(() => {
calls.push("tool start");
});
const handleToolEnd = jest.fn(() => {
calls.push("tool end");
});
const handleLLMStart = jest.fn(() => {
calls.push("llm start");
});
const handleLLMEnd = jest.fn(() => {
calls.push("llm end");
});
const handleChainStart = jest.fn(() => {
calls.push("chain start");
});
const handleChainEnd = jest.fn(() => {
calls.push("chain end");
});
const chain = new LLMChain({
llm: new FakeLLM({}),
prompt: PromptTemplate.fromTemplate("hello world"),
});
const tool = new ChainTool({ chain, name: "fake", description: "fake" });
const result = await tool.invoke("hi", {
callbacks: [
{
awaitHandlers: true,
handleToolStart,
handleToolEnd,
handleLLMStart,
handleLLMEnd,
handleChainStart,
handleChainEnd,
},
],
});
expect(result).toMatchInlineSnapshot(`"hello world"`);
expect(handleToolStart).toBeCalledTimes(1);
expect(handleToolEnd).toBeCalledTimes(1);
expect(handleLLMStart).toBeCalledTimes(1);
expect(handleLLMEnd).toBeCalledTimes(1);
expect(handleChainStart).toBeCalledTimes(1);
expect(handleChainEnd).toBeCalledTimes(1);
expect(calls).toMatchInlineSnapshot(`
[
"tool start",
"chain start",
"llm start",
"llm end",
"chain end",
"tool end",
]
`);
});
test("chain tool with vectordbqa chain", async () => {
const calls: string[] = [];
const handleToolStart = jest.fn(() => {
calls.push("tool start");
});
const handleToolEnd = jest.fn(() => {
calls.push("tool end");
});
const handleLLMStart = jest.fn(() => {
calls.push("llm start");
});
const handleLLMEnd = jest.fn(() => {
calls.push("llm end");
});
const handleChainStart = jest.fn(() => {
calls.push("chain start");
});
const handleChainEnd = jest.fn(() => {
calls.push("chain end");
});
const chain = VectorDBQAChain.fromLLM(
new FakeLLM({}),
await MemoryVectorStore.fromExistingIndex(new FakeEmbeddings())
);
const tool = new ChainTool({ chain, name: "fake", description: "fake" });
const result = await tool.invoke("hi", {
callbacks: [
{
awaitHandlers: true,
handleToolStart,
handleToolEnd,
handleLLMStart,
handleLLMEnd,
handleChainStart,
handleChainEnd,
},
],
});
expect(result).toMatchInlineSnapshot(`
"Use the following pieces of context to answer the question at the end. If you don't know the answer, just say that you don't know, don't try to make up an answer.
Question: hi
Helpful Answer:"
`);
expect(handleToolStart).toBeCalledTimes(1);
expect(handleToolEnd).toBeCalledTimes(1);
expect(handleLLMStart).toBeCalledTimes(1);
expect(handleLLMEnd).toBeCalledTimes(1);
expect(handleChainStart).toBeCalledTimes(3);
expect(handleChainEnd).toBeCalledTimes(3);
expect(calls).toMatchInlineSnapshot(`
[
"tool start",
"chain start",
"chain start",
"chain start",
"llm start",
"llm end",
"chain end",
"chain end",
"chain end",
"tool end",
]
`);
});
|
0 | lc_public_repos/langchainjs/langchain/src/tools | lc_public_repos/langchainjs/langchain/src/tools/tests/webbrowser.test.ts | import { test, expect, describe } from "@jest/globals";
import { readFileSync } from "fs";
import { getText, parseInputs } from "../webbrowser.js";
describe("webbrowser Test suite", () => {
const html = readFileSync("./src/tools/fixtures/wordoftheday.html", "utf8");
test("parse html to text and links", async () => {
const baseUrl = "https://www.merriam-webster.com/word-of-the-day";
const text = getText(html, baseUrl, false);
expect(text).toContain("Word of the Day: Foible");
});
test("parseInputs", () => {
expect(
parseInputs(`"https://www.merriam-webster.com/word-of-the-day",""`)
).toEqual(["https://www.merriam-webster.com/word-of-the-day", ""]);
expect(
parseInputs(
`"https://www.merriam-webster.com/word-of-the-day","word of the day"`
)
).toEqual([
"https://www.merriam-webster.com/word-of-the-day",
"word of the day",
]);
expect(
parseInputs(`"https://www.merriam-webster.com/word-of-the-day","`)
).toEqual(["https://www.merriam-webster.com/word-of-the-day", ""]);
expect(
parseInputs(`"https://www.merriam-webster.com/word-of-the-day",`)
).toEqual(["https://www.merriam-webster.com/word-of-the-day", ""]);
expect(
parseInputs(`"https://www.merriam-webster.com/word-of-the-day"`)
).toEqual(["https://www.merriam-webster.com/word-of-the-day", undefined]);
});
});
|
0 | lc_public_repos/langchainjs/langchain/src/tools | lc_public_repos/langchainjs/langchain/src/tools/tests/webbrowser.int.test.ts | import { test, expect, describe } from "@jest/globals";
import { ChatOpenAI, OpenAIEmbeddings } from "@langchain/openai";
import { WebBrowser } from "../webbrowser.js";
import fetchAdapter from "../../util/axios-fetch-adapter.js";
describe("webbrowser Test suite", () => {
test("get word of the day", async () => {
const model = new ChatOpenAI({ temperature: 0 });
const embeddings = new OpenAIEmbeddings();
const browser = new WebBrowser({ model, embeddings });
const result = await browser.call(
`"https://www.merriam-webster.com/word-of-the-day","word of the day"`
);
expect(result).toContain("Word of the Day:");
});
test("get a summary of the page when empty request with fetch adapter", async () => {
const model = new ChatOpenAI({ temperature: 0 });
const embeddings = new OpenAIEmbeddings();
const browser = new WebBrowser({
model,
embeddings,
axiosConfig: {
adapter: fetchAdapter,
},
});
const result = await browser.call(
`"https://www.merriam-webster.com/word-of-the-day",""`
);
// fuzzy, sometimes its capped and others not
expect(result).toMatch(/word of the day/i);
});
test("error no url", async () => {
const model = new ChatOpenAI({ temperature: 0 });
const embeddings = new OpenAIEmbeddings();
const browser = new WebBrowser({ model, embeddings });
const result = await browser.call(`"",""`);
expect(result).toContain("Invalid URL");
});
test("error no protocol or malformed", async () => {
const model = new ChatOpenAI({ temperature: 0 });
const embeddings = new OpenAIEmbeddings();
const browser = new WebBrowser({ model, embeddings });
const result = await browser.call(
`"www.merriam-webster.com/word-of-the-day","word of the day"`
);
expect(result).toContain("Invalid URL");
});
test("error bad site", async () => {
const model = new ChatOpenAI({ temperature: 0 });
const embeddings = new OpenAIEmbeddings();
const browser = new WebBrowser({ model, embeddings });
const result = await browser.call(
`"https://www.hDjRBKoAD0EIbF29TWM4rbXDGGM5Nhy4uzNEAdDS.com","word of the day"`
);
expect(result).toEqual(
"Error: getaddrinfo ENOTFOUND www.hdjrbkoad0eibf29twm4rbxdggm5nhy4uzneadds.com"
);
});
test.skip("get a summary of a page that detects scraping", async () => {
const model = new ChatOpenAI({ temperature: 0 });
const embeddings = new OpenAIEmbeddings();
const browser = new WebBrowser({ model, embeddings });
const result = await browser.call(
`"https://www.musicgateway.com/spotify-pre-save",""`
);
expect(result).not.toEqual("Error: http response 403");
});
// cant we figure the headers to fix this?
test.skip("get a summary of a page that detects scraping 2", async () => {
const model = new ChatOpenAI({ temperature: 0 });
const embeddings = new OpenAIEmbeddings();
const browser = new WebBrowser({ model, embeddings });
const result = await browser.call(
`"https://parade.com/991228/marynliles/couples-goals",""`
);
expect(result).not.toEqual("Error: http response 403");
});
test("get a summary of a page that rejects unauthorized", async () => {
const model = new ChatOpenAI({ temperature: 0 });
const embeddings = new OpenAIEmbeddings();
const browser = new WebBrowser({ model, embeddings });
const result = await browser.call(
`"https://firstround.com/review/how-to-fix-the-co-founder-fights-youre-sick-of-having-lessons-from-couples-therapist-esther-perel",""`
);
expect(result).toContain("Esther Perel");
});
// other urls that have done this too
// "https://wsimag.com/economy-and-politics/15473-power-and-money",
// "https://thriveglobal.com/stories/sleep-what-to-do-what-not-to-do",
test.skip("get a summary of a page that redirects too many times", async () => {
const model = new ChatOpenAI({ temperature: 0 });
const embeddings = new OpenAIEmbeddings();
const browser = new WebBrowser({ model, embeddings });
const result = await browser.call(
`"https://www.healtheuropa.eu/why-mdma-must-be-reclassified-as-a-schedule-2-drug/95780",""`
);
expect(result).toContain("Beckley Foundation");
});
});
|
0 | lc_public_repos/langchainjs/langchain/src/tools | lc_public_repos/langchainjs/langchain/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/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/list.ts | export {
ListOutputParser,
CommaSeparatedListOutputParser,
CustomListOutputParser,
} from "@langchain/core/output_parsers";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/noop.ts | import { BaseOutputParser } from "@langchain/core/output_parsers";
/**
* The NoOpOutputParser class is a type of output parser that does not
* perform any operations on the output. It extends the BaseOutputParser
* class and is part of the LangChain's output parsers module. This class
* is useful in scenarios where the raw output of the Large Language
* Models (LLMs) is required.
*/
export class NoOpOutputParser extends BaseOutputParser<string> {
static lc_name() {
return "NoOpOutputParser";
}
lc_namespace = ["langchain", "output_parsers", "default"];
lc_serializable = true;
/**
* This method takes a string as input and returns the same string as
* output. It does not perform any operations on the input string.
* @param text The input string to be parsed.
* @returns The same input string without any operations performed on it.
*/
parse(text: string): Promise<string> {
return Promise.resolve(text);
}
/**
* This method returns an empty string. It does not provide any formatting
* instructions.
* @returns An empty string, indicating no formatting instructions.
*/
getFormatInstructions(): string {
return "";
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/http_response.ts | import { BaseMessage } from "@langchain/core/messages";
import {
BaseTransformOutputParser,
StringOutputParser,
} from "@langchain/core/output_parsers";
export type HttpResponseOutputParserInput = {
outputParser?: BaseTransformOutputParser;
contentType?: "text/plain" | "text/event-stream";
};
/**
* OutputParser that formats chunks emitted from an LLM for different HTTP content types.
*/
export class HttpResponseOutputParser extends BaseTransformOutputParser<Uint8Array> {
static lc_name() {
return "HttpResponseOutputParser";
}
lc_namespace = ["langchain", "output_parser"];
lc_serializable = true;
outputParser: BaseTransformOutputParser = new StringOutputParser();
contentType: "text/plain" | "text/event-stream" = "text/plain";
constructor(fields?: HttpResponseOutputParserInput) {
super(fields);
this.outputParser = fields?.outputParser ?? this.outputParser;
this.contentType = fields?.contentType ?? this.contentType;
}
async *_transform(
inputGenerator: AsyncGenerator<string | BaseMessage>
): AsyncGenerator<Uint8Array> {
for await (const chunk of this.outputParser._transform(inputGenerator)) {
if (typeof chunk === "string") {
yield this.parse(chunk);
} else {
yield this.parse(JSON.stringify(chunk));
}
}
if (this.contentType === "text/event-stream") {
const encoder = new TextEncoder();
yield encoder.encode(`event: end\n\n`);
}
}
/**
* Parses a string output from an LLM call. This method is meant to be
* implemented by subclasses to define how a string output from an LLM
* should be parsed.
* @param text The string output from an LLM call.
* @param callbacks Optional callbacks.
* @returns A promise of the parsed output.
*/
async parse(text: string): Promise<Uint8Array> {
const chunk = await this.outputParser.parse(text);
const encoder = new TextEncoder();
if (this.contentType === "text/event-stream") {
return encoder.encode(`event: data\ndata: ${JSON.stringify(chunk)}\n\n`);
}
let parsedChunk;
if (typeof chunk === "string") {
parsedChunk = chunk;
} else {
parsedChunk = JSON.stringify(chunk);
}
return encoder.encode(parsedChunk);
}
getFormatInstructions(): string {
return "";
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/openai_functions.ts | import { JsonSchema7ObjectType } from "zod-to-json-schema";
import {
compare,
type Operation as JSONPatchOperation,
} from "@langchain/core/utils/json_patch";
import { ChatGeneration, Generation } from "@langchain/core/outputs";
import {
BaseCumulativeTransformOutputParser,
type BaseCumulativeTransformOutputParserInput,
BaseLLMOutputParser,
OutputParserException,
} from "@langchain/core/output_parsers";
import { parsePartialJson } from "@langchain/core/output_parsers";
import { Optional } from "../types/type-utils.js";
/**
* Represents optional parameters for a function in a JSON Schema.
*/
export type FunctionParameters = Optional<
JsonSchema7ObjectType,
"additionalProperties"
>;
/**
* Class for parsing the output of an LLM. Can be configured to return
* only the arguments of the function call in the output.
*/
export class OutputFunctionsParser extends BaseLLMOutputParser<string> {
static lc_name() {
return "OutputFunctionsParser";
}
lc_namespace = ["langchain", "output_parsers", "openai_functions"];
lc_serializable = true;
argsOnly = true;
constructor(config?: { argsOnly?: boolean }) {
super();
this.argsOnly = config?.argsOnly ?? this.argsOnly;
}
/**
* Parses the output and returns a string representation of the function
* call or its arguments.
* @param generations The output of the LLM to parse.
* @returns A string representation of the function call or its arguments.
*/
async parseResult(
generations: Generation[] | ChatGeneration[]
): Promise<string> {
if ("message" in generations[0]) {
const gen = generations[0] as ChatGeneration;
const functionCall = gen.message.additional_kwargs.function_call;
if (!functionCall) {
throw new Error(
`No function_call in message ${JSON.stringify(generations)}`
);
}
if (!functionCall.arguments) {
throw new Error(
`No arguments in function_call ${JSON.stringify(generations)}`
);
}
if (this.argsOnly) {
return functionCall.arguments;
}
return JSON.stringify(functionCall);
} else {
throw new Error(
`No message in generations ${JSON.stringify(generations)}`
);
}
}
}
/**
* Class for parsing the output of an LLM into a JSON object. Uses an
* instance of `OutputFunctionsParser` to parse the output.
*/
export class JsonOutputFunctionsParser<
Output extends object = object
> extends BaseCumulativeTransformOutputParser<Output> {
static lc_name() {
return "JsonOutputFunctionsParser";
}
lc_namespace = ["langchain", "output_parsers", "openai_functions"];
lc_serializable = true;
outputParser: OutputFunctionsParser;
argsOnly = true;
constructor(
config?: { argsOnly?: boolean } & BaseCumulativeTransformOutputParserInput
) {
super(config);
this.argsOnly = config?.argsOnly ?? this.argsOnly;
this.outputParser = new OutputFunctionsParser(config);
}
protected _diff(
prev: unknown | undefined,
next: unknown
): JSONPatchOperation[] | undefined {
if (!next) {
return undefined;
}
const ops = compare(prev ?? {}, next);
return ops;
}
async parsePartialResult(
generations: ChatGeneration[]
): Promise<Output | undefined> {
const generation = generations[0];
if (!generation.message) {
return undefined;
}
const { message } = generation;
const functionCall = message.additional_kwargs.function_call;
if (!functionCall) {
return undefined;
}
if (this.argsOnly) {
return parsePartialJson(functionCall.arguments);
}
return {
...functionCall,
arguments: parsePartialJson(functionCall.arguments),
} as Output;
}
/**
* Parses the output and returns a JSON object. If `argsOnly` is true,
* only the arguments of the function call are returned.
* @param generations The output of the LLM to parse.
* @returns A JSON object representation of the function call or its arguments.
*/
async parseResult(
generations: Generation[] | ChatGeneration[]
): Promise<Output> {
const result = await this.outputParser.parseResult(generations);
if (!result) {
throw new Error(
`No result from "OutputFunctionsParser" ${JSON.stringify(generations)}`
);
}
return this.parse(result);
}
async parse(text: string): Promise<Output> {
try {
const parsedResult = JSON.parse(text);
if (this.argsOnly) {
return parsedResult;
}
parsedResult.arguments = JSON.parse(parsedResult.arguments);
return parsedResult;
} catch (e) {
throw new OutputParserException(
`Failed to parse. Text: "${text}". Error: ${e}`
);
}
}
getFormatInstructions(): string {
return "";
}
}
/**
* Class for parsing the output of an LLM into a JSON object and returning
* a specific attribute. Uses an instance of `JsonOutputFunctionsParser`
* to parse the output.
*/
export class JsonKeyOutputFunctionsParser<
T = object
> extends BaseLLMOutputParser<T> {
static lc_name() {
return "JsonKeyOutputFunctionsParser";
}
lc_namespace = ["langchain", "output_parsers", "openai_functions"];
lc_serializable = true;
outputParser = new JsonOutputFunctionsParser();
attrName: string;
get lc_aliases() {
return {
attrName: "key_name",
};
}
constructor(fields: { attrName: string }) {
super(fields);
this.attrName = fields.attrName;
}
/**
* Parses the output and returns a specific attribute of the parsed JSON
* object.
* @param generations The output of the LLM to parse.
* @returns The value of a specific attribute of the parsed JSON object.
*/
async parseResult(generations: Generation[] | ChatGeneration[]): Promise<T> {
const result = await this.outputParser.parseResult(generations);
return result[this.attrName as keyof typeof result] as T;
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/combining.ts | import { Callbacks } from "@langchain/core/callbacks/manager";
import { BaseOutputParser } from "@langchain/core/output_parsers";
/**
* Type for the combined output of the CombiningOutputParser class.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export type CombinedOutput = Record<string, any>;
/**
* Interface for the fields required by the CombiningOutputParser class.
*/
export interface CombiningOutputParserFields {
parsers: BaseOutputParser[];
}
/**
* Class to combine multiple output parsers
* @augments BaseOutputParser
*/
export class CombiningOutputParser extends BaseOutputParser<object> {
static lc_name() {
return "CombiningOutputParser";
}
lc_namespace = ["langchain", "output_parsers", "combining"];
lc_serializable = true;
parsers: BaseOutputParser[];
outputDelimiter = "-----";
constructor(fields: CombiningOutputParserFields);
constructor(...parsers: BaseOutputParser[]);
constructor(
fields: BaseOutputParser | CombiningOutputParserFields,
...parsers: BaseOutputParser[]
) {
if (parsers.length > 0 || !("parsers" in fields)) {
// eslint-disable-next-line no-param-reassign
fields = {
parsers: [fields as BaseOutputParser, ...parsers],
};
}
super(fields);
this.parsers = fields.parsers;
}
/**
* Method to parse an input string using the parsers in the parsers array.
* The parsed outputs are combined into a single object and returned.
* @param input The input string to parse.
* @param callbacks Optional Callbacks object.
* @returns A Promise that resolves to a CombinedOutput object.
*/
async parse(input: string, callbacks?: Callbacks): Promise<CombinedOutput> {
const inputs = input
.trim()
.split(
new RegExp(`${this.outputDelimiter}Output \\d+${this.outputDelimiter}`)
)
.slice(1);
const ret: CombinedOutput = {};
for (const [i, p] of this.parsers.entries()) {
let parsed;
try {
let extracted = inputs[i].includes("```")
? inputs[i].trim().split(/```/)[1]
: inputs[i].trim();
if (extracted.endsWith(this.outputDelimiter)) {
extracted = extracted.slice(0, -this.outputDelimiter.length);
}
parsed = await p.parse(extracted, callbacks);
} catch (e) {
parsed = await p.parse(input.trim(), callbacks);
}
Object.assign(ret, parsed);
}
return ret;
}
/**
* Method to get instructions on how to format the LLM output. The
* instructions are based on the parsers array and the outputDelimiter.
* @returns A string with format instructions.
*/
getFormatInstructions(): string {
return `${[
`Return the following ${this.parsers.length} outputs, each formatted as described below. Include the delimiter characters "${this.outputDelimiter}" in your response:`,
...this.parsers.map(
(p, i) =>
`${this.outputDelimiter}Output ${i + 1}${this.outputDelimiter}\n${p
.getFormatInstructions()
.trim()}\n${this.outputDelimiter}`
),
].join("\n\n")}\n`;
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/regex.ts | import {
BaseOutputParser,
OutputParserException,
} from "@langchain/core/output_parsers";
import type { SerializedFields } from "../load/map_keys.js";
export interface RegExpFields {
pattern: string;
flags?: string;
}
/**
* Interface for the fields required to create a RegexParser instance.
*/
export interface RegexParserFields {
regex: string | RegExp | RegExpFields;
outputKeys: string[];
defaultOutputKey?: string;
}
/**
* Class to parse the output of an LLM call into a dictionary.
* @augments BaseOutputParser
*/
export class RegexParser extends BaseOutputParser<Record<string, string>> {
static lc_name() {
return "RegexParser";
}
lc_namespace = ["langchain", "output_parsers", "regex"];
lc_serializable = true;
get lc_attributes(): SerializedFields | undefined {
return {
regex: this.lc_kwargs.regex,
};
}
regex: string | RegExp;
outputKeys: string[];
defaultOutputKey?: string;
constructor(fields: RegexParserFields);
constructor(
regex: string | RegExp,
outputKeys: string[],
defaultOutputKey?: string
);
constructor(
fields: string | RegExp | RegexParserFields,
outputKeys?: string[],
defaultOutputKey?: string
) {
// eslint-disable-next-line no-instanceof/no-instanceof
if (typeof fields === "string" || fields instanceof RegExp) {
// eslint-disable-next-line no-param-reassign, @typescript-eslint/no-non-null-assertion
fields = { regex: fields, outputKeys: outputKeys!, defaultOutputKey };
}
// eslint-disable-next-line no-instanceof/no-instanceof
if (fields.regex instanceof RegExp) {
// eslint-disable-next-line no-param-reassign
fields.regex = {
pattern: fields.regex.source,
flags: fields.regex.flags,
};
}
super(fields);
this.regex =
// eslint-disable-next-line no-nested-ternary
typeof fields.regex === "string"
? new RegExp(fields.regex)
: "pattern" in fields.regex
? new RegExp(fields.regex.pattern, fields.regex.flags)
: fields.regex;
this.outputKeys = fields.outputKeys;
this.defaultOutputKey = fields.defaultOutputKey;
}
_type() {
return "regex_parser";
}
/**
* Parses the given text using the regex pattern and returns a dictionary
* with the parsed output. If the regex pattern does not match the text
* and no defaultOutputKey is provided, throws an OutputParserException.
* @param text The text to be parsed.
* @returns A dictionary with the parsed output.
*/
async parse(text: string): Promise<Record<string, string>> {
const match = text.match(this.regex);
if (match) {
return this.outputKeys.reduce((acc, key, index) => {
acc[key] = match[index + 1];
return acc;
}, {} as Record<string, string>);
}
if (this.defaultOutputKey === undefined) {
throw new OutputParserException(`Could not parse output: ${text}`, text);
}
return this.outputKeys.reduce((acc, key) => {
acc[key] = key === this.defaultOutputKey ? text : "";
return acc;
}, {} as Record<string, string>);
}
/**
* Returns a string with instructions on how the LLM output should be
* formatted to match the regex pattern.
* @returns A string with formatting instructions.
*/
getFormatInstructions(): string {
return `Your response should match the following regex: ${this.regex}`;
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/router.ts | import { z } from "zod";
import { OutputParserException } from "@langchain/core/output_parsers";
import { JsonMarkdownStructuredOutputParser } from "./structured.js";
/**
* Defines the input parameters for the RouterOutputParser class. It can
* include a default destination and an interpolation depth.
*/
export type RouterOutputParserInput = {
defaultDestination?: string;
interpolationDepth?: number;
};
/**
* A type of output parser that extends the
* JsonMarkdownStructuredOutputParser. It is used to parse the output of a
* router in LangChain. The class takes a schema and an optional
* RouterOutputParserInput object as parameters.
*/
export class RouterOutputParser<
Y extends z.ZodTypeAny
> extends JsonMarkdownStructuredOutputParser<Y> {
defaultDestination = "DEFAULT";
constructor(schema: Y, options?: RouterOutputParserInput) {
super(schema);
this.defaultDestination =
options?.defaultDestination ?? this.defaultDestination;
}
/**
* Overrides the parse method from JsonMarkdownStructuredOutputParser.
* This method takes a string as input, attempts to parse it, and returns
* the parsed text. If the destination of the parsed text matches the
* defaultDestination, the destination is set to null. If the parsing
* fails, an OutputParserException is thrown.
* @param text The text to be parsed.
* @returns The parsed text as a Promise.
*/
async parse(text: string): Promise<z.infer<Y>> {
try {
const parsedText = await super.parse(text);
if (
parsedText.destination?.toLowerCase() ===
this.defaultDestination.toLowerCase()
) {
parsedText.destination = null;
}
return parsedText;
} catch (e) {
throw new OutputParserException(
`Failed to parse. Text: "${text}". Error: ${e}`,
text
);
}
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/structured.ts | import { z } from "zod";
import {
zodToJsonSchema,
JsonSchema7Type,
JsonSchema7ArrayType,
JsonSchema7ObjectType,
JsonSchema7StringType,
JsonSchema7NumberType,
JsonSchema7NullableType,
} from "zod-to-json-schema";
import {
BaseOutputParser,
FormatInstructionsOptions,
OutputParserException,
} from "@langchain/core/output_parsers";
export type JsonMarkdownStructuredOutputParserInput = {
interpolationDepth?: number;
};
export interface JsonMarkdownFormatInstructionsOptions
extends FormatInstructionsOptions {
interpolationDepth?: number;
}
export class StructuredOutputParser<
T extends z.ZodTypeAny
> extends BaseOutputParser<z.infer<T>> {
static lc_name() {
return "StructuredOutputParser";
}
lc_namespace = ["langchain", "output_parsers", "structured"];
toJSON() {
return this.toJSONNotImplemented();
}
constructor(public schema: T) {
super(schema);
}
/**
* Creates a new StructuredOutputParser from a Zod schema.
* @param schema The Zod schema which the output should match
* @returns A new instance of StructuredOutputParser.
*/
static fromZodSchema<T extends z.ZodTypeAny>(schema: T) {
return new this(schema);
}
/**
* Creates a new StructuredOutputParser from a set of names and
* descriptions.
* @param schemas An object where each key is a name and each value is a description
* @returns A new instance of StructuredOutputParser.
*/
static fromNamesAndDescriptions<S extends { [key: string]: string }>(
schemas: S
) {
const zodSchema = z.object(
Object.fromEntries(
Object.entries(schemas).map(
([name, description]) =>
[name, z.string().describe(description)] as const
)
)
);
return new this(zodSchema);
}
/**
* Returns a markdown code snippet with a JSON object formatted according
* to the schema.
* @param options Optional. The options for formatting the instructions
* @returns A markdown code snippet with a JSON object formatted according to the schema.
*/
getFormatInstructions(): string {
return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
\`\`\`json
${JSON.stringify(zodToJsonSchema(this.schema))}
\`\`\`
`;
}
/**
* Parses the given text according to the schema.
* @param text The text to parse
* @returns The parsed output.
*/
async parse(text: string): Promise<z.infer<T>> {
try {
const json = text.includes("```")
? text.trim().split(/```(?:json)?/)[1]
: text.trim();
return await this.schema.parseAsync(JSON.parse(json));
} catch (e) {
try {
return await this.schema.parseAsync(JSON.parse(text.trim()));
} catch (e2) {
throw new OutputParserException(
`Failed to parse. Text: "${text}". Error: ${e2}`,
text
);
}
}
}
}
/**
* A specific type of `StructuredOutputParser` that parses JSON data
* formatted as a markdown code snippet.
*/
export class JsonMarkdownStructuredOutputParser<
T extends z.ZodTypeAny
> extends StructuredOutputParser<T> {
static lc_name() {
return "JsonMarkdownStructuredOutputParser";
}
getFormatInstructions(
options?: JsonMarkdownFormatInstructionsOptions
): string {
const interpolationDepth = options?.interpolationDepth ?? 1;
if (interpolationDepth < 1) {
throw new Error("f string interpolation depth must be at least 1");
}
return `Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(
zodToJsonSchema(this.schema)
)
.replaceAll("{", "{".repeat(interpolationDepth))
.replaceAll("}", "}".repeat(interpolationDepth))}\n\`\`\``;
}
private _schemaToInstruction(
schemaInput: JsonSchema7Type,
indent = 2
): string {
const schema = schemaInput as Extract<
JsonSchema7Type,
| JsonSchema7ObjectType
| JsonSchema7ArrayType
| JsonSchema7StringType
| JsonSchema7NumberType
| JsonSchema7NullableType
>;
if ("type" in schema) {
let nullable = false;
let type: string;
if (Array.isArray(schema.type)) {
const nullIdx = schema.type.findIndex((type) => type === "null");
if (nullIdx !== -1) {
nullable = true;
schema.type.splice(nullIdx, 1);
}
type = schema.type.join(" | ") as string;
} else {
type = schema.type;
}
if (schema.type === "object" && schema.properties) {
const description = schema.description
? ` // ${schema.description}`
: "";
const properties = Object.entries(schema.properties)
.map(([key, value]) => {
const isOptional = schema.required?.includes(key)
? ""
: " (optional)";
return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(
value,
indent + 2
)}${isOptional}`;
})
.join("\n");
return `{\n${properties}\n${" ".repeat(indent - 2)}}${description}`;
}
if (schema.type === "array" && schema.items) {
const description = schema.description
? ` // ${schema.description}`
: "";
return `array[\n${" ".repeat(indent)}${this._schemaToInstruction(
schema.items,
indent + 2
)}\n${" ".repeat(indent - 2)}] ${description}`;
}
const isNullable = nullable ? " (nullable)" : "";
const description = schema.description ? ` // ${schema.description}` : "";
return `${type}${description}${isNullable}`;
}
if ("anyOf" in schema) {
return schema.anyOf
.map((s) => this._schemaToInstruction(s, indent))
.join(`\n${" ".repeat(indent - 2)}`);
}
throw new Error("unsupported schema type");
}
static fromZodSchema<T extends z.ZodTypeAny>(schema: T) {
return new this<T>(schema);
}
static fromNamesAndDescriptions<S extends { [key: string]: string }>(
schemas: S
) {
const zodSchema = z.object(
Object.fromEntries(
Object.entries(schemas).map(
([name, description]) =>
[name, z.string().describe(description)] as const
)
)
);
return new this<typeof zodSchema>(zodSchema);
}
}
export interface AsymmetricStructuredOutputParserFields<
T extends z.ZodTypeAny
> {
inputSchema: T;
}
/**
* A type of `StructuredOutputParser` that handles asymmetric input and
* output schemas.
*/
export abstract class AsymmetricStructuredOutputParser<
T extends z.ZodTypeAny,
Y = unknown
> extends BaseOutputParser<Y> {
private structuredInputParser: JsonMarkdownStructuredOutputParser<T>;
constructor({ inputSchema }: AsymmetricStructuredOutputParserFields<T>) {
super(...arguments);
this.structuredInputParser = new JsonMarkdownStructuredOutputParser(
inputSchema
);
}
/**
* Processes the parsed input into the desired output format. Must be
* implemented by subclasses.
* @param input The parsed input
* @returns The processed output.
*/
abstract outputProcessor(input: z.infer<T>): Promise<Y>;
async parse(text: string): Promise<Y> {
let parsedInput;
try {
parsedInput = await this.structuredInputParser.parse(text);
} catch (e) {
throw new OutputParserException(
`Failed to parse. Text: "${text}". Error: ${e}`,
text
);
}
return this.outputProcessor(parsedInput);
}
getFormatInstructions(): string {
return this.structuredInputParser.getFormatInstructions();
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/expression.ts | import { BaseOutputParser } from "@langchain/core/output_parsers";
import { MasterHandler } from "./expression_type_handlers/factory.js";
import { ParsedType } from "./expression_type_handlers/types.js";
import { ASTParser } from "./expression_type_handlers/base.js";
/**
* We need to be able to handle the following cases:
* ExpressionStatement
* CallExpression
* Identifier | MemberExpression
* ExpressionLiterals: [
* CallExpression
* StringLiteral
* NumericLiteral
* ArrayLiteralExpression
* ExpressionLiterals
* ObjectLiteralExpression
* PropertyAssignment
* Identifier
* ExpressionLiterals
* ]
*/
export class ExpressionParser extends BaseOutputParser<ParsedType> {
lc_namespace = ["langchain", "output_parsers", "expression"];
parser: ParseFunction;
/**
* We should separate loading the parser into its own function
* because loading the grammar takes some time. If there are
* multiple concurrent parse calls, it's faster to just wait
* for building the parser once and then use it for all
* subsequent calls. See expression.test.ts for an example.
*/
async ensureParser() {
if (!this.parser) {
this.parser = await ASTParser.importASTParser();
}
}
/**
* Parses the given text. It first ensures the parser is loaded, then
* tries to parse the text. If the parsing fails, it throws an error. If
* the parsing is successful, it returns the parsed expression.
* @param text The text to be parsed.
* @returns The parsed expression
*/
async parse(text: string) {
await this.ensureParser();
try {
const program = this.parser(text);
const node = program.body;
if (!ASTParser.isExpressionStatement(node)) {
throw new Error(
`Expected ExpressionStatement, got ${(node as ExpressionNode).type}`
);
}
const { expression: expressionStatement } = node;
if (!ASTParser.isCallExpression(expressionStatement)) {
throw new Error("Expected CallExpression");
}
const masterHandler = MasterHandler.createMasterHandler();
return await masterHandler.handle(expressionStatement);
} catch (err) {
throw new Error(`Error parsing ${err}: ${text}`);
}
}
/**
* This method is currently empty, but it could be used to provide
* instructions on the format of the input text.
* @returns string
*/
getFormatInstructions(): string {
return "";
}
}
export * from "./expression_type_handlers/types.js";
export { MasterHandler } from "./expression_type_handlers/factory.js";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/index.ts | export { ListOutputParser, CommaSeparatedListOutputParser } from "./list.js";
export { RegexParser } from "./regex.js";
export {
StructuredOutputParser,
AsymmetricStructuredOutputParser,
JsonMarkdownStructuredOutputParser,
type JsonMarkdownFormatInstructionsOptions,
type JsonMarkdownStructuredOutputParserInput,
} from "./structured.js";
export { OutputFixingParser } from "./fix.js";
export { CombiningOutputParser } from "./combining.js";
export { RouterOutputParser, type RouterOutputParserInput } from "./router.js";
export { CustomListOutputParser } from "./list.js";
export {
type FunctionParameters,
OutputFunctionsParser,
JsonOutputFunctionsParser,
JsonKeyOutputFunctionsParser,
} from "../output_parsers/openai_functions.js";
export {
type ParsedToolCall,
JsonOutputToolsParser,
type JsonOutputToolsParserParams,
JsonOutputKeyToolsParser,
type JsonOutputKeyToolsParserParams,
} from "../output_parsers/openai_tools.js";
export {
HttpResponseOutputParser,
type HttpResponseOutputParserInput,
} from "./http_response.js";
export { DatetimeOutputParser } from "./datetime.js";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/datetime.ts | import {
BaseOutputParser,
OutputParserException,
} from "@langchain/core/output_parsers";
/**
* Class to parse the output of an LLM call to a date.
* @augments BaseOutputParser
*/
export class DatetimeOutputParser extends BaseOutputParser<Date> {
static lc_name() {
return "DatetimeOutputParser";
}
lc_namespace = ["langchain", "output_parsers"];
lc_serializable = true;
/**
* ISO 8601 date time standard.
*/
format = "YYYY-MM-DDTHH:mm:ssZ";
/**
* Parses the given text into a Date.
* If the parsing fails, throws an OutputParserException.
* @param text The text to parse.
* @returns A date object.
*/
async parse(text: string): Promise<Date> {
const parsedDate = new Date(text.trim());
if (Number.isNaN(parsedDate.getTime())) {
throw new OutputParserException(`Could not parse output: ${text}`, text);
}
return parsedDate;
}
/**
* Provides instructions on the expected format of the response for the
* CommaSeparatedListOutputParser.
* @returns A string containing instructions on the expected format of the response.
*/
getFormatInstructions(): string {
return [
`Your response should be a datetime string that matches the following pattern: "${this.format}".`,
`Examples: 2011-10-05T14:48:00Z, 2019-01-01T00:00:00Z, 1932-04-21T04:42:23Z`,
`Return ONLY this string, no other words!`,
].join("\n\n");
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/json.ts | export { parsePartialJson } from "@langchain/core/output_parsers";
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/prompts.ts | import { PromptTemplate } from "@langchain/core/prompts";
export const NAIVE_FIX_TEMPLATE = `Instructions:
--------------
{instructions}
--------------
Completion:
--------------
{completion}
--------------
Above, the Completion did not satisfy the constraints given in the Instructions.
Error:
--------------
{error}
--------------
Please try again. Please only respond with an answer that satisfies the constraints laid out in the Instructions:`;
export const NAIVE_FIX_PROMPT =
/* #__PURE__ */ PromptTemplate.fromTemplate(NAIVE_FIX_TEMPLATE);
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/openai_tools.ts | import { BaseLLMOutputParser } from "@langchain/core/output_parsers";
import type { ChatGeneration } from "@langchain/core/outputs";
/**
* @deprecated Import from "@langchain/core/output_parsers/openai_tools"
*/
export type ParsedToolCall = {
id?: string;
type: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
args: Record<string, any>;
/** @deprecated Use `type` instead. Will be removed in 0.2.0. */
name: string;
/** @deprecated Use `args` instead. Will be removed in 0.2.0. */
arguments: Record<string, any>; // eslint-disable-line @typescript-eslint/no-explicit-any
};
/**
* @deprecated Import from "@langchain/core/output_parsers/openai_tools"
*/
export type JsonOutputToolsParserParams = {
/** Whether to return the tool call id. */
returnId?: boolean;
};
/**
* @deprecated Import from "@langchain/core/output_parsers/openai_tools"
*/
export class JsonOutputToolsParser extends BaseLLMOutputParser<
ParsedToolCall[]
> {
static lc_name() {
return "JsonOutputToolsParser";
}
returnId = false;
lc_namespace = ["langchain", "output_parsers", "openai_tools"];
lc_serializable = true;
constructor(fields?: JsonOutputToolsParserParams) {
super(fields);
this.returnId = fields?.returnId ?? this.returnId;
}
/**
* Parses the output and returns a JSON object. If `argsOnly` is true,
* only the arguments of the function call are returned.
* @param generations The output of the LLM to parse.
* @returns A JSON object representation of the function call or its arguments.
*/
async parseResult(generations: ChatGeneration[]): Promise<ParsedToolCall[]> {
const toolCalls = generations[0].message.additional_kwargs.tool_calls;
if (!toolCalls) {
throw new Error(
`No tools_call in message ${JSON.stringify(generations)}`
);
}
const clonedToolCalls = JSON.parse(JSON.stringify(toolCalls));
const parsedToolCalls = [];
for (const toolCall of clonedToolCalls) {
if (toolCall.function !== undefined) {
// @ts-expect-error name and arguemnts are defined by Object.defineProperty
const parsedToolCall: ParsedToolCall = {
type: toolCall.function.name,
args: JSON.parse(toolCall.function.arguments),
};
if (this.returnId) {
parsedToolCall.id = toolCall.id;
}
// backward-compatibility with previous
// versions of Langchain JS, which uses `name` and `arguments`
Object.defineProperty(parsedToolCall, "name", {
get() {
return this.type;
},
});
Object.defineProperty(parsedToolCall, "arguments", {
get() {
return this.args;
},
});
parsedToolCalls.push(parsedToolCall);
}
}
return parsedToolCalls;
}
}
export type JsonOutputKeyToolsParserParams = {
keyName: string;
returnSingle?: boolean;
/** Whether to return the tool call id. */
returnId?: boolean;
};
/**
* @deprecated Import from "@langchain/core/output_parsers/openai_tools"
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export class JsonOutputKeyToolsParser extends BaseLLMOutputParser<any> {
static lc_name() {
return "JsonOutputKeyToolsParser";
}
lc_namespace = ["langchain", "output_parsers", "openai_tools"];
lc_serializable = true;
returnId = false;
/** The type of tool calls to return. */
keyName: string;
/** Whether to return only the first tool call. */
returnSingle = false;
initialParser: JsonOutputToolsParser;
constructor(params: JsonOutputKeyToolsParserParams) {
super(params);
this.keyName = params.keyName;
this.returnSingle = params.returnSingle ?? this.returnSingle;
this.initialParser = new JsonOutputToolsParser(params);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
async parseResult(generations: ChatGeneration[]): Promise<any> {
const results = await this.initialParser.parseResult(generations);
const matchingResults = results.filter(
(result) => result.type === this.keyName
);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let returnedValues: ParsedToolCall[] | Record<string, any>[] =
matchingResults;
if (!this.returnId) {
returnedValues = matchingResults.map((result) => result.args);
}
if (this.returnSingle) {
return returnedValues[0];
}
return returnedValues;
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/output_parsers/fix.ts | import type { BaseLanguageModelInterface } from "@langchain/core/language_models/base";
import { Callbacks } from "@langchain/core/callbacks/manager";
import {
BaseOutputParser,
OutputParserException,
} from "@langchain/core/output_parsers";
import { BasePromptTemplate } from "@langchain/core/prompts";
import { Runnable } from "@langchain/core/runnables";
import { LLMChain } from "../chains/llm_chain.js";
import { NAIVE_FIX_PROMPT } from "./prompts.js";
interface OutputFixingParserRetryInput {
instructions: string;
completion: string;
error: OutputParserException;
}
function isLLMChain<T>(
x: LLMChain | Runnable<OutputFixingParserRetryInput, T>
): x is LLMChain {
return (
(x as LLMChain).prompt !== undefined && (x as LLMChain).llm !== undefined
);
}
/**
* Class that extends the BaseOutputParser to handle situations where the
* initial parsing attempt fails. It contains a retryChain for retrying
* the parsing process in case of a failure.
*/
export class OutputFixingParser<T> extends BaseOutputParser<T> {
static lc_name() {
return "OutputFixingParser";
}
lc_namespace = ["langchain", "output_parsers", "fix"];
lc_serializable = true;
parser: BaseOutputParser<T>;
retryChain: LLMChain | Runnable<OutputFixingParserRetryInput, T>;
/**
* Static method to create a new instance of OutputFixingParser using a
* given language model, parser, and optional fields.
* @param llm The language model to be used.
* @param parser The parser to be used.
* @param fields Optional fields which may contain a prompt.
* @returns A new instance of OutputFixingParser.
*/
static fromLLM<T>(
llm: BaseLanguageModelInterface,
parser: BaseOutputParser<T>,
fields?: {
prompt?: BasePromptTemplate;
}
) {
const prompt = fields?.prompt ?? NAIVE_FIX_PROMPT;
const chain = new LLMChain({ llm, prompt });
return new OutputFixingParser<T>({ parser, retryChain: chain });
}
constructor({
parser,
retryChain,
}: {
parser: BaseOutputParser<T>;
retryChain: LLMChain | Runnable<OutputFixingParserRetryInput, T>;
}) {
super(...arguments);
this.parser = parser;
this.retryChain = retryChain;
}
/**
* Method to parse the completion using the parser. If the initial parsing
* fails, it uses the retryChain to attempt to fix the output and retry
* the parsing process.
* @param completion The completion to be parsed.
* @param callbacks Optional callbacks to be used during parsing.
* @returns The parsed output.
*/
async parse(completion: string, callbacks?: Callbacks) {
try {
return await this.parser.parse(completion, callbacks);
} catch (e) {
// eslint-disable-next-line no-instanceof/no-instanceof
if (e instanceof OutputParserException) {
const retryInput = {
instructions: this.parser.getFormatInstructions(),
completion,
error: e,
};
if (isLLMChain(this.retryChain)) {
const result = await this.retryChain.call(retryInput, callbacks);
const newCompletion: string = result[this.retryChain.outputKey];
return this.parser.parse(newCompletion, callbacks);
} else {
const result = await this.retryChain.invoke(retryInput, {
callbacks,
});
return result;
}
}
throw e;
}
}
/**
* Method to get the format instructions for the parser.
* @returns The format instructions for the parser.
*/
getFormatInstructions() {
return this.parser.getFormatInstructions();
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/object_literal_expression_handler.ts | import { NodeHandler, ASTParser } from "./base.js";
import { PropertyAssignmentHandler } from "./property_assignment_handler.js";
import { ObjectLiteralType, PropertyAssignmentType } from "./types.js";
/**
* Handles object literal expressions in the LangChain Expression
* Language. Extends the NodeHandler class.
*/
export class ObjectLiteralExpressionHandler extends NodeHandler {
/**
* Checks if a given node is an object expression. Returns the node if it
* is, otherwise returns false.
* @param node The node to check.
* @returns The node if it is an object expression, otherwise false.
*/
async accepts(node: ExpressionNode): Promise<ObjectExpression | boolean> {
if (ASTParser.isObjectExpression(node)) {
return node;
} else {
return false;
}
}
/**
* Processes the object expression node and returns an object of type
* ObjectLiteralType. Throws an error if the parent handler is not set.
* @param node The object expression node to process.
* @returns An object of type ObjectLiteralType.
*/
async handle(node: ObjectExpression): Promise<ObjectLiteralType> {
if (!this.parentHandler) {
throw new Error(
"ArrayLiteralExpressionHandler must have a parent handler"
);
}
const values: PropertyAssignmentType[] = [];
const { properties } = node;
for (const property of properties) {
if (ASTParser.isPropertyAssignment(property)) {
values.push(
await new PropertyAssignmentHandler(this.parentHandler).handle(
property
)
);
}
}
return { type: "object_literal", values };
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/boolean_literal_handler.ts | import { NodeHandler, ASTParser } from "./base.js";
import { BooleanLiteralType } from "./types.js";
/**
* Handler for boolean literal nodes in the abstract syntax tree (AST).
* Extends the NodeHandler class.
*/
export class BooleanLiteralHandler extends NodeHandler {
/**
* Checks if a given node is a boolean literal. If it is, the method
* returns the node; otherwise, it returns false.
* @param node The node to check.
* @returns The node if it is a boolean literal, or false otherwise.
*/
async accepts(node: ExpressionNode): Promise<BooleanLiteral | boolean> {
if (ASTParser.isBooleanLiteral(node)) {
return node;
} else {
return false;
}
}
/**
* Handles the boolean literal node. Throws an error if there is no parent
* handler. If there is a parent handler, it returns an object of type
* BooleanLiteralType which includes the type of the node
* ("boolean_literal") and the value of the boolean literal.
* @param node The boolean literal node to handle.
* @returns An object of type BooleanLiteralType representing the handled node.
*/
async handle(node: BooleanLiteral): Promise<BooleanLiteralType> {
if (!this.parentHandler) {
throw new Error(
"ArrayLiteralExpressionHandler must have a parent handler"
);
}
return {
type: "boolean_literal",
value: node.value as boolean,
};
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/factory.ts | import { NodeHandler } from "./base.js";
import { ArrayLiteralExpressionHandler } from "./array_literal_expression_handler.js";
import { BooleanLiteralHandler } from "./boolean_literal_handler.js";
import { CallExpressionHandler } from "./call_expression_handler.js";
import { NumericLiteralHandler } from "./numeric_literal_handler.js";
import { ObjectLiteralExpressionHandler } from "./object_literal_expression_handler.js";
import { PropertyAssignmentHandler } from "./property_assignment_handler.js";
import { StringLiteralHandler } from "./string_literal_handler.js";
import { IdentifierHandler } from "./identifier_handler.js";
import { MemberExpressionHandler } from "./member_expression_handler.js";
import { ParsedType } from "./types.js";
const handlers = [
ArrayLiteralExpressionHandler,
BooleanLiteralHandler,
CallExpressionHandler,
NumericLiteralHandler,
ObjectLiteralExpressionHandler,
MemberExpressionHandler,
PropertyAssignmentHandler,
StringLiteralHandler,
IdentifierHandler,
];
/**
* The MasterHandler class is responsible for managing a collection of
* node handlers in the LangChain Expression Language. Each node handler
* is capable of handling a specific type of node in the expression
* language. The MasterHandler class uses these node handlers to process
* nodes in the expression language.
*/
export class MasterHandler extends NodeHandler {
nodeHandlers: NodeHandler[] = [];
async accepts(node: ExpressionNode): Promise<ExpressionNode | boolean> {
throw new Error(`Master handler does not accept any nodes: ${node}`);
}
/**
* This method is responsible for handling a node. It iterates over the
* collection of node handlers and uses the first handler that accepts the
* node to handle it. If no handler accepts the node, the method throws an
* error.
* @param node The node to be handled.
* @returns The result of the node handling, or throws an error if no handler can handle the node.
*/
async handle(node: CallExpression): Promise<ParsedType> {
for (const handler of this.nodeHandlers) {
const accepts = await handler.accepts(node);
if (accepts) {
return handler.handle(node);
}
}
throw new Error(`No handler found for node: ${node}`);
}
/**
* This static method creates an instance of the MasterHandler class and
* initializes it with instances of all the node handlers.
* @returns An instance of the MasterHandler class.
*/
static createMasterHandler(): MasterHandler {
const masterHandler = new MasterHandler();
handlers.forEach((Handler) => {
const handlerInstance = new Handler(masterHandler);
masterHandler.nodeHandlers.push(handlerInstance);
});
return masterHandler;
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/property_assignment_handler.ts | import { NodeHandler, ASTParser } from "./base.js";
import { PropertyAssignmentType } from "./types.js";
/**
* Handler for `PropertyAssignment` nodes in an AST. Extends the
* `NodeHandler` base class.
*/
export class PropertyAssignmentHandler extends NodeHandler {
/**
* Checks if a given node is a `PropertyAssignment` and returns the node
* if true, or false otherwise.
* @param node The node to check.
* @returns The node if it is a `PropertyAssignment`, or false otherwise.
*/
async accepts(node: ExpressionNode): Promise<PropertyAssignment | boolean> {
if (ASTParser.isPropertyAssignment(node)) {
return node;
} else {
return false;
}
}
/**
* Processes a `PropertyAssignment` node. Extracts the key and value of
* the property assignment and returns an object of type
* `PropertyAssignmentType` with the extracted identifier and value.
* @param node The `PropertyAssignment` node to process.
* @returns An object of type `PropertyAssignmentType` with the extracted identifier and value.
*/
async handle(node: PropertyAssignment): Promise<PropertyAssignmentType> {
if (!this.parentHandler) {
throw new Error(
"ArrayLiteralExpressionHandler must have a parent handler"
);
}
let name;
if (ASTParser.isIdentifier(node.key)) {
name = node.key.name;
} else if (ASTParser.isStringLiteral(node.key)) {
name = node.key.value;
} else {
throw new Error("Invalid property key type");
}
if (!name) {
throw new Error("Invalid property key");
}
const identifier = (`${name}` as string).replace(
/^["'](.+(?=["']$))["']$/,
"$1"
);
const value = await this.parentHandler.handle(node.value);
return { type: "property_assignment", identifier, value };
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/call_expression_handler.ts | import { NodeHandler, ASTParser } from "./base.js";
import { CallExpressionType, MemberExpressionType } from "./types.js";
/**
* Handles call expressions in the AST parsed by the `ASTParser`. This
* class is part of the LangChain Expression Language (LCEL), a
* declarative way to compose chains together in LangChain.
*/
export class CallExpressionHandler extends NodeHandler {
/**
* Checks if a given node is a call expression. If it is, it returns the
* node; otherwise, it returns false.
* @param node The node to check.
* @returns The node if it is a call expression, or false otherwise.
*/
async accepts(node: ExpressionNode): Promise<CallExpression | boolean> {
if (ASTParser.isCallExpression(node)) {
return node;
} else {
return false;
}
}
/**
* Processes a call expression node. It checks the type of the callee (the
* function being called) and the arguments passed to it. If the callee is
* an identifier, it extracts the function name. If the callee is a member
* expression, it delegates handling to the parent handler. It also checks
* the types of the arguments and delegates their handling to the parent
* handler. The method returns an object representing the call expression,
* including the function call and its arguments.
* @param node The call expression node to process.
* @returns An object representing the call expression, including the function call and its arguments.
*/
async handle(node: CallExpression): Promise<CallExpressionType> {
function checkCallExpressionArgumentType(arg: ExpressionNode): boolean {
return [
ASTParser.isStringLiteral,
ASTParser.isNumericLiteral,
ASTParser.isBooleanLiteral,
ASTParser.isArrayExpression,
ASTParser.isObjectExpression,
ASTParser.isCallExpression,
ASTParser.isIdentifier,
].reduce((acc, func) => acc || func(arg), false);
}
if (this.parentHandler === undefined) {
throw new Error(
"ArrayLiteralExpressionHandler must have a parent handler"
);
}
const { callee } = node;
let funcCall;
if (ASTParser.isIdentifier(callee)) {
funcCall = callee.name.replace(/^["'](.+(?=["']$))["']$/, "$1");
} else if (ASTParser.isMemberExpression(callee)) {
funcCall = (await this.parentHandler.handle(
callee as MemberExpression
)) as MemberExpressionType;
} else {
throw new Error("Unknown expression type");
}
const args = await Promise.all(
node.arguments.map((arg) => {
if (!checkCallExpressionArgumentType(arg)) {
throw new Error("Unknown argument type");
}
if (!this.parentHandler) {
throw new Error("CallExpressionHandler must have a parent handler");
}
return this.parentHandler.handle(arg as ExpressionNode);
})
);
return { type: "call_expression", funcCall, args };
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/types.ts | /**
* Represents the different types of arguments that can be used in
* LangChain.
*/
export type ArgumentsType =
| IdentifierType
| StringLiteralType
| NumericLiteralType
| ArrayLiteralType
| ObjectLiteralType
| CallExpressionType
| BooleanLiteralType;
/**
* Represents the parsed types in LangChain, which can be either an
* ArgumentsType or a PropertyAssignmentType.
*/
export type ParsedType = ArgumentsType | PropertyAssignmentType;
/**
* Represents an array literal in LangChain. It has a type property set to
* 'array_literal' and a values property which is an array of
* ArgumentsType.
*/
export type ArrayLiteralType = {
type: "array_literal";
values: ArgumentsType[];
};
/**
* Represents a boolean literal in LangChain. It has a type property set
* to 'boolean_literal' and a value property which is a boolean.
*/
export type BooleanLiteralType = {
type: "boolean_literal";
value: boolean;
};
/**
* Represents a call expression in LangChain. It has a type property set
* to 'call_expression', a funcCall property which can be a string or a
* MemberExpressionType, and an optional args property which is an array
* of ArgumentsType.
*/
export type CallExpressionType = {
type: "call_expression";
funcCall: string | MemberExpressionType;
args?: ArgumentsType[];
};
/**
* Represents a numeric literal in LangChain. It has a type property set
* to 'numeric_literal' and a value property which is a number.
*/
export type NumericLiteralType = {
type: "numeric_literal";
value: number;
};
/**
* Represents an object literal in LangChain. It has a type property set
* to 'object_literal' and a values property which is an array of
* PropertyAssignmentType.
*/
export type ObjectLiteralType = {
type: "object_literal";
values: PropertyAssignmentType[];
};
/**
* Represents a member expression in LangChain. It has a type property set
* to 'member_expression', an identifier property which is a string, and a
* property property which is also a string.
*/
export type MemberExpressionType = {
type: "member_expression";
identifier: string;
property: string;
};
/**
* Represents a property assignment in LangChain. It has a type property
* set to 'property_assignment', an identifier property which is a string,
* and a value property which is an ArgumentsType.
*/
export type PropertyAssignmentType = {
type: "property_assignment";
identifier: string;
value: ArgumentsType;
};
/**
* Represents a string literal in LangChain. It has a type property set to
* 'string_literal' and a value property which is a string.
*/
export type StringLiteralType = {
type: "string_literal";
value: string;
};
/**
* Represents an identifier in LangChain. It has a type property set to
* 'identifier' and a value property which is a string.
*/
export type IdentifierType = {
type: "identifier";
value: string;
};
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/array_literal_expression_handler.ts | import { NodeHandler, ASTParser } from "./base.js";
import { ArrayLiteralType } from "./types.js";
/**
* Handles array expressions in the LangChain Expression Language (LCEL).
* It extends the NodeHandler base class, providing functionality to
* accept and handle array expressions.
*/
export class ArrayLiteralExpressionHandler extends NodeHandler {
/**
* Checks if the given node is an array expression. If it is, the method
* returns the node; otherwise, it returns false.
* @param node The ExpressionNode to check.
* @returns A Promise that resolves to either the ArrayExpression node if the node is an array expression, or false otherwise.
*/
async accepts(node: ExpressionNode): Promise<ArrayExpression | boolean> {
if (ASTParser.isArrayExpression(node)) {
return node;
} else {
return false;
}
}
/**
* Handles the given array expression node. If the handler doesn't have a
* parent handler, it throws an error. Otherwise, it returns an object
* representing the array literal.
* @param node The ArrayExpression node to handle.
* @returns A Promise that resolves to an object representing the array literal.
*/
async handle(node: ArrayExpression): Promise<ArrayLiteralType> {
if (!this.parentHandler) {
throw new Error(
"ArrayLiteralExpressionHandler must have a parent handler"
);
}
return {
type: "array_literal",
values: await Promise.all(
node.elements.map((innerNode) =>
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
this.parentHandler!.handle(innerNode as ExpressionNode)
)
),
};
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/string_literal_handler.ts | import { NodeHandler, ASTParser } from "./base.js";
import { StringLiteralType } from "./types.js";
/**
* Handler for string literal nodes in the LangChain Expression Language.
* Extends the NodeHandler base class.
*/
export class StringLiteralHandler extends NodeHandler {
/**
* Checks if a given node is a string literal. If it is, the method
* returns the node; otherwise, it returns false.
* @param node The ExpressionNode to check.
* @returns A Promise that resolves to the node if it is a StringLiteral, or false otherwise.
*/
async accepts(node: ExpressionNode): Promise<StringLiteral | boolean> {
if (ASTParser.isStringLiteral(node)) {
return node;
} else {
return false;
}
}
/**
* Processes a string literal node to extract its value. Throws an error
* if the handler does not have a parent handler.
* @param node The StringLiteral node to process.
* @returns A Promise that resolves to a StringLiteralType object representing the processed form of the node.
*/
async handle(node: StringLiteral): Promise<StringLiteralType> {
if (!this.parentHandler) {
throw new Error(
"ArrayLiteralExpressionHandler must have a parent handler"
);
}
const text = (`${node.value}` as string).replace(
/^["'](.+(?=["']$))["']$/,
"$1"
);
return { type: "string_literal", value: text };
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/member_expression_handler.ts | import { NodeHandler, ASTParser } from "./base.js";
import { MemberExpressionType } from "./types.js";
/**
* Handles member expressions in the LangChain Expression Language (LCEL).
* Extends the NodeHandler base class.
*/
export class MemberExpressionHandler extends NodeHandler {
/**
* Checks if a given node is a member expression. If it is, the method
* returns the node; otherwise, it returns false.
* @param node The node to check.
* @returns The node if it is a member expression, or false otherwise.
*/
async accepts(node: ExpressionNode): Promise<MemberExpression | boolean> {
if (ASTParser.isMemberExpression(node)) {
return node;
} else {
return false;
}
}
/**
* Processes a member expression node. It extracts the object and property
* from the node, validates their types, and returns an object with the
* type of the expression, the identifier, and the property.
* @param node The member expression node to process.
* @returns An object with the type of the expression, the identifier, and the property.
*/
async handle(node: MemberExpression): Promise<MemberExpressionType> {
if (!this.parentHandler) {
throw new Error(
"ArrayLiteralExpressionHandler must have a parent handler"
);
}
const { object, property } = node;
let prop: string;
if (ASTParser.isIdentifier(property)) {
prop = property.name.replace(/^["'](.+(?=["']$))["']$/, "$1");
} else if (ASTParser.isStringLiteral(property)) {
prop = (`${property.value}` as string).replace(
/^["'](.+(?=["']$))["']$/,
"$1"
);
} else {
throw new Error("Invalid property key type");
}
let identifier: string;
if (ASTParser.isIdentifier(object)) {
identifier = object.name.replace(/^["'](.+(?=["']$))["']$/, "$1");
} else if (ASTParser.isStringLiteral(object)) {
identifier = (`${object.value}` as string).replace(
/^["'](.+(?=["']$))["']$/,
"$1"
);
} else {
throw new Error("Invalid object type");
}
if (object.type !== "Identifier" && object.type !== "StringLiteral") {
throw new Error("ArrayExpression is not supported");
}
return { type: "member_expression", identifier, property: prop };
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/base.ts | import { GRAMMAR } from "./grammar/parser_grammar.js";
/**
* Abstract class for handling nodes in an expression language. Subclasses
* must implement the `accepts` and `handle` methods.
*/
export abstract class NodeHandler {
constructor(protected parentHandler?: NodeHandler) {}
/**
* Determines whether the given node is acceptable.
* @param node The node to be checked.
* @returns A Promise that resolves to either the node itself or a boolean indicating whether the node is acceptable.
*/
abstract accepts(node: ExpressionNode): Promise<ExpressionNode | boolean>;
/**
* Handles the given node. The specifics of how the node is handled are
* determined by the subclass implementation.
* @param node The node to be handled.
* @returns A Promise that resolves to the result of handling the node.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
abstract handle(node: ExpressionNode): Promise<any>;
}
/**
* Utility class for parsing Abstract Syntax Trees (ASTs). Contains
* methods for identifying the type of a given node and a method for
* importing and generating a parser using the Peggy library.
*/
export class ASTParser {
static astParseInstance: ParseFunction;
/**
* Imports and generates a parser using the Peggy library.
* @returns A Promise that resolves to the parser instance.
*/
static async importASTParser() {
try {
if (!ASTParser.astParseInstance) {
const { default: peggy } = await import("peggy");
const parser = peggy.generate(GRAMMAR);
const { parse } = parser;
ASTParser.astParseInstance = parse as ParseFunction;
}
return ASTParser.astParseInstance;
} catch (e) {
throw new Error(
`Failed to import peggy. Please install peggy (i.e. "npm install peggy" or "yarn add peggy").`
);
}
}
/**
* Checks if the given node is a Program node.
* @param node The node to be checked.
* @returns A boolean indicating whether the node is a Program node.
*/
static isProgram(node: ExpressionNode): node is Program {
return node.type === "Program";
}
/**
* Checks if the given node is an ExpressionStatement node.
* @param node The node to be checked.
* @returns A boolean indicating whether the node is an ExpressionStatement node.
*/
static isExpressionStatement(
node: ExpressionNode
): node is ExpressionStatement {
return node.type === "ExpressionStatement";
}
/**
* Checks if the given node is a CallExpression node.
* @param node The node to be checked.
* @returns A boolean indicating whether the node is a CallExpression node.
*/
static isCallExpression(node: ExpressionNode): node is CallExpression {
return node.type === "CallExpression";
}
/**
* Checks if the given node is a StringLiteral node.
* @param node The node to be checked.
* @returns A boolean indicating whether the node is a StringLiteral node.
*/
static isStringLiteral(node: ExpressionNode): node is StringLiteral {
return node.type === "StringLiteral" && typeof node.value === "string";
}
/**
* Checks if the given node is a NumericLiteral node.
* @param node The node to be checked.
* @returns A boolean indicating whether the node is a NumericLiteral node.
*/
static isNumericLiteral(node: ExpressionNode): node is NumericLiteral {
return node.type === "NumericLiteral" && typeof node.value === "number";
}
/**
* Checks if the given node is a BooleanLiteral node.
* @param node The node to be checked.
* @returns A boolean indicating whether the node is a BooleanLiteral node.
*/
static isBooleanLiteral(node: ExpressionNode): node is BooleanLiteral {
return node.type === "BooleanLiteral" && typeof node.value === "boolean";
}
/**
* Checks if the given node is an Identifier node.
* @param node The node to be checked.
* @returns A boolean indicating whether the node is an Identifier node.
*/
static isIdentifier(node: ExpressionNode): node is Identifier {
return node.type === "Identifier";
}
/**
* Checks if the given node is an ObjectExpression node.
* @param node The node to be checked.
* @returns A boolean indicating whether the node is an ObjectExpression node.
*/
static isObjectExpression(node: ExpressionNode): node is ObjectExpression {
return node.type === "ObjectExpression";
}
/**
* Checks if the given node is an ArrayExpression node.
* @param node The node to be checked.
* @returns A boolean indicating whether the node is an ArrayExpression node.
*/
static isArrayExpression(node: ExpressionNode): node is ArrayExpression {
return node.type === "ArrayExpression";
}
/**
* Checks if the given node is a PropertyAssignment node.
* @param node The node to be checked.
* @returns A boolean indicating whether the node is a PropertyAssignment node.
*/
static isPropertyAssignment(
node: ExpressionNode
): node is PropertyAssignment {
return node.type === "PropertyAssignment";
}
/**
* Checks if the given node is a MemberExpression node.
* @param node The node to be checked.
* @returns A boolean indicating whether the node is a MemberExpression node.
*/
static isMemberExpression(node: ExpressionNode): node is MemberExpression {
return node.type === "MemberExpression";
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/numeric_literal_handler.ts | import { NodeHandler, ASTParser } from "./base.js";
import { NumericLiteralType } from "./types.js";
/**
* Handler for numeric literal nodes in an abstract syntax tree (AST).
* Extends the NodeHandler class.
*/
export class NumericLiteralHandler extends NodeHandler {
/**
* Checks if a given node is a numeric literal. If it is, the method
* returns the node; otherwise, it returns false.
* @param node The node to check.
* @returns A Promise that resolves to the node if it is a numeric literal, or false otherwise.
*/
async accepts(node: ExpressionNode): Promise<NumericLiteral | boolean> {
if (ASTParser.isNumericLiteral(node)) {
return node;
} else {
return false;
}
}
/**
* Processes a numeric literal node and returns a NumericLiteralType
* object representing it.
* @param node The numeric literal node to process.
* @returns A Promise that resolves to a NumericLiteralType object representing the numeric literal node.
*/
async handle(node: NumericLiteral): Promise<NumericLiteralType> {
if (!this.parentHandler) {
throw new Error(
"ArrayLiteralExpressionHandler must have a parent handler"
);
}
return {
type: "numeric_literal",
value: Number(node.value),
};
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/identifier_handler.ts | import { NodeHandler, ASTParser } from "./base.js";
import { IdentifierType } from "./types.js";
/**
* Handles identifiers in the LangChain Expression Language. Extends the
* NodeHandler class.
*/
export class IdentifierHandler extends NodeHandler {
/**
* Checks if a given node is an identifier. If it is, it returns the node;
* otherwise, it returns false.
* @param node The node to check.
* @returns The node if it is an identifier, or false otherwise.
*/
async accepts(node: ExpressionNode): Promise<Identifier | boolean> {
if (ASTParser.isIdentifier(node)) {
return node;
} else {
return false;
}
}
/**
* Processes the identifier node. If the handler does not have a parent
* handler, it throws an error. Otherwise, it extracts the name of the
* identifier, removes any enclosing quotes, and returns an object of type
* IdentifierType with the type set to "identifier" and the value set to
* the extracted name.
* @param node The identifier node to process.
* @returns An object of type IdentifierType with the type set to "identifier" and the value set to the extracted name.
*/
async handle(node: Identifier): Promise<IdentifierType> {
if (!this.parentHandler) {
throw new Error(
"ArrayLiteralExpressionHandler must have a parent handler"
);
}
const text = node.name.replace(/^["'](.+(?=["']$))["']$/, "$1");
return { type: "identifier", value: text };
}
}
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers | lc_public_repos/langchainjs/langchain/src/output_parsers/expression_type_handlers/grammar/parser_grammar.ts | /**
* Here's the main parser for our expression parser. It's a pared down
* Javascript parser with a whole lot of rules removed, leaving only
* rules for parsing literals (i.e. string literal,numeric literal,
* boolean literal, array literal, object literal and null literal),
* identifiers, and expressions (i.e. call expression, member expression,
* array expression and object expression).
*
* For more information see:
* https://peggyjs.org/documentation.html
* https://github.com/peggyjs/peggy/blob/main/examples/javascript.pegjs
*/
export const GRAMMAR = `{{
var TYPES_TO_PROPERTY_NAMES = {
CallExpression: "callee",
MemberExpression: "object",
};
function extractOptional(optional, index) {
return optional ? optional[index] : null;
};
function extractList(list, index) {
return list.map(function(element) { return element[index]; });
};
function buildList(head, tail, index) {
return [head].concat(extractList(tail, index));
};
function optionalList(value) {
return value !== null ? value : [];
};
}}
Start
= __ program:Program __ { return program; };
SourceCharacter
= .;
WhiteSpace
= "\\t"
/ "\\v"
/ "\\f"
/ " "
/ "\\u00A0"
/ "\\uFEFF";
Identifier
= !ReservedWord name:IdentifierName { return name; };
IdentifierName
= head:IdentifierStart tail:IdentifierPart* {
return {
type: "Identifier",
name: head + tail.join("")
};
};
IdentifierStart
= UnicodeLetter
/ "$"
/ "_";
IdentifierPart
= IdentifierStart
/ Nd
/ "\\u200C"
/ "\\u200D";
UnicodeLetter
= Lu
/ Ll;
ReservedWord
= NullToken
/ TrueToken
/ FalseToken;
Literal
= NullLiteral
/ BooleanLiteral
/ NumericLiteral
/ StringLiteral;
NullLiteral
= NullToken { return { type: "NullLiteral", value: null }; };
BooleanLiteral
= TrueToken { return { type: "BooleanLiteral", value: true }; }
/ FalseToken { return { type: "BooleanLiteral", value: false }; };
NumericLiteral
= literal:DecimalLiteral !(IdentifierStart / DecimalDigit) {
return literal;
};
DecimalLiteral
= DecimalIntegerLiteral "." DecimalDigit* {
return { type: "NumericLiteral", value: parseFloat(text()) };
}
/ "." DecimalDigit+ {
return { type: "NumericLiteral", value: parseFloat(text()) };
}
/ DecimalIntegerLiteral {
return { type: "NumericLiteral", value: parseFloat(text()) };
};
DecimalIntegerLiteral
= "0"
/ NonZeroDigit DecimalDigit*;
DecimalDigit
= [0-9];
NonZeroDigit
= [1-9];
StringLiteral
= '"' chars:DoubleStringCharacter* '"' {
return { type: "StringLiteral", value: chars.join("") };
}
/ "'" chars:SingleStringCharacter* "'" {
return { type: "StringLiteral", value: chars.join("") };
};
DoubleStringCharacter
= !('"' / "\\\\") SourceCharacter { return text(); };
SingleStringCharacter
= !("'" / "\\\\") SourceCharacter { return text(); };
SingleEscapeCharacter
= "'"
/ '"';
Ll = [a-z];
Lu = [A-Z];
Nd = [0-9];
FalseToken = "false" !IdentifierPart;
TrueToken = "true" !IdentifierPart;
NullToken = "null" !IdentifierPart;
__ = WhiteSpace*;
PrimaryExpression
= Identifier
/ Literal
/ ArrayExpression
/ ObjectExpression
/ "(" __ expression:Expression __ ")" { return expression; };
ArrayExpression
= "[" __ "]" { return { type: "ArrayExpression", elements: [] }; }
/ "[" __ elements:ElementList __ "]" {
return {
type: "ArrayExpression",
elements: elements
};
};
ElementList
= head:(
element:Expression {
return element;
}
)
tail:(
__ "," __ element:Expression {
return element;
}
)*
{ return Array.prototype.concat.apply(head, tail); };
ObjectExpression
= "{" __ "}" { return { type: "ObjectExpression", properties: [] }; }
/ "{" __ properties:PropertyNameAndValueList __ "}" {
return { type: "ObjectExpression", properties: properties };
}
/ "{" __ properties:PropertyNameAndValueList __ "," __ "}" {
return { type: "ObjectExpression", properties: properties };
};
PropertyNameAndValueList
= head:PropertyAssignment tail:(__ "," __ PropertyAssignment)* {
return buildList(head, tail, 3);
};
PropertyAssignment
= key:PropertyName __ ":" __ value:Expression {
return { type: "PropertyAssignment", key: key, value: value, kind: "init" };
};
PropertyName
= IdentifierName
/ StringLiteral
/ NumericLiteral;
Node
= ArrayExpression
/ BooleanLiteral
/ CallExpression
/ Identifier
/ MemberExpression
/ NumericLiteral
/ ObjectExpression
/ PropertyAssignment
/ StringLiteral
MemberExpression
= head:(PrimaryExpression)
tail:(
__ "[" __ property:Expression __ "]" {
return { property: property, computed: true };
}
/ __ "." __ property:IdentifierName {
return { property: property, computed: false };
}
)*
{
return tail.reduce(function(result, element) {
return {
type: "MemberExpression",
object: result,
property: element.property,
computed: element.computed
};
}, head);
};
CallExpression
= head:(
callee:MemberExpression __ args:Arguments {
return { type: "CallExpression", callee: callee, arguments: args };
}
)
tail:(
__ args:Arguments {
return { type: "CallExpression", arguments: args };
}
/ __ "[" __ property:Expression __ "]" {
return {
type: "MemberExpression",
property: property,
computed: true
};
}
/ __ "." __ property:IdentifierName {
return {
type: "MemberExpression",
property: property,
computed: false
};
}
)*
{
return tail.reduce(function(result, element) {
element[TYPES_TO_PROPERTY_NAMES[element.type]] = result;
return element;
}, head);
};
Arguments
= "(" __ args:(ArgumentList __)? ")" {
return optionalList(extractOptional(args, 0));
};
ArgumentList
= head:Expression tail:(__ "," __ Expression)* {
return buildList(head, tail, 3);
};
Expression
= CallExpression
/ MemberExpression;
ExpressionStatement
= expression:Expression {
return {
type: "ExpressionStatement",
expression: expression
};
};
Program
= exp:ExpressionStatement {
return {
type: "Program",
body: exp
};
};`;
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/tests/openai_tools.int.test.ts | /* eslint-disable @typescript-eslint/no-explicit-any */
import { expect, test } from "@jest/globals";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { JsonOutputToolsParser } from "../openai_tools.js";
const schema = z.object({
setup: z.string().describe("The setup for the joke"),
punchline: z.string().describe("The punchline to the joke"),
});
test("Extraction", async () => {
const prompt = ChatPromptTemplate.fromTemplate(
`tell me two jokes about {foo}`
);
const model = new ChatOpenAI({
modelName: "gpt-3.5-turbo-1106",
temperature: 0,
}).bind({
tools: [
{
type: "function",
function: {
name: "joke",
description: "A joke",
parameters: zodToJsonSchema(schema),
},
},
],
});
const parser = new JsonOutputToolsParser();
const chain = prompt.pipe(model).pipe(parser);
const res = await chain.invoke({
foo: "bears",
});
// console.log(res);
expect(res.length).toBe(2);
});
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/tests/list.test.ts | import { test, expect } from "@jest/globals";
import {
OutputParserException,
CommaSeparatedListOutputParser,
CustomListOutputParser,
} from "@langchain/core/output_parsers";
test("CommaSeparatedListOutputParser", async () => {
const parser = new CommaSeparatedListOutputParser();
expect(await parser.parse("hello, bye")).toEqual(["hello", "bye"]);
expect(await parser.parse("hello,bye")).toEqual(["hello", "bye"]);
expect(await parser.parse("hello")).toEqual(["hello"]);
});
test("CustomListOutputParser", async () => {
const parser1 = new CustomListOutputParser({ length: 3, separator: ";" });
expect(await parser1.parse("a; b;c")).toEqual(["a", "b", "c"]);
await expect(() => parser1.parse("a; b c")).rejects.toThrow(
OutputParserException
);
await expect(() => parser1.parse("a; b; c; d")).rejects.toThrow(
OutputParserException
);
const parser2 = new CustomListOutputParser({ separator: "\n" });
expect(await parser2.parse("a\nb\nc\nd")).toEqual(["a", "b", "c", "d"]);
const parser3 = new CustomListOutputParser({ length: 8 });
expect(await parser3.parse("a,b,c,d,e,f,g,h")).toEqual([
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
]);
});
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/tests/datetime.test.ts | import { test, expect } from "@jest/globals";
import { OutputParserException } from "@langchain/core/output_parsers";
import { DatetimeOutputParser } from "../datetime.js";
test("DatetimeOutputParser", async () => {
const parser = new DatetimeOutputParser();
const currentDate = new Date();
const currentDateStr = currentDate.toISOString();
expect(await parser.parse(currentDateStr)).toEqual(currentDate);
const isoDateStr = "05 October 2011 14:48Z";
const isoDate = new Date(Date.UTC(2011, 9, 5, 14, 48));
expect(await parser.parse(isoDateStr)).toEqual(isoDate);
const invalidDateStr = "Vespertine was released by Bjork.";
await expect(() => parser.parse(invalidDateStr)).rejects.toThrow(
OutputParserException
);
});
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/tests/structured.test.ts | import { expect, test } from "@jest/globals";
import { z } from "zod";
import { StructuredOutputParser } from "../structured.js";
test("StructuredOutputParser handles valid JSON wrapped in triple backticks", async () => {
const parser = StructuredOutputParser.fromZodSchema(
z.object({
name: z.string().describe("Human name"),
age: z.number().describe("Human age"),
})
);
const text = '```json\n{"name": "John Doe", "age": 30}```';
const result = await parser.parse(text);
expect(result).toHaveProperty("name", "John Doe");
expect(result).toHaveProperty("age", 30);
});
test("StructuredOutputParser handles JSON without triple backticks", async () => {
const parser = StructuredOutputParser.fromZodSchema(
z.object({
name: z.string().describe("Human name"),
age: z.number().describe("Human age"),
})
);
const text = '{"name": "John Doe", "age": 30}';
const result = await parser.parse(text);
expect(result).toHaveProperty("name", "John Doe");
expect(result).toHaveProperty("age", 30);
});
test("StructuredOutputParser throws error for invalid JSON wrapped in triple backticks", async () => {
const parser = StructuredOutputParser.fromZodSchema(
z.object({
name: z.string().describe("Human name"),
age: z.number().describe("Human age"),
})
);
// Invalid JSON
const text = '```json\n{"name": "John Doe", "age": }```';
await expect(parser.parse(text)).rejects.toThrow("Failed to parse");
});
test("StructuredOutputParser throws error for normal text without triple backticks", async () => {
const parser = StructuredOutputParser.fromZodSchema(
z.object({
name: z.string().describe("Human name"),
age: z.number().describe("Human age"),
})
);
// Invalid JSON
const text = "This is just a plain text without JSON.";
await expect(parser.parse(text)).rejects.toThrow("Failed to parse");
});
test("StructuredOutputParser handles JSON with backticks inside text but not at the start", async () => {
const parser = StructuredOutputParser.fromZodSchema(
z.object({
name: z.string().describe("Human name"),
age: z.number().describe("Human age"),
})
);
const text = 'Some random text ```json\n{"name": "John Doe", "age": 30}```';
const result = await parser.parse(text);
expect(result).toHaveProperty("name", "John Doe");
expect(result).toHaveProperty("age", 30);
});
test("StructuredOutputParser handles JSON with backticks inside JSON", async () => {
const parser = StructuredOutputParser.fromZodSchema(
z.object({
name: z.string().describe("Human name"),
age: z.number().describe("Human age"),
})
);
const text = '{"name": "John ```Doe```", "age": 30}';
const result = await parser.parse(text);
expect(result).toHaveProperty("name", "John ```Doe```");
expect(result).toHaveProperty("age", 30);
});
test("StructuredOutputParser throws error for JSON with backticks both inside and outside the JSON", async () => {
const parser = StructuredOutputParser.fromZodSchema(
z.object({
name: z.string().describe("Human name"),
age: z.number().describe("Human age"),
})
);
const text =
'Some random text ```json\n{"name": "John ```Doe```", "age": 30}```';
await expect(parser.parse(text)).rejects.toThrow("Failed to parse");
});
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/tests/expression.test.ts | import { test } from "@jest/globals";
import { ExpressionParser } from "../expression.js";
const correctExps = [
{ type: "call_expression", funcCall: "hello", args: [] },
{
type: "call_expression",
funcCall: "hello",
args: [{ type: "string_literal", value: "world" }],
},
{
type: "call_expression",
funcCall: "hello",
args: [
{ type: "string_literal", value: "world" },
{ type: "string_literal", value: "hello" },
],
},
{
type: "call_expression",
funcCall: "hello",
args: [
{ type: "string_literal", value: "world" },
{ type: "string_literal", value: "hello" },
{
type: "array_literal",
values: [
{ type: "string_literal", value: "hello" },
{ type: "string_literal", value: "world" },
{ type: "numeric_literal", value: 1 },
{ type: "numeric_literal", value: 2.1 },
{ type: "numeric_literal", value: 3 },
],
},
],
},
{
type: "call_expression",
funcCall: "hello",
args: [
{ type: "string_literal", value: "world" },
{ type: "string_literal", value: "hello" },
{
type: "array_literal",
values: [
{ type: "string_literal", value: "hello" },
{ type: "string_literal", value: "world" },
{ type: "numeric_literal", value: 1 },
{ type: "numeric_literal", value: 2.1 },
{ type: "numeric_literal", value: 3 },
],
},
{
type: "object_literal",
values: [
{
type: "property_assignment",
identifier: "hello",
value: { type: "string_literal", value: "world" },
},
],
},
],
},
{
type: "call_expression",
funcCall: "hello",
args: [
{ type: "string_literal", value: "world" },
{ type: "string_literal", value: "hello" },
{
type: "array_literal",
values: [
{ type: "string_literal", value: "hello" },
{ type: "string_literal", value: "world" },
{ type: "numeric_literal", value: 1 },
{ type: "numeric_literal", value: 2.1 },
{ type: "numeric_literal", value: 3 },
],
},
{
type: "object_literal",
values: [
{
type: "property_assignment",
identifier: "hello",
value: { type: "string_literal", value: "world" },
},
],
},
{ type: "numeric_literal", value: 1 },
{ type: "numeric_literal", value: 2.1 },
{ type: "numeric_literal", value: 3 },
],
},
{
type: "call_expression",
funcCall: "hello",
args: [
{ type: "string_literal", value: "world" },
{ type: "string_literal", value: "hello" },
{
type: "array_literal",
values: [
{ type: "string_literal", value: "hello" },
{ type: "string_literal", value: "world" },
{ type: "numeric_literal", value: 1 },
{ type: "numeric_literal", value: 2.1 },
{ type: "numeric_literal", value: 3 },
],
},
{
type: "object_literal",
values: [
{
type: "property_assignment",
identifier: "hello",
value: { type: "string_literal", value: "world" },
},
],
},
{ type: "numeric_literal", value: 1 },
{ type: "numeric_literal", value: 2.1 },
{ type: "numeric_literal", value: 3 },
{
type: "call_expression",
funcCall: "world",
args: [
{ type: "string_literal", value: "hello" },
{ type: "string_literal", value: "world" },
{
type: "array_literal",
values: [
{
type: "object_literal",
values: [
{
type: "property_assignment",
identifier: "hello",
value: { type: "string_literal", value: "world" },
},
],
},
{
type: "object_literal",
values: [
{
type: "property_assignment",
identifier: "hello",
value: {
type: "call_expression",
funcCall: "hello",
args: [{ type: "string_literal", value: "world" }],
},
},
],
},
],
},
],
},
],
},
{
type: "call_expression",
funcCall: {
type: "member_expression",
identifier: "hello",
property: "world",
},
args: [
{ type: "string_literal", value: "hello" },
{ type: "string_literal", value: "world" },
{
type: "array_literal",
values: [
{ type: "string_literal", value: "hello" },
{ type: "string_literal", value: "world" },
],
},
{
type: "object_literal",
values: [
{
type: "property_assignment",
identifier: "hello",
value: { type: "string_literal", value: "world" },
},
],
},
],
},
{
type: "call_expression",
funcCall: {
type: "member_expression",
identifier: "hello",
property: "world",
},
args: [
{ type: "string_literal", value: "hello" },
{ type: "string_literal", value: "world" },
{
type: "array_literal",
values: [
{ type: "string_literal", value: "hello" },
{ type: "string_literal", value: "world" },
],
},
],
},
{
type: "call_expression",
funcCall: "a",
args: [
{ type: "identifier", value: "b" },
{
type: "call_expression",
funcCall: "c",
args: [
{ type: "identifier", value: "d" },
{ type: "identifier", value: "e" },
{
type: "array_literal",
values: [
{ type: "identifier", value: "f" },
{ type: "identifier", value: "g" },
],
},
{
type: "object_literal",
values: [
{
type: "property_assignment",
identifier: "h",
value: { type: "identifier", value: "i" },
},
],
},
],
},
],
},
{
type: "call_expression",
funcCall: "and",
args: [
{
type: "call_expression",
funcCall: "in",
args: [
{ type: "string_literal", value: "a" },
{
type: "array_literal",
values: [
{ type: "string_literal", value: "a" },
{ type: "string_literal", value: "b" },
{ type: "string_literal", value: "c" },
],
},
],
},
{
type: "call_expression",
funcCall: "eq",
args: [
{ type: "string_literal", value: "a" },
{ type: "string_literal", value: "b" },
],
},
],
},
{
type: "call_expression",
funcCall: "with",
args: [
{
type: "call_expression",
funcCall: "const",
args: [
{ type: "string_literal", value: "a" },
{
type: "array_literal",
values: [
{ type: "string_literal", value: "a" },
{ type: "string_literal", value: "b" },
{ type: "string_literal", value: "c" },
],
},
],
},
{
type: "call_expression",
funcCall: "eq",
args: [
{ type: "string_literal", value: "a" },
{ type: "string_literal", value: "b" },
{ type: "boolean_literal", value: true },
],
},
],
},
];
test("ExpressionParser multiple expressions test", async () => {
const parser = new ExpressionParser();
await parser.ensureParser();
const expressions = [
`hello()`,
`hello("world")`,
`hello("world", "hello")`,
`hello("world", "hello", ["hello", "world", 1, 2.1, 3])`,
`hello("world", "hello", ["hello", "world", 1, 2.1, 3], { hello: "world" })`,
`hello("world", "hello", ["hello", "world", 1, 2.1, 3], { hello: "world" }, 1, 2.1, 3)`,
`hello("world", "hello", ["hello", "world", 1, 2.1, 3], { hello: "world" }, 1, 2.1, 3, world("hello", "world", [{hello: "world"}, {"hello": hello("world")}]))`,
`hello.world("hello", "world", ["hello", "world"], {"hello": "world"})`,
`hello["world"]("hello", "world", ["hello", "world"])`,
`a(b, c(d, e, [f, g], {h: i}))`,
`and(in("a", ["a", "b", "c"]), eq("a", "b"))`,
`with(const("a", ["a", "b", "c"]), eq("a", "b", true))`,
];
const badExpressions = [
`hello(`,
`hello("world", ["hello", "world", 1, 2, 3 { hello: "world" })`,
`hello("world", ["hello, "world", { hello: "world" )`,
`l:::"""(}))))++===/...`,
];
const parsedPromise = expressions.map((expression) =>
parser.parse(expression)
);
const badExpressionsPromise = badExpressions.map((expression) =>
parser.parse(expression).catch(() => "bad")
);
await Promise.allSettled(badExpressionsPromise).then((errors) => {
errors.forEach((err) => {
if (err.status === "fulfilled") {
expect(err.value).toBe("bad");
}
});
});
const parsed = await Promise.all(parsedPromise);
parsed.forEach((expression, index) => {
expect(expression).toMatchObject(correctExps[index]);
});
});
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/tests/openai_functions.int.test.ts | /* eslint-disable @typescript-eslint/no-explicit-any */
import { expect, test } from "@jest/globals";
import { z } from "zod";
import { zodToJsonSchema } from "zod-to-json-schema";
import { Operation, applyPatch } from "@langchain/core/utils/json_patch";
import { ChatOpenAI } from "@langchain/openai";
import { ChatPromptTemplate } from "@langchain/core/prompts";
import { JsonOutputFunctionsParser } from "../openai_functions.js";
import { HttpResponseOutputParser } from "../http_response.js";
const schema = z.object({
setup: z.string().describe("The setup for the joke"),
punchline: z.string().describe("The punchline to the joke"),
});
const modelParams = {
functions: [
{
name: "joke",
description: "A joke",
parameters: zodToJsonSchema(schema),
},
],
function_call: { name: "joke" },
};
test("Streaming JSON patch", async () => {
const prompt = ChatPromptTemplate.fromTemplate(
`tell me a long joke about {foo}`
);
const model = new ChatOpenAI({
temperature: 0,
}).bind(modelParams);
const parser = new JsonOutputFunctionsParser({ diff: true });
const chain = prompt.pipe(model).pipe(parser);
const stream = await chain.stream({
foo: "bears",
});
const chunks = [];
let aggregate: any = {};
for await (const chunk of stream) {
// console.log(chunk);
chunks.push(chunk);
aggregate = applyPatch(aggregate, chunk as Operation[]).newDocument;
}
expect(chunks.length).toBeGreaterThan(1);
// console.log(aggregate);
expect(aggregate.setup.length).toBeGreaterThan(1);
expect(aggregate.punchline.length).toBeGreaterThan(1);
});
test("Streaming JSON patch with an event stream output parser", async () => {
const prompt = ChatPromptTemplate.fromTemplate(
`tell me a long joke about {foo}`
);
const model = new ChatOpenAI({
temperature: 0,
}).bind(modelParams);
const jsonParser = new JsonOutputFunctionsParser({ diff: true });
const parser = new HttpResponseOutputParser({
outputParser: jsonParser,
contentType: "text/event-stream",
});
const chain = prompt.pipe(model).pipe(parser);
const stream = await chain.stream({
foo: "bears",
});
const chunks = [];
// @eslint-disable-next-line/@typescript-eslint/ban-ts-comment
// @ts-expect-error unused var
const decoder = new TextDecoder();
for await (const chunk of stream) {
// console.log(decoder.decode(chunk));
chunks.push(chunk);
}
expect(chunks.length).toBeGreaterThan(1);
});
test("Streaming aggregated JSON", async () => {
const prompt = ChatPromptTemplate.fromTemplate(
`tell me a long joke about {foo}`
);
const model = new ChatOpenAI({
temperature: 0,
}).bind(modelParams);
const parser = new JsonOutputFunctionsParser();
const chain = prompt.pipe(model).pipe(parser);
const stream = await chain.stream({
foo: "bears",
});
const chunks = [];
let aggregate: any = {};
for await (const chunk of stream) {
// console.log(chunk);
chunks.push(chunk);
aggregate = chunk;
}
expect(chunks.length).toBeGreaterThan(1);
// console.log(aggregate);
expect(aggregate.setup.length).toBeGreaterThan(1);
expect(aggregate.punchline.length).toBeGreaterThan(1);
});
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/tests/structured.int.test.ts | import { expect, test } from "@jest/globals";
import { z } from "zod";
import { OpenAI, ChatOpenAI } from "@langchain/openai";
import {
ChatPromptTemplate,
PromptTemplate,
SystemMessagePromptTemplate,
} from "@langchain/core/prompts";
import { LLMChain } from "../../chains/index.js";
import { StructuredOutputParser } from "../structured.js";
test("StructuredOutputParser deals special chars in prompt with llm model", async () => {
const model = new OpenAI({
temperature: 0,
});
const parser = StructuredOutputParser.fromNamesAndDescriptions({
question1: "a very on-topic question",
question2: "a super weird question",
question3: "an on-topic, but slightly creative",
});
const prompt = new PromptTemplate({
template: "context:\n{context}\n---{format_instructions}",
inputVariables: ["context"],
partialVariables: {
format_instructions: parser.getFormatInstructions(),
},
});
const chain = new LLMChain({
llm: model,
prompt,
outputParser: parser,
outputKey: "questions",
});
const result = await chain.call({
context: `The U2 ur-myth begins in 1976, when drummer Larry Mullen wanted to form a band.
He picked four school friends from Mount Temple Comprehensive School in Dublin.
“Larry formed U2,” says Paul McGuinness, U2’s manager from the beginning. “He
auditioned the other three and he chose them. The first name of U2 was the Larry
Mullen band,” McGuinness laughs. “And he never lets us forget it.” `,
});
// console.log("response", result);
expect(result.questions).toHaveProperty("question1");
expect(result.questions).toHaveProperty("question2");
expect(result.questions).toHaveProperty("question3");
});
test("StructuredOutputParser deals special chars in prompt with chat model", async () => {
const model = new ChatOpenAI({
temperature: 0,
});
const parser = StructuredOutputParser.fromNamesAndDescriptions({
question1: "a very on-topic question",
question2: "a super weird question",
question3: "an on-topic, but slightly creative",
});
const prompt = new ChatPromptTemplate({
promptMessages: [
SystemMessagePromptTemplate.fromTemplate("context:\n{context}\n---"),
SystemMessagePromptTemplate.fromTemplate(`{format_instructions}`),
],
inputVariables: ["context"],
partialVariables: {
format_instructions: parser.getFormatInstructions(),
},
});
const chain = new LLMChain({
llm: model,
prompt,
outputParser: parser,
outputKey: "questions",
});
const result = await chain.call({
context: `The U2 ur-myth begins in 1976, when drummer Larry Mullen wanted to form a band.
He picked four school friends from Mount Temple Comprehensive School in Dublin.
“Larry formed U2,” says Paul McGuinness, U2’s manager from the beginning. “He
auditioned the other three and he chose them. The first name of U2 was the Larry
Mullen band,” McGuinness laughs. “And he never lets us forget it.” `,
});
// console.log("response", result);
expect(result.questions).toHaveProperty("question1");
expect(result.questions).toHaveProperty("question2");
expect(result.questions).toHaveProperty("question3");
});
test("StructuredOutputParser deals special chars in prompt with chat model 2", async () => {
const model = new ChatOpenAI({
temperature: 0,
});
const parser = StructuredOutputParser.fromNamesAndDescriptions({
question1: "a very on-topic question",
question2: "a super weird question",
question3: "an on-topic, but slightly creative",
});
const prompt = new ChatPromptTemplate({
promptMessages: [
SystemMessagePromptTemplate.fromTemplate("context:\n{context}\n---"),
SystemMessagePromptTemplate.fromTemplate(`{format_instructions}`),
],
inputVariables: ["context"],
partialVariables: {
format_instructions: parser.getFormatInstructions(),
},
});
const chain = new LLMChain({
llm: model,
prompt,
outputKey: "questions",
});
const result = await chain.call({
context: `The U2 ur-myth begins in 1976, when drummer Larry Mullen wanted to form a band.
He picked four school friends from Mount Temple Comprehensive School in Dublin.
“Larry formed U2,” says Paul McGuinness, U2’s manager from the beginning. “He
auditioned the other three and he chose them. The first name of U2 was the Larry
Mullen band,” McGuinness laughs. “And he never lets us forget it.” `,
});
// console.log("response", result);
const parsed = await parser.parse(result.questions);
expect(parsed).toHaveProperty("question1");
expect(parsed).toHaveProperty("question2");
expect(parsed).toHaveProperty("question3");
});
test("StructuredOutputParser handles a longer and more complex schema", async () => {
const parser = StructuredOutputParser.fromZodSchema(
z.object({
name: z.string().describe("Human name"),
surname: z.string().describe("Human surname"),
age: z.number().describe("Human age"),
appearance: z.string().describe("Human appearance description"),
shortBio: z.string().describe("Short bio secription"),
university: z.string().optional().describe("University name if attended"),
gender: z.string().describe("Gender of the human"),
interests: z
.array(z.string())
.describe("json array of strings human interests"),
})
);
const formatInstructions = parser.getFormatInstructions();
const prompt = new PromptTemplate({
template:
"Generate details of a hypothetical person.\n{format_instructions}\nPerson description: {inputText}",
inputVariables: ["inputText"],
partialVariables: { format_instructions: formatInstructions },
});
const model = new OpenAI({ temperature: 0.5, modelName: "gpt-3.5-turbo" });
const input = await prompt.format({
inputText: "A man, living in Poland.",
});
const response = await model.invoke(input);
// console.log("response", response);
const parsed = await parser.parse(response);
expect(parsed).toHaveProperty("name");
expect(parsed).toHaveProperty("surname");
expect(parsed).toHaveProperty("age");
expect(parsed).toHaveProperty("appearance");
expect(parsed).toHaveProperty("shortBio");
expect(parsed).toHaveProperty("age");
expect(parsed).toHaveProperty("gender");
expect(parsed).toHaveProperty("interests");
expect(parsed.interests.length).toBeGreaterThan(0);
});
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/tests/combining.test.ts | import { expect, test } from "@jest/globals";
import { CombiningOutputParser } from "../combining.js";
import { StructuredOutputParser } from "../structured.js";
import { RegexParser } from "../regex.js";
test("CombiningOutputParser", async () => {
const parser = new CombiningOutputParser(
StructuredOutputParser.fromNamesAndDescriptions({
url: "A link to the resource",
}),
new RegexParser(
/Confidence: (A|B|C), Explanation: (.*)/,
["confidence", "explanation"],
"noConfidence"
)
);
expect(parser.getFormatInstructions()).toMatchInlineSnapshot(`
"Return the following 2 outputs, each formatted as described below. Include the delimiter characters "-----" in your response:
-----Output 1-----
You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}}}
would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings.
Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted.
Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas!
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
\`\`\`json
{"type":"object","properties":{"url":{"type":"string","description":"A link to the resource"}},"required":["url"],"additionalProperties":false,"$schema":"http://json-schema.org/draft-07/schema#"}
\`\`\`
-----
-----Output 2-----
Your response should match the following regex: /Confidence: (A|B|C), Explanation: (.*)/
-----
"
`);
expect(
await parser.parse(
`-----Output 0-----
{"url": "https://en.wikipedia.org/wiki/Paris"}
-----
-----Output 1-----
Confidence: A, Explanation: Because it is the capital of France.
-----`
)
).toMatchInlineSnapshot(`
{
"confidence": "A",
"explanation": "Because it is the capital of France.",
"url": "https://en.wikipedia.org/wiki/Paris",
}
`);
expect(
await parser.parse(
'```\n{"url": "https://en.wikipedia.org/wiki/Paris"}\n```\nConfidence: A, Explanation: Because it is the capital of France.'
)
).toMatchInlineSnapshot(`
{
"confidence": "A",
"explanation": "Because it is the capital of France.",
"url": "https://en.wikipedia.org/wiki/Paris",
}
`);
});
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/tests/combining.int.test.ts | import { test } from "@jest/globals";
import { PromptTemplate } from "@langchain/core/prompts";
import { ChatOpenAI } from "@langchain/openai";
import {
StructuredOutputParser,
RegexParser,
CombiningOutputParser,
} from "../index.js";
test("CombiningOutputParser", async () => {
const answerParser = StructuredOutputParser.fromNamesAndDescriptions({
answer: "answer to the user's question",
source: "source used to answer the user's question, should be a website.",
});
const confidenceParser = new RegexParser(
/Confidence: (A|B|C), Explanation: (.*)/,
["confidence", "explanation"],
"noConfidence"
);
const parser = new CombiningOutputParser(answerParser, confidenceParser);
const formatInstructions = parser.getFormatInstructions();
const prompt = new PromptTemplate({
template:
"Answer the users question as best as possible.\n{format_instructions}\n{question}",
inputVariables: ["question"],
partialVariables: { format_instructions: formatInstructions },
});
const model = new ChatOpenAI({ temperature: 0 });
const input = await prompt.format({
question: "What is the capital of France?",
});
// console.log(input);
// @eslint-disable-next-line/@typescript-eslint/ban-ts-comment
// @ts-expect-error unused var
const response = await model.invoke(input);
// console.log(response);
// console.log(await parser.parse(response.content as string));
});
|
0 | lc_public_repos/langchainjs/langchain/src/output_parsers | lc_public_repos/langchainjs/langchain/src/output_parsers/tests/http_response.test.ts | import { FakeStreamingLLM } from "@langchain/core/utils/testing";
import { HttpResponseOutputParser } from "../http_response.js";
test("text/plain stream", async () => {
const llm = new FakeStreamingLLM({});
const stream = await llm
.pipe(new HttpResponseOutputParser())
.stream("Hi there!");
const chunks = [];
const decoder = new TextDecoder();
for await (const chunk of stream) {
chunks.push(decoder.decode(chunk));
}
expect(chunks.length).toEqual("Hi there!".length);
expect(chunks.join("")).toEqual("Hi there!");
});
test("text/event-stream stream", async () => {
const llm = new FakeStreamingLLM({});
const stream = await llm
.pipe(new HttpResponseOutputParser({ contentType: "text/event-stream" }))
.stream("Hi there!");
const chunks = [];
const decoder = new TextDecoder();
for await (const chunk of stream) {
chunks.push(decoder.decode(chunk));
}
expect(chunks.length).toEqual("Hi there!".length + 1);
expect(chunks).toEqual([
`event: data\ndata: "H"\n\n`,
`event: data\ndata: "i"\n\n`,
`event: data\ndata: " "\n\n`,
`event: data\ndata: "t"\n\n`,
`event: data\ndata: "h"\n\n`,
`event: data\ndata: "e"\n\n`,
`event: data\ndata: "r"\n\n`,
`event: data\ndata: "e"\n\n`,
`event: data\ndata: "!"\n\n`,
`event: end\n\n`,
]);
});
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tests/sql_database.int.test.ts | import { test, expect, beforeEach, afterEach } from "@jest/globals";
import { DataSource } from "typeorm";
import { SqlDatabase } from "../sql_db.js";
let datasource: DataSource;
beforeEach(async () => {
datasource = new DataSource({
type: "sqlite",
database: ":memory:",
synchronize: true,
});
await datasource.initialize();
await datasource.query(`
CREATE TABLE products (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, price INTEGER);
`);
await datasource.query(`
INSERT INTO products (name, price) VALUES ('Apple', 100);
`);
await datasource.query(`
INSERT INTO products (name, price) VALUES ('Banana', 200);
`);
await datasource.query(`
INSERT INTO products (name, price) VALUES ('Orange', 300);
`);
await datasource.query(`
CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER);
`);
await datasource.query(`
INSERT INTO users (name, age) VALUES ('Alice', 20);
`);
await datasource.query(`
INSERT INTO users (name, age) VALUES ('Bob', 21);
`);
await datasource.query(`
INSERT INTO users (name, age) VALUES ('Charlie', 22);
`);
});
afterEach(async () => {
await datasource.destroy();
});
test("Test getTableInfo", async () => {
const db = await SqlDatabase.fromDataSourceParams({
appDataSource: datasource,
});
const result = await db.getTableInfo(["users", "products"]);
const expectStr = `
CREATE TABLE products (
id INTEGER , name TEXT , price INTEGER )
SELECT * FROM "products" LIMIT 3;
id name price
1 Apple 100
2 Banana 200
3 Orange 300
CREATE TABLE users (
id INTEGER , name TEXT , age INTEGER )
SELECT * FROM "users" LIMIT 3;
id name age
1 Alice 20
2 Bob 21
3 Charlie 22`;
expect(result.trim()).toBe(expectStr.trim());
});
test("Test getTableInfo with less tables than in db", async () => {
const db = await SqlDatabase.fromDataSourceParams({
appDataSource: datasource,
});
const result = await db.getTableInfo(["products"]);
const expectStr = `
CREATE TABLE products (
id INTEGER , name TEXT , price INTEGER )
SELECT * FROM "products" LIMIT 3;
id name price
1 Apple 100
2 Banana 200
3 Orange 300`;
expect(result.trim()).toBe(expectStr.trim());
});
test("Test getTableInfo with includes tables", async () => {
const db = await SqlDatabase.fromDataSourceParams({
appDataSource: datasource,
includesTables: ["products"],
});
const result = await db.getTableInfo();
const expectStr = `
CREATE TABLE products (
id INTEGER , name TEXT , price INTEGER )
SELECT * FROM "products" LIMIT 3;
id name price
1 Apple 100
2 Banana 200
3 Orange 300`;
expect(result.trim()).toBe(expectStr.trim());
});
test("Test getTableInfo with ignoreTables", async () => {
const db = await SqlDatabase.fromDataSourceParams({
appDataSource: datasource,
ignoreTables: ["users"],
});
const result = await db.getTableInfo();
const expectStr = `
CREATE TABLE products (
id INTEGER , name TEXT , price INTEGER )
SELECT * FROM "products" LIMIT 3;
id name price
1 Apple 100
2 Banana 200
3 Orange 300`;
expect(result.trim()).toBe(expectStr.trim());
});
test("Test getTableInfo with error", async () => {
await expect(async () => {
const db = await SqlDatabase.fromDataSourceParams({
appDataSource: datasource,
});
await db.getTableInfo(["users", "productss"]);
}).rejects.toThrow(
"Wrong target table name: the table productss was not found in the database"
);
});
test("Test run", async () => {
const db = await SqlDatabase.fromDataSourceParams({
appDataSource: datasource,
});
const result = await db.run("SELECT * FROM users");
const expectStr = `[{"id":1,"name":"Alice","age":20},{"id":2,"name":"Bob","age":21},{"id":3,"name":"Charlie","age":22}]`;
expect(result.trim()).toBe(expectStr.trim());
});
test("Test run with error", async () => {
await expect(async () => {
const db = await SqlDatabase.fromDataSourceParams({
appDataSource: datasource,
});
await db.run("SELECT * FROM userss");
}).rejects.toThrow("SQLITE_ERROR: no such table: userss");
});
test("Test customDescription initialization from DataSourceParams", async () => {
const db = await SqlDatabase.fromDataSourceParams({
appDataSource: datasource,
customDescription: {
products: "this is a customDescription for table in db",
productss: "this customDescription should be skipped as table not in db",
},
});
expect(db.customDescription).toStrictEqual({
products: "this is a customDescription for table in db",
});
});
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tests/text_splitter.test.ts | import { describe, expect, test } from "@jest/globals";
import { Document } from "@langchain/core/documents";
import {
CharacterTextSplitter,
LatexTextSplitter,
MarkdownTextSplitter,
RecursiveCharacterTextSplitter,
TokenTextSplitter,
} from "../text_splitter.js";
function textLineGenerator(char: string, length: number) {
const line = new Array(length).join(char);
return `${line}\n`;
}
describe("Character text splitter", () => {
test("Test splitting by character count.", async () => {
const text = "foo bar baz 123";
const splitter = new CharacterTextSplitter({
separator: " ",
chunkSize: 7,
chunkOverlap: 3,
});
const output = await splitter.splitText(text);
const expectedOutput = ["foo bar", "bar baz", "baz 123"];
expect(output).toEqual(expectedOutput);
});
test("Test splitting by character count doesn't create empty documents.", async () => {
const text = "foo bar";
const splitter = new CharacterTextSplitter({
separator: " ",
chunkSize: 2,
chunkOverlap: 0,
});
const output = await splitter.splitText(text);
const expectedOutput = ["foo", "bar"];
expect(output).toEqual(expectedOutput);
});
test("Test splitting by character count on long words.", async () => {
const text = "foo bar baz a a";
const splitter = new CharacterTextSplitter({
separator: " ",
chunkSize: 3,
chunkOverlap: 1,
});
const output = await splitter.splitText(text);
const expectedOutput = ["foo", "bar", "baz", "a a"];
expect(output).toEqual(expectedOutput);
});
test("Test splitting by character count when shorter words are first.", async () => {
const text = "a a foo bar baz";
const splitter = new CharacterTextSplitter({
separator: " ",
chunkSize: 3,
chunkOverlap: 1,
});
const output = await splitter.splitText(text);
const expectedOutput = ["a a", "foo", "bar", "baz"];
expect(output).toEqual(expectedOutput);
});
test("Test splitting by characters when splits not found easily.", async () => {
const text = "foo bar baz 123";
const splitter = new CharacterTextSplitter({
separator: " ",
chunkSize: 1,
chunkOverlap: 0,
});
const output = await splitter.splitText(text);
const expectedOutput = ["foo", "bar", "baz", "123"];
expect(output).toEqual(expectedOutput);
});
test("Test invalid arguments.", () => {
expect(() => {
// @eslint-disable-next-line/@typescript-eslint/ban-ts-comment
// @ts-expect-error unused var
const res = new CharacterTextSplitter({ chunkSize: 2, chunkOverlap: 4 });
// console.log(res);
}).toThrow();
});
test("Test create documents method.", async () => {
const texts = ["foo bar", "baz"];
const splitter = new CharacterTextSplitter({
separator: " ",
chunkSize: 3,
chunkOverlap: 0,
});
const docs = await splitter.createDocuments(texts);
const metadata = { loc: { lines: { from: 1, to: 1 } } };
const expectedDocs = [
new Document({ pageContent: "foo", metadata }),
new Document({ pageContent: "bar", metadata }),
new Document({ pageContent: "baz", metadata }),
];
expect(docs).toEqual(expectedDocs);
});
test("Test create documents with metadata method.", async () => {
const texts = ["foo bar", "baz"];
const splitter = new CharacterTextSplitter({
separator: " ",
chunkSize: 3,
chunkOverlap: 0,
});
const docs = await splitter.createDocuments(texts, [
{ source: "1" },
{ source: "2" },
]);
const loc = { lines: { from: 1, to: 1 } };
const expectedDocs = [
new Document({ pageContent: "foo", metadata: { source: "1", loc } }),
new Document({
pageContent: "bar",
metadata: { source: "1", loc },
}),
new Document({ pageContent: "baz", metadata: { source: "2", loc } }),
];
expect(docs).toEqual(expectedDocs);
});
test("Test create documents method with metadata and an added chunk header.", async () => {
const texts = ["foo bar", "baz"];
const splitter = new CharacterTextSplitter({
separator: " ",
chunkSize: 3,
chunkOverlap: 0,
});
const docs = await splitter.createDocuments(
texts,
[{ source: "1" }, { source: "2" }],
{
chunkHeader: `SOURCE NAME: testing\n-----\n`,
appendChunkOverlapHeader: true,
}
);
const loc = { lines: { from: 1, to: 1 } };
const expectedDocs = [
new Document({
pageContent: "SOURCE NAME: testing\n-----\nfoo",
metadata: { source: "1", loc },
}),
new Document({
pageContent: "SOURCE NAME: testing\n-----\n(cont'd) bar",
metadata: { source: "1", loc },
}),
new Document({
pageContent: "SOURCE NAME: testing\n-----\nbaz",
metadata: { source: "2", loc },
}),
];
expect(docs).toEqual(expectedDocs);
});
});
describe("RecursiveCharacter text splitter", () => {
test("One unique chunk", async () => {
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 100,
chunkOverlap: 0,
});
const content = textLineGenerator("A", 70);
const docs = await splitter.createDocuments([content]);
const expectedDocs = [
new Document({
pageContent: content.trim(),
metadata: { loc: { lines: { from: 1, to: 1 } } },
}),
];
expect(docs).toEqual(expectedDocs);
});
test("Test iterative text splitter.", async () => {
const text = `Hi.\n\nI'm Harrison.\n\nHow? Are? You?\nOkay then f f f f.
This is a weird text to write, but gotta test the splittingggg some how.\n\n
Bye!\n\n-H.`;
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 10,
chunkOverlap: 1,
});
const output = await splitter.splitText(text);
const expectedOutput = [
"Hi.",
"I'm",
"Harrison.",
"How? Are?",
"You?",
"Okay then",
"f f f f.",
"This is a",
"weird",
"text to",
"write,",
"but gotta",
"test the",
"splitting",
"gggg",
"some how.",
"Bye!",
"-H.",
];
expect(output).toEqual(expectedOutput);
});
test("A basic chunked document", async () => {
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 100,
chunkOverlap: 0,
});
const line1 = textLineGenerator("A", 70);
const line2 = textLineGenerator("B", 70);
const content = line1 + line2;
const docs = await splitter.createDocuments([content]);
const expectedDocs = [
new Document({
pageContent: line1.trim(),
metadata: { loc: { lines: { from: 1, to: 1 } } },
}),
new Document({
pageContent: line2.trim(),
metadata: { loc: { lines: { from: 2, to: 2 } } },
}),
];
expect(docs).toEqual(expectedDocs);
});
test("A chunked document with similar text", async () => {
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 100,
chunkOverlap: 0,
});
const line = textLineGenerator("A", 70);
const content = line + line;
const docs = await splitter.createDocuments([content]);
const expectedDocs = [
new Document({
pageContent: line.trim(),
metadata: { loc: { lines: { from: 1, to: 1 } } },
}),
new Document({
pageContent: line.trim(),
metadata: { loc: { lines: { from: 2, to: 2 } } },
}),
];
expect(docs).toEqual(expectedDocs);
});
test("A chunked document starting with new lines", async () => {
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 100,
chunkOverlap: 0,
});
const line1 = textLineGenerator("\n", 2);
const line2 = textLineGenerator("A", 70);
const line3 = textLineGenerator("\n", 4);
const line4 = textLineGenerator("B", 70);
const line5 = textLineGenerator("\n", 4);
const content = line1 + line2 + line3 + line4 + line5;
const docs = await splitter.createDocuments([content]);
const expectedDocs = [
new Document({
pageContent: line2.trim(),
metadata: { loc: { lines: { from: 3, to: 3 } } },
}),
new Document({
pageContent: line4.trim(),
metadata: { loc: { lines: { from: 8, to: 8 } } },
}),
];
expect(docs).toEqual(expectedDocs);
});
test("A chunked with overlap", async () => {
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 100,
chunkOverlap: 30,
});
const line1 = textLineGenerator("A", 70);
const line2 = textLineGenerator("B", 20);
const line3 = textLineGenerator("C", 70);
const content = line1 + line2 + line3;
const docs = await splitter.createDocuments([content]);
const expectedDocs = [
new Document({
pageContent: line1 + line2.trim(),
metadata: { loc: { lines: { from: 1, to: 2 } } },
}),
new Document({
pageContent: line2 + line3.trim(),
metadata: { loc: { lines: { from: 2, to: 3 } } },
}),
];
expect(docs).toEqual(expectedDocs);
});
test("Chunks with overlap that contains new lines", async () => {
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 100,
chunkOverlap: 30,
});
const line1 = textLineGenerator("A", 70);
const line2 = textLineGenerator("B", 10);
const line3 = textLineGenerator("C", 10);
const line4 = textLineGenerator("D", 70);
const content = line1 + line2 + line3 + line4;
const docs = await splitter.createDocuments([content]);
const expectedDocs = [
new Document({
pageContent: line1 + line2 + line3.trim(),
metadata: { loc: { lines: { from: 1, to: 3 } } },
}),
new Document({
pageContent: line2 + line3 + line4.trim(),
metadata: { loc: { lines: { from: 2, to: 4 } } },
}),
];
expect(docs).toEqual(expectedDocs);
});
});
test("Separator length is considered correctly for chunk size", async () => {
const text = "aa ab ac ba bb";
const splitter = new RecursiveCharacterTextSplitter({
keepSeparator: false,
chunkSize: 7,
chunkOverlap: 3,
});
const output = await splitter.splitText(text);
const expectedOutput = ["aa ab", "ab ac", "ac ba", "ba bb"];
expect(output).toEqual(expectedOutput);
});
test("Token text splitter", async () => {
const text = "foo bar baz a a";
const splitter = new TokenTextSplitter({
encodingName: "r50k_base",
chunkSize: 3,
chunkOverlap: 0,
});
const output = await splitter.splitText(text);
const expectedOutput = ["foo bar b", "az a a"];
expect(output).toEqual(expectedOutput);
});
test("Token text splitter overlap when last chunk is large", async () => {
const text = "foo bar baz a a";
const splitter = new TokenTextSplitter({
encodingName: "r50k_base",
chunkSize: 5,
chunkOverlap: 3,
});
const output = await splitter.splitText(text);
const expectedOutput = ["foo bar baz a", " baz a a"];
expect(output).toEqual(expectedOutput);
});
test("Test markdown text splitter", async () => {
const text =
"# 🦜️🔗 LangChain\n" +
"\n" +
"⚡ Building applications with LLMs through composability ⚡\n" +
"\n" +
"## Quick Install\n" +
"\n" +
"```bash\n" +
"# Hopefully this code block isn't split\n" +
"pip install langchain\n" +
"```\n" +
"\n" +
"As an open source project in a rapidly developing field, we are extremely open to contributions.";
const splitter = new MarkdownTextSplitter({
chunkSize: 100,
chunkOverlap: 0,
});
const output = await splitter.splitText(text);
const expectedOutput = [
"# 🦜️🔗 LangChain\n\n⚡ Building applications with LLMs through composability ⚡",
"## Quick Install\n\n```bash\n# Hopefully this code block isn't split\npip install langchain",
"```",
"As an open source project in a rapidly developing field, we are extremely open to contributions.",
];
expect(output).toEqual(expectedOutput);
});
test("Test latex text splitter.", async () => {
const text = `\\begin{document}
\\title{🦜️🔗 LangChain}
⚡ Building applications with LLMs through composability ⚡
\\section{Quick Install}
\\begin{verbatim}
Hopefully this code block isn't split
yarn add langchain
\\end{verbatim}
As an open source project in a rapidly developing field, we are extremely open to contributions.
\\end{document}`;
const splitter = new LatexTextSplitter({
chunkSize: 100,
chunkOverlap: 0,
});
const output = await splitter.splitText(text);
const expectedOutput = [
"\\begin{document}\n\\title{🦜️🔗 LangChain}\n⚡ Building applications with LLMs through composability ⚡",
"\\section{Quick Install}",
"\\begin{verbatim}\nHopefully this code block isn't split\nyarn add langchain\n\\end{verbatim}",
"As an open source project in a rapidly developing field, we are extremely open to contributions.",
"\\end{document}",
];
expect(output).toEqual(expectedOutput);
});
test("Test HTML text splitter", async () => {
const text = `<!DOCTYPE html>
<html>
<head>
<title>🦜️🔗 LangChain</title>
<style>
body {
font-family: Arial, sans-serif;
}
h1 {
color: darkblue;
}
</style>
</head>
<body>
<div>
<h1>🦜️🔗 LangChain</h1>
<p>⚡ Building applications with LLMs through composability ⚡</p>
</div>
<div>
As an open source project in a rapidly developing field, we are extremely open to contributions.
</div>
</body>
</html>`;
const splitter = RecursiveCharacterTextSplitter.fromLanguage("html", {
chunkSize: 175,
chunkOverlap: 20,
});
const output = await splitter.splitText(text);
const expectedOutput = [
"<!DOCTYPE html>\n<html>",
"<head>\n <title>🦜️🔗 LangChain</title>",
`<style>\n body {
font-family: Arial, sans-serif;
}
h1 {
color: darkblue;
}
</style>
</head>`,
`<body>
<div>
<h1>🦜️🔗 LangChain</h1>
<p>⚡ Building applications with LLMs through composability ⚡</p>
</div>`,
`<div>
As an open source project in a rapidly developing field, we are extremely open to contributions.
</div>
</body>
</html>`,
];
expect(output).toEqual(expectedOutput);
});
test("Test lines loc on iterative text splitter.", async () => {
const text = `Hi.\nI'm Harrison.\n\nHow?\na\nb`;
const splitter = new RecursiveCharacterTextSplitter({
chunkSize: 20,
chunkOverlap: 1,
});
const docs = await splitter.createDocuments([text]);
const expectedDocs = [
new Document({
pageContent: "Hi.\nI'm Harrison.",
metadata: { loc: { lines: { from: 1, to: 2 } } },
}),
new Document({
pageContent: "How?\na\nb",
metadata: { loc: { lines: { from: 4, to: 6 } } },
}),
];
expect(docs).toEqual(expectedDocs);
});
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tests/hub.int.test.ts | /* eslint-disable no-process-env */
import { PromptTemplate } from "@langchain/core/prompts";
import * as hub from "../hub.js";
test("Test LangChain Hub client pushing a new repo", async () => {
const prompt = PromptTemplate.fromTemplate(
`You are a parrot. The current date is ${new Date().toISOString()}\n{input}`
);
const repoName = `${
process.env.LANGCHAIN_HUB_USERNAME
}/langchainjs-${new Date().getTime()}`;
await hub.push(repoName, prompt, {
newRepoIsPublic: false,
});
const pulledPrompt = await hub.pull(repoName);
expect(prompt.invoke({ input: "testing" })).toEqual(
pulledPrompt.invoke({ input: "testing" })
);
});
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/tests/code_text_splitter.test.ts | import { test, expect } from "@jest/globals";
import { RecursiveCharacterTextSplitter } from "../text_splitter.js";
test("Python code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("python", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `def hello_world():
print("Hello, World!")
# Call the function
hello_world()`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"def",
"hello_world():",
'print("Hello,',
'World!")',
"# Call the",
"function",
"hello_world()",
]);
});
test("Golang code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("go", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `package main
import "fmt"
func helloWorld() {
fmt.Println("Hello, World!")
}
func main() {
helloWorld()
}`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"package main",
'import "fmt"',
"func",
"helloWorld() {",
'fmt.Println("He',
"llo,",
'World!")',
"}",
"func main() {",
"helloWorld()",
"}",
]);
});
test("RST code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("rst", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `Sample Document
===============
Section
-------
This is the content of the section.
Lists
-----
- Item 1
- Item 2
- Item 3`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"Sample Document",
"===============",
"Section\n-------",
"This is the",
"content of the",
"section.",
"Lists\n-----",
"- Item 1",
"- Item 2",
"- Item 3",
]);
});
test("Proto code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("proto", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `syntax = "proto3";
package example;
message Person {
string name = 1;
int32 age = 2;
repeated string hobbies = 3;
}`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"syntax =",
'"proto3";',
"package",
"example;",
"message Person",
"{",
"string name",
"= 1;",
"int32 age =",
"2;",
"repeated",
"string hobbies",
"= 3;",
"}",
]);
});
test("JS code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("js", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `function helloWorld() {
console.log("Hello, World!");
}
// Call the function
helloWorld();`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"function",
"helloWorld() {",
'console.log("He',
"llo,",
'World!");',
"}",
"// Call the",
"function",
"helloWorld();",
]);
});
test("Java code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("java", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"public class",
"HelloWorld {",
"public static",
"void",
"main(String[]",
"args) {",
"System.out.prin",
'tln("Hello,',
'World!");',
"}\n}",
]);
});
test("CPP code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("cpp", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"#include",
"<iostream>",
"int main() {",
"std::cout",
'<< "Hello,',
'World!" <<',
"std::endl;",
"return 0;\n}",
]);
});
test("Scala code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("scala", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `object HelloWorld {
def main(args: Array[String]): Unit = {
println("Hello, World!")
}
}`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"object",
"HelloWorld {",
"def",
"main(args:",
"Array[String]):",
"Unit = {",
'println("Hello,',
'World!")',
"}\n}",
]);
});
test("Ruby code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("ruby", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `def hello_world
puts "Hello, World!"
end
hello_world`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"def hello_world",
'puts "Hello,',
'World!"',
"end\nhello_world",
]);
});
test("PHP code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("php", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `<?php
function hello_world() {
echo "Hello, World!";
}
hello_world();
?>`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"<?php",
"function",
"hello_world() {",
"echo",
'"Hello,',
'World!";',
"}",
"hello_world();",
"?>",
]);
});
test("Swift code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("swift", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `func helloWorld() {
print("Hello, World!")
}
helloWorld()`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"func",
"helloWorld() {",
'print("Hello,',
'World!")',
"}\nhelloWorld()",
]);
});
test("Rust code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("rust", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `fn main() {
println!("Hello, World!");
}`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"fn main() {",
'println!("Hello',
",",
'World!");',
"}",
]);
});
test("Solidity code splitter", async () => {
const splitter = RecursiveCharacterTextSplitter.fromLanguage("sol", {
chunkSize: 16,
chunkOverlap: 0,
});
const code = `pragma solidity ^0.8.20;
contract HelloWorld {
function add(uint a, uint b) pure public returns(uint) {
return a + b;
}
}
`;
const chunks = await splitter.splitText(code);
expect(chunks).toStrictEqual([
"pragma solidity",
"^0.8.20;",
"contract",
"HelloWorld {",
"function",
"add(uint a,",
"uint b) pure",
"public",
"returns(uint) {",
"return a",
"+ b;",
"}\n }",
]);
});
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/embeddings/cache_backed.ts | import { insecureHash } from "@langchain/core/utils/hash";
import {
type EmbeddingsInterface,
Embeddings,
} from "@langchain/core/embeddings";
import { BaseStore } from "@langchain/core/stores";
import { AsyncCallerParams } from "@langchain/core/utils/async_caller";
import { EncoderBackedStore } from "../storage/encoder_backed.js";
/**
* Interface for the fields required to initialize an instance of the
* CacheBackedEmbeddings class.
*/
export interface CacheBackedEmbeddingsFields extends AsyncCallerParams {
underlyingEmbeddings: EmbeddingsInterface;
documentEmbeddingStore: BaseStore<string, number[]>;
}
/**
* Interface for caching results from embedding models.
*
* The interface allows works with any store that implements
* the abstract store interface accepting keys of type str and values of list of
* floats.
*
* If need be, the interface can be extended to accept other implementations
* of the value serializer and deserializer, as well as the key encoder.
* @example
* ```typescript
* const underlyingEmbeddings = new OpenAIEmbeddings();
*
* const cacheBackedEmbeddings = CacheBackedEmbeddings.fromBytesStore(
* underlyingEmbeddings,
* new ConvexKVStore({ ctx }),
* {
* namespace: underlyingEmbeddings.modelName,
* },
* );
*
* const loader = new TextLoader("./state_of_the_union.txt");
* const rawDocuments = await loader.load();
* const splitter = new RecursiveCharacterTextSplitter({
* chunkSize: 1000,
* chunkOverlap: 0,
* });
* const documents = await splitter.splitDocuments(rawDocuments);
*
* let time = Date.now();
* const vectorstore = await ConvexVectorStore.fromDocuments(
* documents,
* cacheBackedEmbeddings,
* { ctx },
* );
* console.log(`Initial creation time: ${Date.now() - time}ms`);
*
* time = Date.now();
* const vectorstore2 = await ConvexVectorStore.fromDocuments(
* documents,
* cacheBackedEmbeddings,
* { ctx },
* );
* console.log(`Cached creation time: ${Date.now() - time}ms`);
*
* ```
*/
export class CacheBackedEmbeddings extends Embeddings {
protected underlyingEmbeddings: EmbeddingsInterface;
protected documentEmbeddingStore: BaseStore<string, number[]>;
constructor(fields: CacheBackedEmbeddingsFields) {
super(fields);
this.underlyingEmbeddings = fields.underlyingEmbeddings;
this.documentEmbeddingStore = fields.documentEmbeddingStore;
}
/**
* Embed query text.
*
* This method does not support caching at the moment.
*
* Support for caching queries is easy to implement, but might make
* sense to hold off to see the most common patterns.
*
* If the cache has an eviction policy, we may need to be a bit more careful
* about sharing the cache between documents and queries. Generally,
* one is OK evicting query caches, but document caches should be kept.
*
* @param document The text to embed.
* @returns The embedding for the given text.
*/
async embedQuery(document: string): Promise<number[]> {
return this.underlyingEmbeddings.embedQuery(document);
}
/**
* Embed a list of texts.
*
* The method first checks the cache for the embeddings.
* If the embeddings are not found, the method uses the underlying embedder
* to embed the documents and stores the results in the cache.
*
* @param documents
* @returns A list of embeddings for the given texts.
*/
async embedDocuments(documents: string[]): Promise<number[][]> {
const vectors = await this.documentEmbeddingStore.mget(documents);
const missingIndicies = [];
const missingDocuments = [];
for (let i = 0; i < vectors.length; i += 1) {
if (vectors[i] === undefined) {
missingIndicies.push(i);
missingDocuments.push(documents[i]);
}
}
if (missingDocuments.length) {
const missingVectors = await this.underlyingEmbeddings.embedDocuments(
missingDocuments
);
const keyValuePairs: [string, number[]][] = missingDocuments.map(
(document, i) => [document, missingVectors[i]]
);
await this.documentEmbeddingStore.mset(keyValuePairs);
for (let i = 0; i < missingIndicies.length; i += 1) {
vectors[missingIndicies[i]] = missingVectors[i];
}
}
return vectors as number[][];
}
/**
* Create a new CacheBackedEmbeddings instance from another embeddings instance
* and a storage instance.
* @param underlyingEmbeddings Embeddings used to populate the cache for new documents.
* @param documentEmbeddingStore Stores raw document embedding values. Keys are hashes of the document content.
* @param options.namespace Optional namespace for store keys.
* @returns A new CacheBackedEmbeddings instance.
*/
static fromBytesStore(
underlyingEmbeddings: EmbeddingsInterface,
documentEmbeddingStore: BaseStore<string, Uint8Array>,
options?: {
namespace?: string;
}
) {
const encoder = new TextEncoder();
const decoder = new TextDecoder();
const encoderBackedStore = new EncoderBackedStore<
string,
number[],
Uint8Array
>({
store: documentEmbeddingStore,
keyEncoder: (key) => (options?.namespace ?? "") + insecureHash(key),
valueSerializer: (value) => encoder.encode(JSON.stringify(value)),
valueDeserializer: (serializedValue) =>
JSON.parse(decoder.decode(serializedValue)),
});
return new this({
underlyingEmbeddings,
documentEmbeddingStore: encoderBackedStore,
});
}
}
|
0 | lc_public_repos/langchainjs/langchain/src | lc_public_repos/langchainjs/langchain/src/embeddings/fake.ts | export * from "@langchain/core/utils/testing";
|
0 | lc_public_repos/langchainjs/langchain/src/embeddings | lc_public_repos/langchainjs/langchain/src/embeddings/tests/fake.test.ts | import { test, expect } from "@jest/globals";
import { SyntheticEmbeddings } from "@langchain/core/utils/testing";
test("Synthetic basic", async () => {
const embed = new SyntheticEmbeddings({ vectorSize: 5 });
const vector = await embed.embedQuery("aaaaaaaaaa");
expect(vector).toHaveLength(5);
expect(vector[0]).toEqual(0.46153846153846156);
expect(vector[4]).toEqual(0.46153846153846156);
});
test("Synthetic Padding", async () => {
const embed = new SyntheticEmbeddings({ vectorSize: 5 });
const vector = await embed.embedQuery("aaaaaaaaa");
expect(vector).toHaveLength(5);
expect(vector[0]).toEqual(0.46153846153846156);
expect(vector[4]).toEqual(0.9615384615384616);
});
test("Synthetic extreme padding", async () => {
const embed = new SyntheticEmbeddings({ vectorSize: 768 });
const vector = await embed.embedQuery("aa");
expect(vector).toHaveLength(768);
expect(vector[0]).toEqual(0.7307692307692307);
expect(vector[1]).toEqual(0.7307692307692307);
expect(vector[2]).toEqual(0);
});
test("Synthetic similarity", async () => {
const embed = new SyntheticEmbeddings({ vectorSize: 2 });
const v1 = await embed.embedQuery("this");
const v2 = await embed.embedQuery("that");
// console.log(v1, v2);
expect(v1).toHaveLength(2);
expect(v2).toHaveLength(2);
expect(v1[0]).toEqual(v2[0]);
expect(v1[1]).not.toEqual(v2[1]);
});
|
0 | lc_public_repos/langchainjs/langchain/src/embeddings | lc_public_repos/langchainjs/langchain/src/embeddings/tests/cache.test.ts | import { test, expect } from "@jest/globals";
import { Embeddings } from "@langchain/core/embeddings";
import { CacheBackedEmbeddings } from "../cache_backed.js";
import { InMemoryStore } from "../../storage/in_memory.js";
class RandomEmbeddings extends Embeddings {
async embedDocuments(documents: string[]): Promise<number[][]> {
const quoteUnquoteEmbeddings = [];
for (const document of documents) {
quoteUnquoteEmbeddings.push(await this.embedQuery(document));
}
return quoteUnquoteEmbeddings;
}
async embedQuery(_document: string): Promise<number[]> {
return [Math.random(), Math.random()];
}
}
test("Basic embeddings cache", async () => {
const embeddingsCache = CacheBackedEmbeddings.fromBytesStore(
new RandomEmbeddings({}),
new InMemoryStore()
);
const documents = ["How are you?", "I am fine", "I am LangChain"];
const result = await embeddingsCache.embedDocuments(documents);
expect(result.findIndex((v) => v === undefined)).toEqual(-1);
const result2 = await embeddingsCache.embedDocuments(documents);
expect(result).toEqual(result2);
});
|
0 | lc_public_repos/langchainjs/langchain/src/experimental | lc_public_repos/langchainjs/langchain/src/experimental/openai_files/index.ts | import { OpenAIClient, type ClientOptions } from "@langchain/openai";
import { Serializable } from "@langchain/core/load/serializable";
export type OpenAIFilesInput = {
client?: OpenAIClient;
clientOptions?: ClientOptions;
};
export class OpenAIFiles extends Serializable {
lc_namespace = ["langchain", "experimental"];
private oaiClient: OpenAIClient;
constructor(fields?: OpenAIFilesInput) {
super(fields);
this.oaiClient = fields?.client ?? new OpenAIClient(fields?.clientOptions);
}
/**
* Upload file
* Upload a file that can be used across various endpoints. The size of all the files uploaded by one organization can be up to 100 GB.
*
* @note The size of individual files can be a maximum of 512 MB. See the Assistants Tools guide to learn more about the types of files supported. The Fine-tuning API only supports .jsonl files.
*
* @link {https://platform.openai.com/docs/api-reference/files/create}
* @param {OpenAIClient.FileCreateParams['file']} file
* @param {OpenAIClient.FileCreateParams['purpose']} purpose
* @param {OpenAIClient.RequestOptions | undefined} options
* @returns {Promise<OpenAIClient.Files.FileObject>}
*/
async createFile({
file,
purpose,
options,
}: OpenAIClient.FileCreateParams & {
options?: OpenAIClient.RequestOptions;
}) {
return this.oaiClient.files.create({ file, purpose }, options);
}
/**
* Delete a file.
*
* @link {https://platform.openai.com/docs/api-reference/files/delete}
* @param {string} fileId
* @param {OpenAIClient.RequestOptions | undefined} options
* @returns {Promise<OpenAIClient.Files.FileDeleted>}
*/
async deleteFile({
fileId,
options,
}: {
fileId: string;
options?: OpenAIClient.RequestOptions;
}) {
return this.oaiClient.files.del(fileId, options);
}
/**
* List files
* Returns a list of files that belong to the user's organization.
*
* @link {https://platform.openai.com/docs/api-reference/files/list}
* @param {OpenAIClient.Files.FileListParams | undefined} query
* @param {OpenAIClient.RequestOptions | undefined} options
* @returns {Promise<OpenAIClient.Files.FileObjectsPage>}
*/
async listFiles(props?: {
query?: OpenAIClient.Files.FileListParams;
options?: OpenAIClient.RequestOptions;
}) {
return this.oaiClient.files.list(props?.query, props?.options);
}
/**
* Retrieve file
* Returns information about a specific file.
*
* @link {https://platform.openai.com/docs/api-reference/files/retrieve}
* @param {string} fileId
* @param {OpenAIClient.RequestOptions | undefined} options
* @returns {Promise<OpenAIClient.Files.FileObject>}
*/
async retrieveFile({
fileId,
options,
}: {
fileId: string;
options?: OpenAIClient.RequestOptions;
}) {
return this.oaiClient.files.retrieve(fileId, options);
}
/**
* Retrieve file content
* Returns the contents of the specified file.
*
* @note You can't retrieve the contents of a file that was uploaded with the "purpose": "assistants" API.
*
* @link {https://platform.openai.com/docs/api-reference/files/retrieve-contents}
* @param {string} fileId
* @param {OpenAIClient.RequestOptions | undefined} options
* @returns {Promise<string>}
*/
async retrieveFileContent({
fileId,
options,
}: {
fileId: string;
options?: OpenAIClient.RequestOptions;
}) {
return this.oaiClient.files.retrieveContent(fileId, options);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.