mirror of
https://github.com/langchain-ai/langchain.git
synced 2026-10-14 05:39:23 +03:00
<!-- Thank you for contributing to LangChain! Replace this entire comment with: - **Description:** a description of the change, - **Issue:** the issue # it fixes (if applicable), - **Dependencies:** any dependencies required for this change, - **Tag maintainer:** for a quicker response, tag the relevant maintainer (see below), - **Twitter handle:** we announce bigger features on Twitter. If your PR gets announced, and you'd like a mention, we'll gladly shout you out! Please make sure your PR is passing linting and testing before submitting. Run `make format`, `make lint` and `make test` to check this locally. See contribution guidelines for more information on how to write/run tests, lint, etc: https://github.com/langchain-ai/langchain/blob/master/.github/CONTRIBUTING.md If you're adding a new integration, please include: 1. a test for the integration, preferably unit tests that do not rely on network access, 2. an example notebook showing its use. It lives in `docs/extras` directory. If no one reviews your PR within a few days, please @-mention one of @baskaryan, @eyurtsev, @hwchase17. -->
33 KiB
33 KiB
Cell:
[Cell type raw - unsupported, skipped]
In [1]:
from langchain.prompts import ChatPromptTemplate
from langchain.chat_models import ChatOpenAI
In [2]:
model = ChatOpenAI()
In [3]:
prompt = ChatPromptTemplate.from_template("tell me a joke about {topic}")
In [4]:
chain = prompt | model
In [5]:
# The input schema of the chain is the input schema of its first part, the prompt.
chain.input_schema.schema()Out [5]:
{'title': 'PromptInput',
'type': 'object',
'properties': {'topic': {'title': 'Topic', 'type': 'string'}}}In [6]:
# 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 [6]:
{'title': 'ChatOpenAIOutput',
'anyOf': [{'$ref': '#/definitions/HumanMessageChunk'},
{'$ref': '#/definitions/AIMessageChunk'},
{'$ref': '#/definitions/ChatMessageChunk'},
{'$ref': '#/definitions/FunctionMessageChunk'},
{'$ref': '#/definitions/SystemMessageChunk'}],
'definitions': {'HumanMessageChunk': {'title': 'HumanMessageChunk',
'description': 'A Human Message chunk.',
'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'},
'is_chunk': {'title': 'Is Chunk',
'default': True,
'enum': [True],
'type': 'boolean'}},
'required': ['content']},
'AIMessageChunk': {'title': 'AIMessageChunk',
'description': 'A Message chunk 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'},
'is_chunk': {'title': 'Is Chunk',
'default': True,
'enum': [True],
'type': 'boolean'}},
'required': ['content']},
'ChatMessageChunk': {'title': 'ChatMessageChunk',
'description': 'A Chat Message chunk.',
'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'},
'is_chunk': {'title': 'Is Chunk',
'default': True,
'enum': [True],
'type': 'boolean'}},
'required': ['content', 'role']},
'FunctionMessageChunk': {'title': 'FunctionMessageChunk',
'description': 'A Function Message chunk.',
'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'},
'is_chunk': {'title': 'Is Chunk',
'default': True,
'enum': [True],
'type': 'boolean'}},
'required': ['content', 'name']},
'SystemMessageChunk': {'title': 'SystemMessageChunk',
'description': 'A System Message chunk.',
'type': 'object',
'properties': {'content': {'title': 'Content', 'type': 'string'},
'additional_kwargs': {'title': 'Additional Kwargs', 'type': 'object'},
'type': {'title': 'Type',
'default': 'system',
'enum': ['system'],
'type': 'string'},
'is_chunk': {'title': 'Is Chunk',
'default': True,
'enum': [True],
'type': 'boolean'}},
'required': ['content']}}}In [7]:
for s in chain.stream({"topic": "bears"}):
print(s.content, end="", flush=True)
Why don't bears wear shoes? Because they have bear feet!
In [8]:
chain.invoke({"topic": "bears"})
Out [8]:
AIMessage(content="Why don't bears wear shoes?\n\nBecause they have bear feet!")
In [9]:
chain.batch([{"topic": "bears"}, {"topic": "cats"}])
Out [9]:
[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 [10]:
chain.batch([{"topic": "bears"}, {"topic": "cats"}], config={"max_concurrency": 5})
Out [10]:
[AIMessage(content="Why don't bears wear shoes?\n\nBecause they have bear feet!"), AIMessage(content="Sure, here's a cat joke for you:\n\nWhy don't cats play poker in the wild?\n\nToo many cheetahs!")]
In [11]:
async for s in chain.astream({"topic": "bears"}):
print(s.content, end="", flush=True)
Sure, here's a bear joke for you: Why don't bears wear shoes? Because they have bear feet!
In [12]:
await chain.ainvoke({"topic": "bears"})
Out [12]:
AIMessage(content="Why don't bears wear shoes? \n\nBecause they have bear feet!")
In [13]:
await chain.abatch([{"topic": "bears"}])
Out [13]:
[AIMessage(content="Why don't bears wear shoes?\n\nBecause they have bear feet!")]
In [14]:
from langchain.embeddings import OpenAIEmbeddings
from langchain.schema.output_parser import StrOutputParser
from langchain.schema.runnable import RunnablePassthrough
from langchain.vectorstores import FAISS
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(chunk)
RunLogPatch({'op': 'replace',
'path': '',
'value': {'final_output': None,
'id': 'fd6fcf62-c92c-4edf-8713-0fc5df000f62',
'logs': {},
'streamed_output': []}})
RunLogPatch({'op': 'add',
'path': '/logs/Docs',
'value': {'end_time': None,
'final_output': None,
'id': '8c998257-1ec8-4546-b744-c3fdb9728c41',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:35.668',
'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-05T12:52:36.033'})
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 [15]:
async for chunk in retrieval_chain.astream_log("where did harrison work?", include_names=['Docs'], diff=False):
print(chunk)RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {},
'streamed_output': []})
RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': None,
'final_output': None,
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': []})
RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': '2023-10-05T12:52:37.217',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': []})
RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': '2023-10-05T12:52:37.217',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['']})
RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': '2023-10-05T12:52:37.217',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H']})
RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': '2023-10-05T12:52:37.217',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison']})
RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': '2023-10-05T12:52:37.217',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison', ' worked']})
RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': '2023-10-05T12:52:37.217',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison', ' worked', ' at']})
RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': '2023-10-05T12:52:37.217',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison', ' worked', ' at', ' Kens']})
RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': '2023-10-05T12:52:37.217',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison', ' worked', ' at', ' Kens', 'ho']})
RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': '2023-10-05T12:52:37.217',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['', 'H', 'arrison', ' worked', ' at', ' Kens', 'ho', '.']})
RunLog({'final_output': None,
'id': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': '2023-10-05T12:52:37.217',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'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': 'f95ccb87-31f1-48ea-a51c-d2dadde44185',
'logs': {'Docs': {'end_time': '2023-10-05T12:52:37.217',
'final_output': {'documents': [Document(page_content='harrison worked at kensho')]},
'id': '621597dd-d716-4532-938d-debc21a453d1',
'metadata': {},
'name': 'Docs',
'start_time': '2023-10-05T12:52:36.935',
'streamed_output_str': [],
'tags': ['map:key:context', 'FAISS'],
'type': 'retriever'}},
'streamed_output': ['',
'H',
'arrison',
' worked',
' at',
' Kens',
'ho',
'.',
'']})
In [7]:
from langchain.schema.runnable import RunnableMap
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 = RunnableMap({
"joke": chain1,
"poem": chain2,
})
In [11]:
%%time
chain1.invoke({"topic": "bears"})
Out [11]:
CPU times: user 31.7 ms, sys: 8.59 ms, total: 40.3 ms Wall time: 1.05 s
AIMessage(content="Why don't bears like fast food?\n\nBecause they can't catch it!", additional_kwargs={}, example=False)In [12]:
%%time
chain2.invoke({"topic": "bears"})
Out [12]:
CPU times: user 42.9 ms, sys: 10.2 ms, total: 53 ms Wall time: 1.93 s
AIMessage(content="In forest's embrace, bears roam free,\nSilent strength, nature's majesty.", additional_kwargs={}, example=False)In [13]:
%%time
combined.invoke({"topic": "bears"})
Out [13]:
CPU times: user 96.3 ms, sys: 20.4 ms, total: 117 ms Wall time: 1.1 s
{'joke': AIMessage(content="Why don't bears wear socks?\n\nBecause they have bear feet!", additional_kwargs={}, example=False),
'poem': AIMessage(content="In forest's embrace,\nMajestic bears leave their trace.", additional_kwargs={}, example=False)}In [ ]: