mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-05 17:35:28 +03:00
…tch]: import models from community ran ```bash git grep -l 'from langchain\.chat_models' | xargs -L 1 sed -i '' "s/from\ langchain\.chat_models/from\ langchain_community.chat_models/g" git grep -l 'from langchain\.llms' | xargs -L 1 sed -i '' "s/from\ langchain\.llms/from\ langchain_community.llms/g" git grep -l 'from langchain\.embeddings' | xargs -L 1 sed -i '' "s/from\ langchain\.embeddings/from\ langchain_community.embeddings/g" git checkout master libs/langchain/tests/unit_tests/llms git checkout master libs/langchain/tests/unit_tests/chat_models git checkout master libs/langchain/tests/unit_tests/embeddings/test_imports.py make format cd libs/langchain; make format cd ../experimental; make format cd ../core; make format ```
42 KiB
42 KiB
Cell:
[Cell type raw - unsupported, skipped]
In [1]:
from langchain.prompts import ChatPromptTemplate
from langchain_community.chat_models import ChatOpenAI
model = ChatOpenAI()
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
chain = prompt | modelIn [13]:
# The input schema of the chain is the input schema of its first part, the prompt.
chain.input_schema.schema()Out [13]:
{'title': 'PromptInput',
'type': 'object',
'properties': {'topic': {'title': 'Topic', 'type': 'string'}}}In [16]:
prompt.input_schema.schema()Out [16]:
{'title': 'PromptInput',
'type': 'object',
'properties': {'topic': {'title': 'Topic', 'type': 'string'}}}In [15]:
model.input_schema.schema()Out [15]:
{'title': 'ChatOpenAIInput',
'anyOf': [{'type': 'string'},
{'$ref': '#/definitions/StringPromptValue'},
{'$ref': '#/definitions/ChatPromptValueConcrete'},
{'type': 'array',
'items': {'anyOf': [{'$ref': '#/definitions/AIMessage'},
{'$ref': '#/definitions/HumanMessage'},
{'$ref': '#/definitions/ChatMessage'},
{'$ref': '#/definitions/SystemMessage'},
{'$ref': '#/definitions/FunctionMessage'}]}}],
'definitions': {'StringPromptValue': {'title': 'StringPromptValue',
'description': 'String prompt value.',
'type': 'object',
'properties': {'text': {'title': 'Text', 'type': 'string'},
'type': {'title': 'Type',
'default': 'StringPromptValue',
'enum': ['StringPromptValue'],
'type': 'string'}},
'required': ['text']},
'AIMessage': {'title': 'AIMessage',
'description': 'A Message from an AI.',
'type': 'object',
'properties': {'content': {'title': 'Content', 'type': 'string'},
'additional_kwargs': {'title': 'Additional Kwargs', 'type': 'object'},
'type': {'title': 'Type',
'default': 'ai',
'enum': ['ai'],
'type': 'string'},
'example': {'title': 'Example', 'default': False, 'type': 'boolean'}},
'required': ['content']},
'HumanMessage': {'title': 'HumanMessage',
'description': 'A Message from a human.',
'type': 'object',
'properties': {'content': {'title': 'Content', 'type': 'string'},
'additional_kwargs': {'title': 'Additional Kwargs', 'type': 'object'},
'type': {'title': 'Type',
'default': 'human',
'enum': ['human'],
'type': 'string'},
'example': {'title': 'Example', 'default': False, 'type': 'boolean'}},
'required': ['content']},
'ChatMessage': {'title': 'ChatMessage',
'description': 'A Message that can be assigned an arbitrary speaker (i.e. role).',
'type': 'object',
'properties': {'content': {'title': 'Content', 'type': 'string'},
'additional_kwargs': {'title': 'Additional Kwargs', 'type': 'object'},
'type': {'title': 'Type',
'default': 'chat',
'enum': ['chat'],
'type': 'string'},
'role': {'title': 'Role', 'type': 'string'}},
'required': ['content', 'role']},
'SystemMessage': {'title': 'SystemMessage',
'description': 'A Message for priming AI behavior, usually passed in as the first of a sequence\nof input messages.',
'type': 'object',
'properties': {'content': {'title': 'Content', 'type': 'string'},
'additional_kwargs': {'title': 'Additional Kwargs', 'type': 'object'},
'type': {'title': 'Type',
'default': 'system',
'enum': ['system'],
'type': 'string'}},
'required': ['content']},
'FunctionMessage': {'title': 'FunctionMessage',
'description': 'A Message for passing the result of executing a function back to a model.',
'type': 'object',
'properties': {'content': {'title': 'Content', 'type': 'string'},
'additional_kwargs': {'title': 'Additional Kwargs', 'type': 'object'},
'type': {'title': 'Type',
'default': 'function',
'enum': ['function'],
'type': 'string'},
'name': {'title': 'Name', 'type': 'string'}},
'required': ['content', 'name']},
'ChatPromptValueConcrete': {'title': 'ChatPromptValueConcrete',
'description': 'Chat prompt value which explicitly lists out the message types it accepts.\nFor use in external schemas.',
'type': 'object',
'properties': {'messages': {'title': 'Messages',
'type': 'array',
'items': {'anyOf': [{'$ref': '#/definitions/AIMessage'},
{'$ref': '#/definitions/HumanMessage'},
{'$ref': '#/definitions/ChatMessage'},
{'$ref': '#/definitions/SystemMessage'},
{'$ref': '#/definitions/FunctionMessage'}]}},
'type': {'title': 'Type',
'default': 'ChatPromptValueConcrete',
'enum': ['ChatPromptValueConcrete'],
'type': 'string'}},
'required': ['messages']}}}In [17]:
# The output schema of the chain is the output schema of its last part, in this case a ChatModel, which outputs a ChatMessage
chain.output_schema.schema()Out [17]:
{'title': 'ChatOpenAIOutput',
'anyOf': [{'$ref': '#/definitions/HumanMessage'},
{'$ref': '#/definitions/AIMessage'},
{'$ref': '#/definitions/ChatMessage'},
{'$ref': '#/definitions/FunctionMessage'},
{'$ref': '#/definitions/SystemMessage'}],
'definitions': {'HumanMessage': {'title': 'HumanMessage',
'description': 'A Message from a human.',
'type': 'object',
'properties': {'content': {'title': 'Content', 'type': 'string'},
'additional_kwargs': {'title': 'Additional Kwargs', 'type': 'object'},
'type': {'title': 'Type',
'default': 'human',
'enum': ['human'],
'type': 'string'},
'example': {'title': 'Example', 'default': False, 'type': 'boolean'}},
'required': ['content']},
'AIMessage': {'title': 'AIMessage',
'description': 'A Message from an AI.',
'type': 'object',
'properties': {'content': {'title': 'Content', 'type': 'string'},
'additional_kwargs': {'title': 'Additional Kwargs', 'type': 'object'},
'type': {'title': 'Type',
'default': 'ai',
'enum': ['ai'],
'type': 'string'},
'example': {'title': 'Example', 'default': False, 'type': 'boolean'}},
'required': ['content']},
'ChatMessage': {'title': 'ChatMessage',
'description': 'A Message that can be assigned an arbitrary speaker (i.e. role).',
'type': 'object',
'properties': {'content': {'title': 'Content', 'type': 'string'},
'additional_kwargs': {'title': 'Additional Kwargs', 'type': 'object'},
'type': {'title': 'Type',
'default': 'chat',
'enum': ['chat'],
'type': 'string'},
'role': {'title': 'Role', 'type': 'string'}},
'required': ['content', 'role']},
'FunctionMessage': {'title': 'FunctionMessage',
'description': 'A Message for passing the result of executing a function back to a model.',
'type': 'object',
'properties': {'content': {'title': 'Content', 'type': 'string'},
'additional_kwargs': {'title': 'Additional Kwargs', 'type': 'object'},
'type': {'title': 'Type',
'default': 'function',
'enum': ['function'],
'type': 'string'},
'name': {'title': 'Name', 'type': 'string'}},
'required': ['content', 'name']},
'SystemMessage': {'title': 'SystemMessage',
'description': 'A Message for priming AI behavior, usually passed in as the first of a sequence\nof input messages.',
'type': 'object',
'properties': {'content': {'title': 'Content', 'type': 'string'},
'additional_kwargs': {'title': 'Additional Kwargs', 'type': 'object'},
'type': {'title': 'Type',
'default': 'system',
'enum': ['system'],
'type': 'string'}},
'required': ['content']}}}In [20]:
for s in chain.stream({"topic": "bears"}):
print(s.content, end="", flush=True)Why don't bears wear shoes? Because they already have bear feet!
In [21]:
chain.invoke({"topic": "bears"})Out [21]:
AIMessage(content="Why don't bears wear shoes?\n\nBecause they already have bear feet!")
In [22]:
chain.batch([{"topic": "bears"}, {"topic": "cats"}])Out [22]:
[AIMessage(content="Why don't bears wear shoes?\n\nBecause they have bear feet!"), AIMessage(content="Why don't cats play poker in the wild?\n\nToo many cheetahs!")]
In [23]:
chain.batch([{"topic": "bears"}, {"topic": "cats"}], config={"max_concurrency": 5})Out [23]:
[AIMessage(content="Why don't bears wear shoes? \n\nBecause they have bear feet!"), AIMessage(content="Why don't cats play poker in the wild?\n\nToo many cheetahs!")]
In [24]:
async for s in chain.astream({"topic": "bears"}):
print(s.content, end="", flush=True)Sure, here's a bear-themed joke for you: Why don't bears wear shoes? Because they already have bear feet!
In [25]:
await chain.ainvoke({"topic": "bears"})Out [25]:
AIMessage(content="Why don't bears wear shoes? \n\nBecause they have bear feet!")
In [26]:
await chain.abatch([{"topic": "bears"}])Out [26]:
[AIMessage(content="Why don't bears wear shoes?\n\nBecause they have bear feet!")]
In [29]:
from langchain.vectorstores import FAISS
from langchain_community.embeddings import OpenAIEmbeddings
from langchain_core.output_parsers import StrOutputParser
from langchain_core.runnables import RunnablePassthrough
template = """Answer the question based only on the following context:
{context}
Question: {question}
"""
prompt = ChatPromptTemplate.from_template(template)
vectorstore = FAISS.from_texts(
["harrison worked at kensho"], embedding=OpenAIEmbeddings()
)
retriever = vectorstore.as_retriever()
retrieval_chain = (
{
"context": retriever.with_config(run_name="Docs"),
"question": RunnablePassthrough(),
}
| prompt
| model
| StrOutputParser()
)
async for chunk in retrieval_chain.astream_log(
"where did harrison work?", include_names=["Docs"]
):
print("-" * 40)
print(chunk)----------------------------------------
RunLogPatch({'op': 'replace',
'path': '',
'value': {'final_output': None,
'id': 'e2f2cc72-eb63-4d20-8326-237367482efb',
'logs': {},
'streamed_output': []}})
----------------------------------------
RunLogPatch({'op': 'add',
'path': '/logs/Docs',
'value': {'end_time': None,
'final_output': None,
'id': '8da492cc-4492-4e74-b8b0-9e60e8693390',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:50:13.526',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}})
----------------------------------------
RunLogPatch({'op': 'add',
'path': '/logs/Docs/final_output',
'value': {'documents': [Document(page_content='harrison worked at kensho')]}},
{'op': 'add',
'path': '/logs/Docs/end_time',
'value': '2023-10-19T17:50:13.713'})
----------------------------------------
RunLogPatch({'op': 'add', 'path': '/streamed_output/-', 'value': ''})
----------------------------------------
RunLogPatch({'op': 'add', 'path': '/streamed_output/-', 'value': 'H'})
----------------------------------------
RunLogPatch({'op': 'add', 'path': '/streamed_output/-', 'value': 'arrison'})
----------------------------------------
RunLogPatch({'op': 'add', 'path': '/streamed_output/-', 'value': ' worked'})
----------------------------------------
RunLogPatch({'op': 'add', 'path': '/streamed_output/-', 'value': ' at'})
----------------------------------------
RunLogPatch({'op': 'add', 'path': '/streamed_output/-', 'value': ' Kens'})
----------------------------------------
RunLogPatch({'op': 'add', 'path': '/streamed_output/-', 'value': 'ho'})
----------------------------------------
RunLogPatch({'op': 'add', 'path': '/streamed_output/-', 'value': '.'})
----------------------------------------
RunLogPatch({'op': 'add', 'path': '/streamed_output/-', 'value': ''})
----------------------------------------
RunLogPatch({'op': 'replace',
'path': '/final_output',
'value': {'output': 'Harrison worked at Kensho.'}})
In [31]:
async for chunk in retrieval_chain.astream_log(
"where did harrison work?", include_names=["Docs"], diff=False
):
print("-" * 70)
print(chunk)----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {},
'streamed_output': []})
----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': None,
'final_output': None,
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': []})
----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': '2023-10-19T17:52:15.738',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': []})
----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': '2023-10-19T17:52:15.738',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['']})
----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': '2023-10-19T17:52:15.738',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H']})
----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': '2023-10-19T17:52:15.738',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison']})
----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': '2023-10-19T17:52:15.738',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison', ' worked']})
----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': '2023-10-19T17:52:15.738',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison', ' worked', ' at']})
----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': '2023-10-19T17:52:15.738',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison', ' worked', ' at', ' Kens']})
----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': '2023-10-19T17:52:15.738',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison', ' worked', ' at', ' Kens', 'ho']})
----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': '2023-10-19T17:52:15.738',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison', ' worked', ' at', ' Kens', 'ho', '.']})
----------------------------------------------------------------------
RunLog({'final_output': None,
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': '2023-10-19T17:52:15.738',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['',
'H',
'arrison',
' worked',
' at',
' Kens',
'ho',
'.',
'']})
----------------------------------------------------------------------
RunLog({'final_output': {'output': 'Harrison worked at Kensho.'},
'id': 'afe66178-d75f-4c2d-b348-b1d144239cd6',
'logs': {'Docs': {'end_time': '2023-10-19T17:52:15.738',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '88d51118-5756-4891-89c5-2f6a5e90cc26',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-19T17:52:15.438',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['',
'H',
'arrison',
' worked',
' at',
' Kens',
'ho',
'.',
'']})
In [32]:
from langchain_core.runnables import RunnableParallel
chain1 = ChatPromptTemplate.from_template("tell me a joke about {topic}") | model
chain2 = (
ChatPromptTemplate.from_template("write a short (2 line) poem about {topic}")
| model
)
combined = RunnableParallel(joke=chain1, poem=chain2)In [43]:
%%time
chain1.invoke({"topic": "bears"})Out [43]:
CPU times: user 54.3 ms, sys: 0 ns, total: 54.3 ms Wall time: 2.29 s
AIMessage(content="Why don't bears wear shoes?\n\nBecause they already have bear feet!")
In [44]:
%%time
chain2.invoke({"topic": "bears"})Out [44]:
CPU times: user 7.8 ms, sys: 0 ns, total: 7.8 ms Wall time: 1.43 s
AIMessage(content="In wild embrace,\nNature's strength roams with grace.")
In [45]:
%%time
combined.invoke({"topic": "bears"})Out [45]:
CPU times: user 167 ms, sys: 921 µs, total: 168 ms Wall time: 1.56 s
{'joke': AIMessage(content="Why don't bears wear shoes?\n\nBecause they already have bear feet!"),
'poem': AIMessage(content="Fierce and wild, nature's might,\nBears roam the woods, shadows of the night.")}In [40]:
%%time
chain1.batch([{"topic": "bears"}, {"topic": "cats"}])Out [40]:
CPU times: user 159 ms, sys: 3.66 ms, total: 163 ms Wall time: 1.34 s
[AIMessage(content="Why don't bears wear shoes?\n\nBecause they already have bear feet!"), AIMessage(content="Sure, here's a cat joke for you:\n\nWhy don't cats play poker in the wild?\n\nBecause there are too many cheetahs!")]
In [41]:
%%time
chain2.batch([{"topic": "bears"}, {"topic": "cats"}])Out [41]:
CPU times: user 165 ms, sys: 0 ns, total: 165 ms Wall time: 1.73 s
[AIMessage(content="Silent giants roam,\nNature's strength, love's emblem shown."), AIMessage(content='Whiskers aglow, paws tiptoe,\nGraceful hunters, hearts aglow.')]
In [42]:
%%time
combined.batch([{"topic": "bears"}, {"topic": "cats"}])Out [42]:
CPU times: user 507 ms, sys: 125 ms, total: 632 ms Wall time: 1.49 s
[{'joke': AIMessage(content="Why don't bears wear shoes?\n\nBecause they already have bear feet!"),
'poem': AIMessage(content="Majestic bears roam,\nNature's wild guardians of home.")},
{'joke': AIMessage(content="Sure, here's a cat joke for you:\n\nWhy did the cat sit on the computer?\n\nBecause it wanted to keep an eye on the mouse!"),
'poem': AIMessage(content='Whiskers twitch, eyes gleam,\nGraceful creatures, feline dream.')}]In [ ]: