|
| 1 | +import asyncio |
| 2 | +import operator |
| 3 | +from os import getenv |
| 4 | +from typing import Annotated, Literal, TypedDict |
| 5 | + |
| 6 | +from langchain.chains.combine_documents.reduce import acollapse_docs, split_list_of_docs |
| 7 | +from langchain_community.document_loaders import WebBaseLoader |
| 8 | +from langchain_core.documents import Document |
| 9 | +from langchain_core.output_parsers import StrOutputParser |
| 10 | +from langchain_core.prompts import ChatPromptTemplate |
| 11 | +from langchain_ollama import ChatOllama |
| 12 | +from langchain_openai import AzureChatOpenAI |
| 13 | +from langchain_text_splitters import CharacterTextSplitter |
| 14 | +from langgraph.constants import Send |
| 15 | +from langgraph.graph import END, START, StateGraph |
| 16 | + |
| 17 | +token_max = 1000 |
| 18 | +url = "https://lilianweng.github.io/posts/2023-06-23-agent/" |
| 19 | + |
| 20 | +llm_ollama = ChatOllama( |
| 21 | + model="phi3", |
| 22 | + temperature=0, |
| 23 | +) |
| 24 | +llm_azure_openai = AzureChatOpenAI( |
| 25 | + temperature=0, |
| 26 | + api_key=getenv("AZURE_OPENAI_API_KEY"), |
| 27 | + api_version=getenv("AZURE_OPENAI_API_VERSION"), |
| 28 | + azure_endpoint=getenv("AZURE_OPENAI_ENDPOINT"), |
| 29 | + model=getenv("AZURE_OPENAI_GPT_MODEL"), |
| 30 | +) |
| 31 | +# Use the Ollama model |
| 32 | +llm = llm_ollama |
| 33 | + |
| 34 | + |
| 35 | +def length_function(documents: list[Document]) -> int: |
| 36 | + """Get number of tokens for input contents.""" |
| 37 | + return sum(llm.get_num_tokens(doc.page_content) for doc in documents) |
| 38 | + |
| 39 | + |
| 40 | +# This will be the overall state of the main graph. |
| 41 | +# It will contain the input document contents, corresponding |
| 42 | +# summaries, and a final summary. |
| 43 | +class OverallState(TypedDict): |
| 44 | + # Notice here we use the operator.add |
| 45 | + # This is because we want combine all the summaries we generate |
| 46 | + # from individual nodes back into one list - this is essentially |
| 47 | + # the "reduce" part |
| 48 | + contents: list[str] |
| 49 | + summaries: Annotated[list, operator.add] |
| 50 | + collapsed_summaries: list[Document] |
| 51 | + final_summary: str |
| 52 | + |
| 53 | + |
| 54 | +# This will be the state of the node that we will "map" all |
| 55 | +# documents to in order to generate summaries |
| 56 | +class SummaryState(TypedDict): |
| 57 | + content: str |
| 58 | + |
| 59 | + |
| 60 | +map_prompt = ChatPromptTemplate.from_messages([("system", "Write a concise summary of the following:\\n\\n{context}")]) |
| 61 | + |
| 62 | +map_chain = map_prompt | llm | StrOutputParser() |
| 63 | + |
| 64 | + |
| 65 | +# Here we generate a summary, given a document |
| 66 | +async def generate_summary(state: SummaryState): |
| 67 | + response = await map_chain.ainvoke(state["content"]) |
| 68 | + return {"summaries": [response]} |
| 69 | + |
| 70 | + |
| 71 | +# Here we define the logic to map out over the documents |
| 72 | +# We will use this an edge in the graph |
| 73 | +def map_summaries(state: OverallState): |
| 74 | + # We will return a list of `Send` objects |
| 75 | + # Each `Send` object consists of the name of a node in the graph |
| 76 | + # as well as the state to send to that node |
| 77 | + return [Send("generate_summary", {"content": content}) for content in state["contents"]] |
| 78 | + |
| 79 | + |
| 80 | +def collect_summaries(state: OverallState): |
| 81 | + return {"collapsed_summaries": [Document(summary) for summary in state["summaries"]]} |
| 82 | + |
| 83 | + |
| 84 | +# Also available via the hub: `hub.pull("rlm/reduce-prompt")` |
| 85 | +reduce_template = """ |
| 86 | +The following is a set of summaries: |
| 87 | +{docs} |
| 88 | +Take these and distill it into a final, consolidated summary |
| 89 | +of the main themes. |
| 90 | +""" |
| 91 | + |
| 92 | +reduce_prompt = ChatPromptTemplate([("human", reduce_template)]) |
| 93 | + |
| 94 | +reduce_chain = reduce_prompt | llm | StrOutputParser() |
| 95 | + |
| 96 | + |
| 97 | +# Add node to collapse summaries |
| 98 | +async def collapse_summaries(state: OverallState): |
| 99 | + doc_lists = split_list_of_docs(state["collapsed_summaries"], length_function, token_max) |
| 100 | + results = [] |
| 101 | + for doc_list in doc_lists: |
| 102 | + results.append(await acollapse_docs(doc_list, reduce_chain.ainvoke)) |
| 103 | + |
| 104 | + return {"collapsed_summaries": results} |
| 105 | + |
| 106 | + |
| 107 | +# This represents a conditional edge in the graph that determines |
| 108 | +# if we should collapse the summaries or not |
| 109 | +def should_collapse( |
| 110 | + state: OverallState, |
| 111 | +) -> Literal["collapse_summaries", "generate_final_summary"]: |
| 112 | + num_tokens = length_function(state["collapsed_summaries"]) |
| 113 | + if num_tokens > token_max: |
| 114 | + return "collapse_summaries" |
| 115 | + else: |
| 116 | + return "generate_final_summary" |
| 117 | + |
| 118 | + |
| 119 | +# Here we will generate the final summary |
| 120 | +async def generate_final_summary(state: OverallState): |
| 121 | + response = await reduce_chain.ainvoke(state["collapsed_summaries"]) |
| 122 | + return {"final_summary": response} |
| 123 | + |
| 124 | + |
| 125 | +async def main(): |
| 126 | + # Construct the graph |
| 127 | + # Nodes: |
| 128 | + graph = StateGraph(OverallState) |
| 129 | + graph.add_node("generate_summary", generate_summary) # same as before |
| 130 | + graph.add_node("collect_summaries", collect_summaries) |
| 131 | + graph.add_node("collapse_summaries", collapse_summaries) |
| 132 | + graph.add_node("generate_final_summary", generate_final_summary) |
| 133 | + |
| 134 | + # Edges: |
| 135 | + graph.add_conditional_edges(START, map_summaries, ["generate_summary"]) |
| 136 | + graph.add_edge("generate_summary", "collect_summaries") |
| 137 | + graph.add_conditional_edges("collect_summaries", should_collapse) |
| 138 | + graph.add_conditional_edges("collapse_summaries", should_collapse) |
| 139 | + graph.add_edge("generate_final_summary", END) |
| 140 | + |
| 141 | + app = graph.compile() |
| 142 | + |
| 143 | + # create graph image |
| 144 | + app.get_graph().draw_mermaid_png(output_file_path="docs/images/15_streamlit_chat_slm.summarize_graph.png") |
| 145 | + |
| 146 | + text_splitter = CharacterTextSplitter.from_tiktoken_encoder(chunk_size=1000, chunk_overlap=0) |
| 147 | + |
| 148 | + loader = WebBaseLoader(web_path=url) |
| 149 | + docs = loader.load() |
| 150 | + |
| 151 | + split_docs = text_splitter.split_documents(docs) |
| 152 | + print(f"Generated {len(split_docs)} documents.") |
| 153 | + |
| 154 | + async for step in app.astream( |
| 155 | + {"contents": [doc.page_content for doc in split_docs]}, |
| 156 | + {"recursion_limit": 10}, |
| 157 | + ): |
| 158 | + print(list(step.keys())) |
| 159 | + print(step) |
| 160 | + |
| 161 | + |
| 162 | +asyncio.run(main()) |
0 commit comments