
LangChain ã® HOW-TO EXAMPLES (6) - ã¡ã¢ãª
ãLangChainãã®ãã¡ã¢ãªããæäŸããæ©èœã玹ä»ãã HOW-TO EXAMPLES ããŸãšããŸããã
åå
1. ã¡ã¢ãªã®æ©èœ
ãã¡ã¢ãªãã¯ãéå»ã®ã¡ãã»ãŒãžã®ããåããèšæ¶ããŸãã
2. ã¡ã¢ãªã®è¿œå
ã¡ã¢ãªã®è¿œå æé ã¯ã次ã®ãšããã§ãã
(1) ChatBotçšã®ãã³ãã¬ãŒãã®æºåã
ãã³ãã¬ãŒãã«ã¯ã人éã®å
¥å (human_input) ãšã¡ã¢ãªã®å
¥å (chat_history) ã®2ã€ã®å
¥åããŒãçšæããŸãã
from langchain.chains.conversation.memory import ConversationBufferMemory
from langchain import OpenAI, LLMChain, PromptTemplate
# ãã³ãã¬ãŒãã®æºå
template = """ããªãã¯äººéãšäŒè©±ãããã£ãããããã§ãã
{chat_history}
Human: {human_input}
Chatbot:"""
# ããã³ãããã³ãã¬ãŒãã®æºå
prompt = PromptTemplate(
input_variables=["chat_history", "human_input"],
template=template
)(2) ã¡ã¢ãªã®æºåã
# ã¡ã¢ãªã®æºå
memory = ConversationBufferMemory(memory_key="chat_history")(3) LLMChainã®æºåã
å
çšæºåããããã³ãããã³ãã¬ãŒããšã¡ã¢ãªãèšå®ããŸãã
# LLMChainã®æºå
llm_chain = LLMChain(
llm=OpenAI(),
prompt=prompt,
memory=memory,
verbose=True,
)(4) æšè«ã®å®è¡ã
llm_chain.predict(human_input="ããã«ã¡ã¯ïŒ")> Entering new LLMChain chain...
Prompt after formatting:
ããªãã¯äººéãšäŒè©±ãããã£ãããããã§ãã
Human: ããã«ã¡ã¯ïŒ
AI: ããã«ã¡ã¯ïŒãå
æ°ã§ããïŒ
Human: å
æ°ã§ããããªãã¯ïŒ
Chatbot:
> Finished LLMChain chain.
' ã¯ããå
æ°ã§ãïŒæè¿äœãããŠããŸããïŒ'(5) æšè«ã®å®è¡ã
ããã³ããã«éå»ãã°ãå«ãŸããŠããããšãããããŸãã
llm_chain.predict(human_input="å
æ°ã§ããããªãã¯ïŒ")> Entering new LLMChain chain...
Prompt after formatting:
ããªãã¯äººéãšäŒè©±ãããã£ãããããã§ãã
Human: ããã«ã¡ã¯ïŒ
AI: ããã«ã¡ã¯ïŒãå
æ°ã§ããïŒ
Human: å
æ°ã§ããããªãã¯ïŒ
Chatbot:
> Finished LLMChain chain.
' ã¯ããå
æ°ã§ãïŒæè¿äœãããŠããŸããïŒ'3. ãã«ãå ¥åãã§ãŒã³ãžã®ã¡ã¢ãªã®è¿œå
å€ãã®ã¡ã¢ãªãªããžã§ã¯ãã¯ãåäžã®åºåãåæãšããŠããŸãããè€æ°ã®åºåãæãããããšãã§ããŸãã
(1) ããã±ãŒãžã®ã€ã³ããŒãã
# ããã±ãŒãžã®ã€ã³ããŒã
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.embeddings.cohere import CohereEmbeddings
from langchain.text_splitter import CharacterTextSplitter
from langchain.vectorstores.elastic_vector_search import ElasticVectorSearch
from langchain.vectorstores.faiss import FAISS
from langchain.docstore.document import Document
from langchain.chains.question_answering import load_qa_chain
from langchain.llms import OpenAI
from langchain.prompts import PromptTemplate
from langchain.chains.conversation.memory import ConversationBufferMemory(2) ããã¥ã¡ã³ããæºåããColabã«ã¢ããããŒãã
ä»åã¯ãWikipediaã®ãã©ãŽã³ããŒã«ã®ãããããèšè¿°ããããã¹ããã¡ã€ã«ãdragonball.txtããçšæããŸãã
ã»dragonball.txt (9KBã»ã©)
å«æç©ºå°å¹Žç·š
å°çã®äººéé¢ãã山奥ã«äœã尻尟ã®çããå°å¹Žã»å«æç©ºã¯ããæ¥ã西ã®éœãããã£ãŠæ¥ãå°å¥³ã»ãã«ããšåºäŒããããã§ã7ã€éãããšç¥éŸïŒã·ã§ã³ãã³ïŒãçŸããã©ããªé¡ãã§ãäžã€ã ãå¶ããŠããããšãããã©ãŽã³ããŒã«ã®ååšããããã«è²ãŠã®èŠªã§ãã嫿飝ã®åœ¢èŠãšããŠå€§åã«æã£ãŠããçããã®1ã€ãåæçïŒã¹ãŒã·ã³ãã¥ãŠïŒãã§ããããšãç¥ãããã«ããšå
±ã«æ®ãã®ãã©ãŽã³ããŒã«ãæ¢ãæ
ã«åºãã人ãããã®ãŠãŒãã³ãçè³ã®ã€ã ãã£ããå·»ã蟌ãã ããŒã«æ¢ãã®æ«ãäžçåŸæãäŒããã©ãäžå³ã«ããŒã«ã奪ããç¥éŸãåŒã³åºããããããŠãŒãã³ããšã£ãã«èšãæŸã£ãäžããªãé¡ããå¶ããŠãããããšã§äžå³ã®éæã黿¢ããã
ãã®åŸãæç©ºã¯æ
ã®éäžã«ç¥ãåã£ãæŠè¡ã®é人ã»äºä»äººã®äžã§ãåŸã«èŠªåãšãªãã¯ãªãªã³ãšå
±ã«8ãæéã«ãããä¿®è¡ãç©ã¿ããã®ææã確ãããããã«äžçäžã®æŠè¡ã®éäººãæ±ºãã倩äžäžæŠéäŒã«åºå Žããå€è£
ããŠåºå ŽããŠããäºä»äººã«æãããæºåªåãæãããæç©ºã¯åã³ä¿®è¡ã®æ
ãžãšåºçºãããã©ãŽã³ããŒã«ã®æªçšãäŒãã¬ãããªãã³è»ãšã®éããã嫿飝ãšã®åäŒãªã©ãçµãŠããã«åŒ·ããå¢ããŠãããããã«3幎åŸã®å€©äžäžæŠéäŒã§ã¯ãäºä»æµã®ã©ã€ãã«ã§ããé¶Žä»æµã®å€©æŽ¥é£¯ïŒãŠãããã¯ãïŒãšéãããããšäžæ©ã®ãšããã§æããååãšåããæºåªåã«çµããã
ããã³ã倧éçç·š
倩äžäžæŠéäŒçµäºåŸã
:(3) ããã¹ãã®èªã¿èŸŒã¿ãšåå²
# ããã¹ãã®èªã¿èŸŒã¿ãšåå²
with open('dragonball.txt') as f:
doragonball_txt = f.read()
text_splitter = CharacterTextSplitter(chunk_size=500, chunk_overlap=0)
texts = text_splitter.split_text(doragonball_txt)(4) é¢é£ãããã£ã³ã¯ã®æœåº
# é¢é£ãããã£ã³ã¯ã®æœåº
embeddings = OpenAIEmbeddings()
docsearch = FAISS.from_texts(
texts,
embeddings,
metadatas=[{"source": i} for i in range(len(texts))]
)
query = "ãã©ã³ã¯ã¹ã®èŠªã¯èª°ïŒ"
docs = docsearch.similarity_search(query)
docs = docs[:2] # 4ã€ã ãšå€ãã®ã§2ã€ã«çµã(5) ãã³ãã¬ãŒããšããã³ãããã³ãã¬ãŒããšã¡ã¢ãªãšãã§ãŒã³ã®æºåã
# ãã³ãã¬ãŒãã®æºå
template = """ããªãã¯äººéãšäŒè©±ãããã£ãããããã§ãã
次ã®é·ãããã¥ã¡ã³ããšè³ªåã®äžéšãæç²ããŠãæçµçãªåçãäœæããŸãã
{context}
{chat_history}
Human: {human_input}
Chatbot:"""
# ããã³ãããã³ãã¬ãŒãã®æºå
prompt = PromptTemplate(
input_variables=["chat_history", "human_input", "context"],
template=template
)
# ã¡ã¢ãªã®æºå
memory = ConversationBufferMemory(memory_key="chat_history", input_key="human_input")
# ãã§ãŒã³ã®æºå
chain = load_qa_chain(
OpenAI(temperature=0),
chain_type="stuff",
memory=memory,
prompt=prompt)(6) æšè«ã®å®è¡ã
chain({"input_documents": docs, "human_input": query}, return_only_outputs=True){'output_text': ' ãã©ã³ã¯ã¹ã®èŠªã¯ããã«ããšããžãŒã¿ã®äºäººã§ãã'}(7) ã¡ã¢ãªãããã¡ã®ç¢ºèªã
print(chain.memory.buffer)Human: ãã©ã³ã¯ã¹ã®èŠªã¯èª°ïŒ
AI: ãã©ã³ã¯ã¹ã®èŠªã¯ããã«ããšããžãŒã¿ã®äºäººã§ãã4. äŒè©±ã¡ã¢ãª
LangChainã§ã¯ãäŒè©±ã«åœ¹ç«ã€ã¡ã¢ãªãããã€ãæäŸãããŠããŸãã
4-1. ConversationBufferMemory
éå»ã®äŒè©±ãã°ããã¹ãŠããã³ããã«è¿œå ããåçŽãªã¡ã¢ãªã§ãã
(1) ConversationChainã®æºåããã¡ã¢ãªã«ConversationBufferMemoryãæå®ã
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.chains.conversation.memory import ConversationBufferMemory
# ConversationChainã®æºå
conversation = ConversationChain(
llm=OpenAI(),
memory=ConversationBufferMemory(),
verbose=True,
)(2) æšè«ã®å®è¡ã
# æšè«ã®å®è¡
conversation.predict(input="ããã«ã¡ã¯ïŒ")> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: ããã«ã¡ã¯ïŒ
AI:
> Finished ConversationChain chain.
' ããã«ã¡ã¯ïŒç§ã¯AIã§ããã©ãããããããé¡ãããŸãïŒ(3) æšè«ã®å®è¡ã
éå»ã®äŒè©±ãã°ãããã³ããã«è¿œå ãããŠããããšãããããŸãã
# æšè«ã®å®è¡
conversation.predict(input="äŒã¿ã®æ¥ã¯äœããŠãŸããïŒ")> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: ããã«ã¡ã¯ïŒ
AI: ããã«ã¡ã¯ïŒç§ã¯AIã§ããã©ãããããããé¡ãããŸãïŒ
Human: äŒã¿ã®æ¥ã¯äœããŠãŸããïŒ
AI:
> Finished ConversationChain chain.
' äŒã¿ã®æ¥ã¯ãå®¶æãå人ãšã®æéãæ¥œããã ããæ°ããããšã«ææŠãããããŠããŸããæè¿ã¯ãæ°ããããã°ã©ãã³ã°èšèªãåŠãã ããæ°ããã¬ã·ãã詊ãããããŠããŸãã'4-2. ConversationSummaryMemory
éå»ã®äŒè©±ãã°ã®èŠçŽãããã³ããã«è¿œå ããã¡ã¢ãªã§ãã
(1) ConversationChainã®æºåããã¡ã¢ãªã«ConversationSummaryMemoryãæå®ã
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.chains.conversation.memory import ConversationSummaryMemory
# ConversationChainã®æºå
conversation_with_summary = ConversationChain(
llm=OpenAI(),
memory=ConversationSummaryMemory(llm=OpenAI()),
verbose=True
)(2) æšè«ã®å®è¡ã
# æšè«ã®å®è¡
conversation_with_summary.predict(input="ãè
¹ã空ããŸãã")> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: ãè
¹ã空ããŸãã
AI:
> Finished ConversationChain chain.
' ãè
¹ã空ãããã§ããïŒãè
¹ã空ããããã©ããªæçãé£ã¹ããã§ããïŒ'(3) æšè«ã®å®è¡ã
éå»ã®äŒè©±ãã°ã®èŠçŽãããã³ããã«è¿œå ãããŠããããšãããããŸãã
(è±èªã§ã¯ãããŸãã)
# æšè«ã®å®è¡
conversation_with_summary.predict(input="ãã³ããŒã°ãé£ã¹ããã§ã")> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
The human asks what the AI thinks of artificial intelligence. The AI thinks artificial intelligence is a force for good because it will help humans reach their full potential. The human then states that they are hungry, to which the AI responds asking what kind of food they would like to eat.
Human: ãã³ããŒã°ãé£ã¹ããã§ã
AI:
> Finished ConversationChain chain.
' ã¯ãããã³ããŒã°ã§ããïŒããããã§ãããïŒã©ãã§ãã³ããŒã°ãè²·ãã°ããã§ããïŒ'4-3. ConversationBufferWindowMemory
æåŸã®Kååã®å¯Ÿè©±ãããã³ããã«è¿œå ããã¡ã¢ãªã§ãã
(1) ConversationChainã®æºåããã¡ã¢ãªã«ConversationBufferWindowMemoryãæå®ã
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.chains.conversation.memory import ConversationBufferWindowMemory
# ConversationChainã®æºå
conversation_with_summary = ConversationChain(
llm=OpenAI(),
memory=ConversationBufferWindowMemory(k=2),
verbose=True
)4-4. ConversationSummaryBufferMemory
éå»ã®äŒè©±ãã°ã®èŠçŽãšæåŸã®KããŒã¯ã³åã®å¯Ÿè©±ãããã³ããã«è¿œå ããã¡ã¢ãªã§ãã
(1) ConversationChainã®æºåããã¡ã¢ãªã«ConversationBufferWindowMemoryãæå®ã
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.chains.conversation.memory import ConversationSummaryBufferMemory
# ConversationChainã®æºå
conversation_with_summary = ConversationChain(
llm=OpenAI(),
memory=ConversationSummaryBufferMemory(llm=OpenAI(), max_token_limit=40),
verbose=True
)5. äŒè©±ã¡ã¢ãªã®ã«ã¹ã¿ãã€ãº
äŒè©±ã¡ã¢ãªã®ã«ã¹ã¿ãã€ãºãšããŠããap_prefixãã倿Žããããšãã§ããŸããããã©ã«ãã§ã¯ãAIãã«èšå®ãããŠããŸãããä»»æã«èšå®ã§ããŸãã
(1) ConversationChainã®æºåã
ä»åã¯ãAIãã¬ãã£ãã¯ã¹ããAI Assistantãã«ããŠã¿ãŸããã
from langchain.prompts.prompt import PromptTemplate
# ãã³ãã¬ãŒãã®æºå
template = """以äžã¯ãHumanãšAIã®éã®å奜çãªäŒè©±ã§ãã
AIã¯ãããã¹ãã§ããã®ã³ã³ããã¹ãããå€ãã®å
·äœçãªè©³çްãæäŸããŸãã
AIã質åã«å¯Ÿããçããç¥ããªãå Žåãæ£çŽã«"ç¥ããªã"ãšèšããŸãã
Current conversation:
{history}
Human: {input}
AI Assistant:"""
# ããã³ãããã³ãã¬ãŒãã®æºå
prompt = PromptTemplate(
input_variables=["history", "input"], template=template
)
# ConversationChainã®æºå
conversation = ConversationChain(
prompt=prompt,
llm=OpenAI(),
verbose=True,
memory=ConversationBufferMemory(ai_prefix="AI Assistant")
)(2) æšè«ã®å®è¡ã
# æšè«ã®å®è¡ã
conversation.predict(input="ããã«ã¡ã¯")> Entering new ConversationChain chain...
Prompt after formatting:
以äžã¯ãHumanãšAIã®éã®å奜çãªäŒè©±ã§ãã
AIã¯ãããã¹ãã§ããã®ã³ã³ããã¹ãããå€ãã®å
·äœçãªè©³çްãæäŸããŸãã
AIã質åã«å¯Ÿããçããç¥ããªãå Žåãæ£çŽã«"ç¥ããªã"ãšèšããŸãã
Current conversation:
Human: ããã«ã¡ã¯
AI Assistant:
> Finished ConversationChain chain.
' ããã«ã¡ã¯ïŒç§ã¯ããªãã®AIã¢ã·ã¹ã¿ã³ãã§ãã仿¥ã¯äœãããŸããïŒ'(3) æšè«ã®å®è¡ã
AIãã¬ãã£ãã¯ã¹ããAI Assistantãã«ãªã£ãŠããããšãããããŸãã
conversation.predict(input="仿¥ã®é座ã®éå¢ã¯ïŒ")> Entering new ConversationChain chain...
Prompt after formatting:
以äžã¯ãHumanãšAIã®éã®å奜çãªäŒè©±ã§ãã
AIã¯ãããã¹ãã§ããã®ã³ã³ããã¹ãããå€ãã®å
·äœçãªè©³çްãæäŸããŸãã
AIã質åã«å¯Ÿããçããç¥ããªãå Žåãæ£çŽã«"ç¥ããªã"ãšèšããŸãã
Current conversation:
Human: ããã«ã¡ã¯
AI Assistant: ããã«ã¡ã¯ïŒç§ã¯ããªãã®AIã¢ã·ã¹ã¿ã³ãã§ãã仿¥ã¯äœãããŸããïŒ
Human: 仿¥ã®é座ã®éå¢ã¯ïŒ
AI Assistant:
> Finished ConversationChain chain.
' 仿¥ã®é座ã®éå¢ã¯ã仿¥ã¯ããªããèªåã®å€¢ãå®çŸããããã«åªåããŠããããšã瀺ããŠããŸããããªãã¯ãèªåã®èœåãæå€§éã«æŽ»çšããŠãèªåã®å€¢ãå®çŸããããã«åªåããŠããããšã瀺ããŠããŸãã'6. ãšãŒãžã§ã³ããžã®ã¡ã¢ãªã®è¿œå
ãšãŒãžã§ã³ããžã®ã¡ã¢ãªã®è¿œå ãè¡ãã«ã¯ãã«ã¹ã¿ã ãšãŒãžã§ã³ããäœæããå¿ èŠããããŸãã
(1) ããŒã«ãšããã³ãããã³ãã¬ãŒããšã¡ã¢ãªã®æºåã
from langchain.agents import ZeroShotAgent, Tool, AgentExecutor
from langchain.chains.conversation.memory import ConversationBufferMemory
from langchain import OpenAI, SerpAPIWrapper, LLMChain
# ããŒã«ã®æºå
search = SerpAPIWrapper()
tools = [
Tool(
name = "Search",
func=search.run,
description="useful for when you need to answer questions about current events"
)
]
# ããã³ãããã³ãã¬ãŒãã®æºå #prefix = """Have a conversation with a human, answering the following questions as best you can. You have access to the following tools:""" #suffix = """Begin!"
prefix = """人éãšäŒè©±ããŠã次ã®è³ªåã«ã§ããéãçããŠãã ããã æ¬¡ã®ããŒã«ã«ã¢ã¯ã»ã¹ã§ããŸãã"""
suffix = """å§ã!"
{chat_history}
Question: {input}
{agent_scratchpad}"""
prompt = ZeroShotAgent.create_prompt(
tools,
prefix=prefix,
suffix=suffix,
input_variables=["input", "chat_history", "agent_scratchpad"]
)
# ã¡ã¢ãªã®æºå
memory = ConversationBufferMemory(memory_key="chat_history")(2) ãšãŒãžã§ã³ãã®æºåã
# ãšãŒãžã§ã³ãã®æºå
llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt)
agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True)
agent_chain = AgentExecutor.from_agent_and_tools(
agent=agent,
tools=tools,
verbose=True,
memory=memory
)(3) ãšãŒãžã§ã³ãã®å®è¡ã
# ãšãŒãžã§ã³ãã®å®è¡
agent_chain.run(input="æ¥æ¬ã®äººå£ã¯ïŒ")> Entering new AgentExecutor chain...
Thought: æ¥æ¬ã®äººå£ã調ã¹ã
Action: Search
Action Input: æ¥æ¬ã®äººå£
Observation: Japan is an island country in East Asia. It is situated in the northwest Pacific Ocean, and is bordered on the west by the Sea of Japan, while extending from the Sea of Okhotsk in the north toward the East China Sea, Philippine Sea, and Taiwan in the south.
Thought: æ¥æ¬ã®äººå£ã確èªãã
Action: Search
Action Input: æ¥æ¬ã®äººå£ 2020
Observation: Japan is an island country in East Asia. It is situated in the northwest Pacific Ocean, and is bordered on the west by the Sea of Japan, while extending from the Sea of Okhotsk in the north toward the East China Sea, Philippine Sea, and Taiwan in the south.
Thought: æ¥æ¬ã®2020幎ã®äººå£ã確èªãã
Action: Search
Action Input: æ¥æ¬ã®äººå£ 2020
Observation: Japan is an island country in East Asia. It is situated in the northwest Pacific Ocean, and is bordered on the west by the Sea of Japan, while extending from the Sea of Okhotsk in the north toward the East China Sea, Philippine Sea, and Taiwan in the south.
Thought: æ¥æ¬ã®2020幎ã®äººå£ã確èªãã
Final Answer: 2020å¹Žã®æ¥æ¬ã®äººå£ã¯1å2700äžäººã§ãã
> Finished AgentExecutor chain.
'2020å¹Žã®æ¥æ¬ã®äººå£ã¯1å2700äžäººã§ãã(4) ãšãŒãžã§ã³ãã®å®è¡ã
éå»ã®äŒè©±ãèŠããŠããããšã確èªããŸãã
# ãšãŒãžã§ã³ãã®å®è¡
agent_chain.run(input="圌ãã®åœæã®ååã¯ïŒ")> Entering new AgentExecutor chain...
Thought: æ¥æ¬ã®åœæã®ååãæ€çŽ¢ãã
Action: Search
Action Input: æ¥æ¬ã®åœæã®åå
Observation: ãåã代ãïŒãã¿ããïŒã¯ãæ¥æ¬åœã®åœæã ã倩çã®æ²»äžããå¥ç¥ããæã§ããããç¥çŠãåãã人ã®å¯¿åœããæãåæãå
ã«ããŠããã æè©ã¯10äžçŽåãã«ç·šçºããããå€ä»åæéãã®çæã®äžã€ã§ãæ²ã¯1880å¹ŽïŒææ²»13幎ïŒã«ä»ããããã
Thought: æ¥æ¬ã®åœæã®ååã確èªãã
Final Answer: æ¥æ¬ã®åœæã®ååã¯ãåã代ãïŒãã¿ããïŒã§ãã
> Finished AgentExecutor chain.
'æ¥æ¬ã®åœæã®ååã¯ãåã代ãïŒãã¿ããïŒã§ãã'7. ã«ã¹ã¿ã ã¡ã¢ãª
ã«ã¹ã¿ã LLMã®å®è£
æé ã¯ã次ã®ãšããã§ãã
spacyã§ãšã³ãã£ãã£ãæœåºããããã«é¢ããæ
å ±ãããã·ã¥ããŒãã«ã§ä¿æããã«ã¹ã¿ã ã¡ã¢ãªãäœããŸãã
(1) spacyã®ã€ã³ã¹ããŒã«ã
!pip install spacy
!python -m spacy download ja_core_news_lg(2) ããã±ãŒãžã®ã€ã³ããŒãã
from langchain import OpenAI, ConversationChain
from langchain.chains.base import Memory
from pydantic import BaseModel
from typing import List, Dict, Any(3) spacyã®æºåã
import spacy
# Spacyã®æºå
nlp = spacy.load('ja_core_news_lg')(4) ã«ã¹ã¿ã ã¡ã¢ãªã®æºåã
# ã«ã¹ã¿ã ã¡ã¢ãªãŒã®æºå
class SpacyEntityMemory(Memory, BaseModel):
entities: dict = {} # ãšã³ãã£ãã£æ
å ±
memory_key: str = "entities" # ãšã³ãã£ãã£æ
å ±ãããã³ããã«æž¡ãããã®ããŒ
# ããã³ããã«æäŸãã倿°ã®ååŸ
@property
def memory_variables(self) -> List[str]:
return [self.memory_key]
# ã¡ã¢ãªå€æ°ã®ååŸ
def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:
# å
¥åããã¹ãã«spacyãé©çš
doc = nlp(inputs[list(inputs.keys())[0]])
# ãšã³ãã£ãã£ãååšããå Žåã¯ãšã³ãã£ãã£æ
å ±ãæœåº
entities = [self.entities[str(ent)] for ent in doc.ents if str(ent) in self.entities]
# ã¡ã¢ãªå€æ°ãè¿ã
return {self.memory_key: "\n".join(entities)}
# äŒè©±ã®ã³ã³ããã¹ãããããã¡ã«ä¿å
def save_context(self, inputs: Dict[str, Any], outputs: Dict[str, str]) -> None:
# å
¥åããã¹ãã«spacyãé©çš
text = inputs[list(inputs.keys())[0]]
doc = nlp(text)
# ãšã³ãã£ãã£ããšã«æ
å ±ãèŸæžã«ä¿å
for ent in doc.ents:
ent_str = str(ent)
if ent_str in self.entities:
self.entities[ent_str] += f"\n{text}"
else:
self.entities[ent_str] = text
# ã¡ã¢ãªã®ã¯ãªã¢
def clear(self) -> None:
self.entities = {}(5) ããã³ãããã³ãã¬ãŒãã®æºåã
from langchain.prompts.prompt import PromptTemplate
# ããã³ãããã³ãã¬ãŒãã®æºå
template = """以äžã¯ã人éãš AI ã®éã®å奜çãªäŒè©±ã§ãã
AI ã¯ãããã¹ãã§ããã®ã³ã³ããã¹ãããå€ãã®å
·äœçãªè©³çްãæäŸããŸãã
AI ã質åã«å¯Ÿããçããç¥ããªãå ŽåãAI ã¯æ£çŽã«ãç¥ããªãããšèšããŸãã
é¢é£ããå Žåã人éãèšåãããšã³ãã£ãã£ã«é¢ããæ
å ±ãæäŸãããŸãã
Relevant entity information:
{entities}
Conversation:
Human: {input}
AI:"""
prompt = PromptTemplate(
input_variables=["entities", "input"], template=template
)(6) LLMãšConversationChainã®æºåã
# LLMã®æºå
llm = OpenAI(temperature=0)
# ConversationChainã®æºå
conversation = ConversationChain(
llm=llm,
prompt=prompt,
verbose=True,
memory=SpacyEntityMemory()
)(7) ãã§ãŒã³ã®å®è¡ã
conversation.predict(input="ããªãœã³ã¯æ©æ¢°åŠç¿ã奜ã")> Entering new ConversationChain chain...
Prompt after formatting:
以äžã¯ã人éãš AI ã®éã®å奜çãªäŒè©±ã§ãã
AI ã¯ãããã¹ãã§ããã®ã³ã³ããã¹ãããå€ãã®å
·äœçãªè©³çްãæäŸããŸãã
AI ã質åã«å¯Ÿããçããç¥ããªãå ŽåãAI ã¯æ£çŽã«ãç¥ããªãããšèšããŸãã
é¢é£ããå Žåã人éãèšåãããšã³ãã£ãã£ã«é¢ããæ
å ±ãæäŸãããŸãã
Relevant entity information:
Conversation:
Human: ããªãœã³ã¯æ©æ¢°åŠç¿ã奜ã
AI:
> Finished ConversationChain chain.
' ããã§ããïŒããªãœã³ã¯ãæ©æ¢°åŠç¿ã䜿ã£ããããžã§ã¯ãã«åãçµãã§ããŸãããŸãã圌ã¯ãæ©æ¢°åŠç¿ã䜿ã£ããœãããŠã§ã¢éçºã«ãåãçµãã§ããŸãã(8) ãã§ãŒã³ã®å®è¡ã
conversation.predict(input="ããªãœã³ã倧åŠã§å¥œãã ã£ãç§ç®ã¯äœã ãšæããŸãã?")> Entering new ConversationChain chain...
Prompt after formatting:
以äžã¯ã人éãš AI ã®éã®å奜çãªäŒè©±ã§ãã
AI ã¯ãããã¹ãã§ããã®ã³ã³ããã¹ãããå€ãã®å
·äœçãªè©³çްãæäŸããŸãã
AI ã質åã«å¯Ÿããçããç¥ããªãå ŽåãAI ã¯æ£çŽã«ãç¥ããªãããšèšããŸãã
é¢é£ããå Žåã人éãèšåãããšã³ãã£ãã£ã«é¢ããæ
å ±ãæäŸãããŸãã
Relevant entity information:
ããªãœã³ã¯æ©æ¢°åŠç¿ã奜ã
Conversation:
Human: ããªãœã³ã倧åŠã§å¥œãã ã£ãç§ç®ã¯äœã ãšæããŸãã?
AI:
> Finished ConversationChain chain.
' ããªãœã³ã¯æ©æ¢°åŠç¿ã倧åŠã§å¥œãã ã£ããšèããŠããŸãã