Partial Values
It can often make sense to "partial" a prompt template - eg pass in a subset of the required values, as to create a new prompt template which expects only the remaining subset of values.
LangChain supports this in two ways:
Partial formatting with string values.
Partial formatting with functions that return string values.
These two different ways support different use cases. In the examples below, we go over the motivations for both use cases as well as how to do it in LangChain.
Partial With Strings
One common use case for wanting to partial a prompt template is if you get some of the variables before others. For example, suppose you have a prompt template that requires two variables, foo and baz. If you get the foo value early on in the chain, but the baz value later, it can be annoying to wait until you have both variables in the same place to pass them to the prompt template. Instead, you can partial the prompt template with the foo value, and then pass the partialed prompt template along and just use that. Below is an example of doing this:
package main
import (
"fmt"
"log"
"github.com/tmc/langchaingo/prompts"
)
func main() {
prompt := prompts.PromptTemplate{
Template: "{{.foo}}{{.bar}}",
InputVariables: []string{"bar"},
PartialVariables: map[string]any{
"foo": "foo",
},
TemplateFormat: prompts.TemplateFormatGoTemplate,
}
result, err := prompt.Format(map[string]any{
"bar": "baz",
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
foobaz
Partial With Functions
The other common use is to partial with a function. The use case for this is when you have a variable you know that you always want to fetch in a common way. A prime example of this is with date or time. Imagine you have a prompt which you always want to have the current date. You can't hard code it in the prompt, and passing it along with the other input variables is a bit annoying. In this case, it's very handy to be able to partial the prompt with a function that always returns the current date.
package main
import (
"fmt"
"log"
"time"
"github.com/tmc/langchaingo/prompts"
)
func main() {
prompt := prompts.PromptTemplate{
Template: "Tell me a {{.adjective}} joke about the day {{.date}}",
InputVariables: []string{"adjective"},
PartialVariables: map[string]any{
"date": func() string {
return time.Now().Format("January 02, 2006")
},
},
TemplateFormat: prompts.TemplateFormatGoTemplate,
}
result, err := prompt.Format(map[string]any{
"adjective": "funny",
})
if err != nil {
log.Fatal(err)
}
fmt.Println(result)
}
Tell me a funny joke about the day June 28, 2023