Skip to content

Commit

Permalink
fix(openai): Pass OpenAI caching information through in responses (#6922
Browse files Browse the repository at this point in the history
)
  • Loading branch information
jacoblee93 authored Oct 2, 2024
1 parent a7c46f5 commit 00a727e
Show file tree
Hide file tree
Showing 3 changed files with 671 additions and 3 deletions.
364 changes: 364 additions & 0 deletions docs/core_docs/docs/integrations/chat/openai.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,370 @@
"}]);"
]
},
{
"cell_type": "markdown",
"id": "af20e756",
"metadata": {},
"source": [
"## Prompt caching\n",
"\n",
"Newer OpenAI models will automatically [cache parts of your prompt](https://openai.com/index/api-prompt-caching/) if your inputs are above a certain size (1024 tokens at the time of writing) in order to reduce costs for use-cases that require long context.\n",
"\n",
"**Note:** The number of tokens cached for a given query is not yet standardized in `AIMessage.usage_metadata`, and is instead contained in the `AIMessage.response_metadata` field.\n",
"\n",
"Here's an example"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "cb4e4fd0",
"metadata": {},
"outputs": [],
"source": [
"// @lc-docs-hide-cell\n",
"\n",
"const CACHED_TEXT = `## Components\n",
"\n",
"LangChain provides standard, extendable interfaces and external integrations for various components useful for building with LLMs.\n",
"Some components LangChain implements, some components we rely on third-party integrations for, and others are a mix.\n",
"\n",
"### Chat models\n",
"\n",
"<span data-heading-keywords=\"chat model,chat models\"></span>\n",
"\n",
"Language models that use a sequence of messages as inputs and return chat messages as outputs (as opposed to using plain text).\n",
"These are generally newer models (older models are generally \\`LLMs\\`, see below).\n",
"Chat models support the assignment of distinct roles to conversation messages, helping to distinguish messages from the AI, users, and instructions such as system messages.\n",
"\n",
"Although the underlying models are messages in, message out, the LangChain wrappers also allow these models to take a string as input.\n",
"This gives them the same interface as LLMs (and simpler to use).\n",
"When a string is passed in as input, it will be converted to a \\`HumanMessage\\` under the hood before being passed to the underlying model.\n",
"\n",
"LangChain does not host any Chat Models, rather we rely on third party integrations.\n",
"\n",
"We have some standardized parameters when constructing ChatModels:\n",
"\n",
"- \\`model\\`: the name of the model\n",
"\n",
"Chat Models also accept other parameters that are specific to that integration.\n",
"\n",
":::important\n",
"Some chat models have been fine-tuned for **tool calling** and provide a dedicated API for it.\n",
"Generally, such models are better at tool calling than non-fine-tuned models, and are recommended for use cases that require tool calling.\n",
"Please see the [tool calling section](/docs/concepts/#functiontool-calling) for more information.\n",
":::\n",
"\n",
"For specifics on how to use chat models, see the [relevant how-to guides here](/docs/how_to/#chat-models).\n",
"\n",
"#### Multimodality\n",
"\n",
"Some chat models are multimodal, accepting images, audio and even video as inputs.\n",
"These are still less common, meaning model providers haven't standardized on the \"best\" way to define the API.\n",
"Multimodal outputs are even less common. As such, we've kept our multimodal abstractions fairly light weight\n",
"and plan to further solidify the multimodal APIs and interaction patterns as the field matures.\n",
"\n",
"In LangChain, most chat models that support multimodal inputs also accept those values in OpenAI's content blocks format.\n",
"So far this is restricted to image inputs. For models like Gemini which support video and other bytes input, the APIs also support the native, model-specific representations.\n",
"\n",
"For specifics on how to use multimodal models, see the [relevant how-to guides here](/docs/how_to/#multimodal).\n",
"\n",
"### LLMs\n",
"\n",
"<span data-heading-keywords=\"llm,llms\"></span>\n",
"\n",
":::caution\n",
"Pure text-in/text-out LLMs tend to be older or lower-level. Many popular models are best used as [chat completion models](/docs/concepts/#chat-models),\n",
"even for non-chat use cases.\n",
"\n",
"You are probably looking for [the section above instead](/docs/concepts/#chat-models).\n",
":::\n",
"\n",
"Language models that takes a string as input and returns a string.\n",
"These are traditionally older models (newer models generally are [Chat Models](/docs/concepts/#chat-models), see above).\n",
"\n",
"Although the underlying models are string in, string out, the LangChain wrappers also allow these models to take messages as input.\n",
"This gives them the same interface as [Chat Models](/docs/concepts/#chat-models).\n",
"When messages are passed in as input, they will be formatted into a string under the hood before being passed to the underlying model.\n",
"\n",
"LangChain does not host any LLMs, rather we rely on third party integrations.\n",
"\n",
"For specifics on how to use LLMs, see the [relevant how-to guides here](/docs/how_to/#llms).\n",
"\n",
"### Message types\n",
"\n",
"Some language models take an array of messages as input and return a message.\n",
"There are a few different types of messages.\n",
"All messages have a \\`role\\`, \\`content\\`, and \\`response_metadata\\` property.\n",
"\n",
"The \\`role\\` describes WHO is saying the message.\n",
"LangChain has different message classes for different roles.\n",
"\n",
"The \\`content\\` property describes the content of the message.\n",
"This can be a few different things:\n",
"\n",
"- A string (most models deal this type of content)\n",
"- A List of objects (this is used for multi-modal input, where the object contains information about that input type and that input location)\n",
"\n",
"#### HumanMessage\n",
"\n",
"This represents a message from the user.\n",
"\n",
"#### AIMessage\n",
"\n",
"This represents a message from the model. In addition to the \\`content\\` property, these messages also have:\n",
"\n",
"**\\`response_metadata\\`**\n",
"\n",
"The \\`response_metadata\\` property contains additional metadata about the response. The data here is often specific to each model provider.\n",
"This is where information like log-probs and token usage may be stored.\n",
"\n",
"**\\`tool_calls\\`**\n",
"\n",
"These represent a decision from an language model to call a tool. They are included as part of an \\`AIMessage\\` output.\n",
"They can be accessed from there with the \\`.tool_calls\\` property.\n",
"\n",
"This property returns a list of \\`ToolCall\\`s. A \\`ToolCall\\` is an object with the following arguments:\n",
"\n",
"- \\`name\\`: The name of the tool that should be called.\n",
"- \\`args\\`: The arguments to that tool.\n",
"- \\`id\\`: The id of that tool call.\n",
"\n",
"#### SystemMessage\n",
"\n",
"This represents a system message, which tells the model how to behave. Not every model provider supports this.\n",
"\n",
"#### ToolMessage\n",
"\n",
"This represents the result of a tool call. In addition to \\`role\\` and \\`content\\`, this message has:\n",
"\n",
"- a \\`tool_call_id\\` field which conveys the id of the call to the tool that was called to produce this result.\n",
"- an \\`artifact\\` field which can be used to pass along arbitrary artifacts of the tool execution which are useful to track but which should not be sent to the model.\n",
"\n",
"#### (Legacy) FunctionMessage\n",
"\n",
"This is a legacy message type, corresponding to OpenAI's legacy function-calling API. \\`ToolMessage\\` should be used instead to correspond to the updated tool-calling API.\n",
"\n",
"This represents the result of a function call. In addition to \\`role\\` and \\`content\\`, this message has a \\`name\\` parameter which conveys the name of the function that was called to produce this result.\n",
"\n",
"### Prompt templates\n",
"\n",
"<span data-heading-keywords=\"prompt,prompttemplate,chatprompttemplate\"></span>\n",
"\n",
"Prompt templates help to translate user input and parameters into instructions for a language model.\n",
"This can be used to guide a model's response, helping it understand the context and generate relevant and coherent language-based output.\n",
"\n",
"Prompt Templates take as input an object, where each key represents a variable in the prompt template to fill in.\n",
"\n",
"Prompt Templates output a PromptValue. This PromptValue can be passed to an LLM or a ChatModel, and can also be cast to a string or an array of messages.\n",
"The reason this PromptValue exists is to make it easy to switch between strings and messages.\n",
"\n",
"There are a few different types of prompt templates:\n",
"\n",
"#### String PromptTemplates\n",
"\n",
"These prompt templates are used to format a single string, and generally are used for simpler inputs.\n",
"For example, a common way to construct and use a PromptTemplate is as follows:\n",
"\n",
"\\`\\`\\`typescript\n",
"import { PromptTemplate } from \"@langchain/core/prompts\";\n",
"\n",
"const promptTemplate = PromptTemplate.fromTemplate(\n",
" \"Tell me a joke about {topic}\"\n",
");\n",
"\n",
"await promptTemplate.invoke({ topic: \"cats\" });\n",
"\\`\\`\\`\n",
"\n",
"#### ChatPromptTemplates\n",
"\n",
"These prompt templates are used to format an array of messages. These \"templates\" consist of an array of templates themselves.\n",
"For example, a common way to construct and use a ChatPromptTemplate is as follows:\n",
"\n",
"\\`\\`\\`typescript\n",
"import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
"\n",
"const promptTemplate = ChatPromptTemplate.fromMessages([\n",
" [\"system\", \"You are a helpful assistant\"],\n",
" [\"user\", \"Tell me a joke about {topic}\"],\n",
"]);\n",
"\n",
"await promptTemplate.invoke({ topic: \"cats\" });\n",
"\\`\\`\\`\n",
"\n",
"In the above example, this ChatPromptTemplate will construct two messages when called.\n",
"The first is a system message, that has no variables to format.\n",
"The second is a HumanMessage, and will be formatted by the \\`topic\\` variable the user passes in.\n",
"\n",
"#### MessagesPlaceholder\n",
"\n",
"<span data-heading-keywords=\"messagesplaceholder\"></span>\n",
"\n",
"This prompt template is responsible for adding an array of messages in a particular place.\n",
"In the above ChatPromptTemplate, we saw how we could format two messages, each one a string.\n",
"But what if we wanted the user to pass in an array of messages that we would slot into a particular spot?\n",
"This is how you use MessagesPlaceholder.\n",
"\n",
"\\`\\`\\`typescript\n",
"import {\n",
" ChatPromptTemplate,\n",
" MessagesPlaceholder,\n",
"} from \"@langchain/core/prompts\";\n",
"import { HumanMessage } from \"@langchain/core/messages\";\n",
"\n",
"const promptTemplate = ChatPromptTemplate.fromMessages([\n",
" [\"system\", \"You are a helpful assistant\"],\n",
" new MessagesPlaceholder(\"msgs\"),\n",
"]);\n",
"\n",
"promptTemplate.invoke({ msgs: [new HumanMessage({ content: \"hi!\" })] });\n",
"\\`\\`\\`\n",
"\n",
"This will produce an array of two messages, the first one being a system message, and the second one being the HumanMessage we passed in.\n",
"If we had passed in 5 messages, then it would have produced 6 messages in total (the system message plus the 5 passed in).\n",
"This is useful for letting an array of messages be slotted into a particular spot.\n",
"\n",
"An alternative way to accomplish the same thing without using the \\`MessagesPlaceholder\\` class explicitly is:\n",
"\n",
"\\`\\`\\`typescript\n",
"const promptTemplate = ChatPromptTemplate.fromMessages([\n",
" [\"system\", \"You are a helpful assistant\"],\n",
" [\"placeholder\", \"{msgs}\"], // <-- This is the changed part\n",
"]);\n",
"\\`\\`\\`\n",
"\n",
"For specifics on how to use prompt templates, see the [relevant how-to guides here](/docs/how_to/#prompt-templates).\n",
"\n",
"### Example Selectors\n",
"\n",
"One common prompting technique for achieving better performance is to include examples as part of the prompt.\n",
"This gives the language model concrete examples of how it should behave.\n",
"Sometimes these examples are hardcoded into the prompt, but for more advanced situations it may be nice to dynamically select them.\n",
"Example Selectors are classes responsible for selecting and then formatting examples into prompts.\n",
"\n",
"For specifics on how to use example selectors, see the [relevant how-to guides here](/docs/how_to/#example-selectors).\n",
"\n",
"### Output parsers\n",
"\n",
"<span data-heading-keywords=\"output parser\"></span>\n",
"\n",
":::note\n",
"\n",
"The information here refers to parsers that take a text output from a model try to parse it into a more structured representation.\n",
"More and more models are supporting function (or tool) calling, which handles this automatically.\n",
"It is recommended to use function/tool calling rather than output parsing.\n",
"See documentation for that [here](/docs/concepts/#function-tool-calling).\n",
"\n",
":::\n",
"\n",
"Responsible for taking the output of a model and transforming it to a more suitable format for downstream tasks.\n",
"Useful when you are using LLMs to generate structured data, or to normalize output from chat models and LLMs.\n",
"\n",
"There are two main methods an output parser must implement:\n",
"\n",
"- \"Get format instructions\": A method which returns a string containing instructions for how the output of a language model should be formatted.\n",
"- \"Parse\": A method which takes in a string (assumed to be the response from a language model) and parses it into some structure.\n",
"\n",
"And then one optional one:\n",
"\n",
"- \"Parse with prompt\": A method which takes in a string (assumed to be the response from a language model) and a prompt (assumed to be the prompt that generated such a response) and parses it into some structure. The prompt is largely provided in the event the OutputParser wants to retry or fix the output in some way, and needs information from the prompt to do so.\n",
"\n",
"Output parsers accept a string or \\`BaseMessage\\` as input and can return an arbitrary type.\n",
"\n",
"LangChain has many different types of output parsers. This is a list of output parsers LangChain supports. The table below has various pieces of information:\n",
"\n",
"**Name**: The name of the output parser\n",
"\n",
"**Supports Streaming**: Whether the output parser supports streaming.\n",
"\n",
"**Input Type**: Expected input type. Most output parsers work on both strings and messages, but some (like OpenAI Functions) need a message with specific arguments.\n",
"\n",
"**Output Type**: The output type of the object returned by the parser.\n",
"\n",
"**Description**: Our commentary on this output parser and when to use it.\n",
"\n",
"The current date is ${new Date().toISOString()}`;\n",
"\n",
"// Noop statement to hide output\n",
"void 0;"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "7a43595c",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"USAGE: {\n",
" prompt_tokens: 2624,\n",
" completion_tokens: 263,\n",
" total_tokens: 2887,\n",
" prompt_tokens_details: { cached_tokens: 0 },\n",
" completion_tokens_details: { reasoning_tokens: 0 }\n",
"}\n"
]
}
],
"source": [
"import { ChatOpenAI } from \"@langchain/openai\";\n",
"\n",
"const modelWithCaching = new ChatOpenAI({\n",
" model: \"gpt-4o-mini-2024-07-18\",\n",
"});\n",
"\n",
"// CACHED_TEXT is some string longer than 1024 tokens\n",
"const LONG_TEXT = `You are a pirate. Always respond in pirate dialect.\n",
"\n",
"Use the following as context when answering questions:\n",
"\n",
"${CACHED_TEXT}`;\n",
"\n",
"const longMessages = [\n",
" {\n",
" role: \"system\",\n",
" content: LONG_TEXT,\n",
" },\n",
" {\n",
" role: \"user\",\n",
" content: \"What types of messages are supported in LangChain?\",\n",
" },\n",
"];\n",
"\n",
"const originalRes = await modelWithCaching.invoke(longMessages);\n",
"\n",
"console.log(\"USAGE:\", originalRes.response_metadata.usage);"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "76c8005e",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"USAGE: {\n",
" prompt_tokens: 2624,\n",
" completion_tokens: 272,\n",
" total_tokens: 2896,\n",
" prompt_tokens_details: { cached_tokens: 2432 },\n",
" completion_tokens_details: { reasoning_tokens: 0 }\n",
"}\n"
]
}
],
"source": [
"const resWitCaching = await modelWithCaching.invoke(longMessages);\n",
"\n",
"console.log(\"USAGE:\", resWitCaching.response_metadata.usage);"
]
},
{
"cell_type": "markdown",
"id": "3a5bb5ca-c3ae-4a58-be67-2cd18574b9a3",
Expand Down
Loading

0 comments on commit 00a727e

Please sign in to comment.