-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlangchain_basics.py
67 lines (53 loc) · 2.46 KB
/
langchain_basics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
from langchain_core.output_parsers import StrOutputParser #response.choices[0].message.content
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI
from setup_environment import set_environment_variables
set_environment_variables()
french_german_prompt = ChatPromptTemplate.from_template(
"Please tell me the french and german words for {word} with an example sentence for each."
)
# ==> template = ChatPromptTemplate.from_messages([
# ("human", "Please tell me the french and german words for {word} with an example sentence for each.")
# ])
## Example of a ChatPromptTemplate
# template = ChatPromptTemplate.from_messages([
# ("system", "You are a helpful AI bot. Your name is {name}."),
# ("human", "Hello, how are you doing?"),
# ("ai", "I'm doing well, thanks!"),
# ("human", "{user_input}"),
# ])
llm = ChatOpenAI(model="gpt-3.5-turbo-0125")
output_parser = StrOutputParser()
#'LCEL or LangChain Expression Language'
french_german_chain = french_german_prompt | llm | output_parser
# result = french_german_chain.invoke({"word": "polar bear"})
# print(result)
# for chunk in french_german_chain.stream({"word": "polar bear"}):
# print(chunk, end="", flush=True)
# print(
# french_german_chain.batch(
# [{"word": "computer"}, {"word": "elephant"}, {"word": "carrot"}]
# )
# )
# print("input_schema", french_german_chain.input_schema.schema())
# print("output_schema", french_german_chain.output_schema.schema())
check_if_correct_prompt = ChatPromptTemplate.from_template(
"""
You are a helpful assistant that looks at a question and its given answer. You will find out what is wrong with the answer and improve it. You will return the improved version of the answer.
Question:\n{question}\nAnswer Given:\n{initial_answer}\nReview the answer and give me an improved version instead.
Improved answer:
"""
)
check_answer_chain = check_if_correct_prompt | llm | output_parser
def run_chain(word: str) -> str:
initial_answer = french_german_chain.invoke({"word": word})
print("initial answer:", initial_answer, end="\n\n")
answer = check_answer_chain.invoke(
{
"question": f"Please tell me the french and german words for {word} with an example sentence for each.",
"initial_answer": initial_answer,
}
)
print("improved answer:", answer)
return answer
run_chain("strawberries")