KeyError-FewshotpromptTemplate #25758
Replies: 1 comment 2 replies
-
To resolve the Here's a step-by-step approach to resolve this issue:
Here is an example to illustrate this: from langchain_core.prompts import FewShotPromptTemplate, PromptTemplate
# Define the example prompt template
example_prompt = PromptTemplate(
input_variables=["Question", "Answer"],
template="Question: {Question}\nAnswer: {Answer}"
)
# Define the few-shot prompt template
few_shot_prompt = FewShotPromptTemplate(
examples=[
{"Question": "Write Python code for App", "Answer": "def app():\n pass"}
],
example_prompt=example_prompt,
suffix="Question: {Input}",
input_variables=["Input"]
)
# Format the prompt
formatted_prompt = few_shot_prompt.format(Input="ABC")
print(formatted_prompt) In this example, the Additionally, if your def escape_examples(examples):
return [{k: escape_f_string(v) for k, v in example.items()} for example in examples]
def escape_f_string(text):
return text.replace('{', '{{').replace('}', '}}')
# Read the content of the file
with open('**Path to my file/test.py', 'r') as file:
Answer_4 = file.read()
# Escape curly brackets in the examples
examples = escape_examples([
{"Question": "Write Python code for App", "Answer": Answer_4}
])
# Define the few-shot prompt template with escaped examples
few_shot_prompt = FewShotPromptTemplate(
examples=examples,
example_prompt=example_prompt,
suffix="Question: {Input}",
input_variables=["Input"]
)
# Format the prompt
formatted_prompt = few_shot_prompt.format(Input="ABC")
print(formatted_prompt) This workaround ensures that curly brackets are properly escaped before f-string formatting, preventing errors [2]. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Checked other resources
Commit to Help
Example Code
Description
I am trying to read a simple .py file and make that as an example answer in the fewshotprompt template. It is giving a keyError for this one example input, rest seems to be working fine. Below is a content of the test.py file i am trying to read above. the Key Error starts at "Cell_ID" and propagates further down. I am not sure what is causing the issue in the method of .format. All I intend to do is be able to do a fewshot prompt with Q/A format when the answer is the content of the .py file as is.. and then be able to use example selector after this..
System Info
I am on Windows machine, using WSL and jupyter lab
langchain==0.2.11
langchain-anthropic==0.1.3
langchain-cli==0.0.21
langchain-community==0.0.28
langchain-core==0.2.26
langchain-experimental==0.0.50
langchain-openai==0.0.8
langchain-text-splitters==0.2.2
langchainhub==0.1.20
Python 3.11.6
Beta Was this translation helpful? Give feedback.
All reactions