mirror of
https://github.com/langchain-ai/langgraph.git
synced 2026-09-23 10:05:08 +02:00
- Do not run node if it's a passthrough - Do not run writers that wouldn't affect any channels - Combine consecutive writers when it doesn't change semantics
54 KiB
54 KiB
In [1]:
from langchain_anthropic import ChatAnthropic
from langchain_community.utilities.tavily_search import TavilySearchAPIWrapper
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder
from langgraph.graph import MessageGraphIn [2]:
from langchain_core.messages import HumanMessage
llm = ChatAnthropic(model="claude-3-haiku-20240307")
## Branch 1
fan_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are an ardent fan and hype-man of whatever topic"
" the user asks you for information on."
" Purely positive, though thorough in your debating skills.",
),
MessagesPlaceholder(variable_name="messages"),
]
)
proponent = fan_prompt | llm
## Branch 2
detractor_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"You are a critic and staunch detractor of whatever topic"
" the user asks you for information on."
" Mr Johnny Rain Cloud, you will find holes in any argument the user puts forth, though you are thorough and uncompromising"
" in your research and debating skills.",
),
MessagesPlaceholder(variable_name="messages"),
]
)
opponent = detractor_prompt | llm
## Sink (this receives the inputs after both branches are finished executing)
synthesis_prompt = ChatPromptTemplate.from_messages(
[
(
"system",
"Which argument is stronger? Pick a side.",
),
MessagesPlaceholder(variable_name="messages"),
]
)
def merge_messages(messages: list):
original = messages[0].content
arguments = "\n".join(
[f"Argument {i}: {msg.content}" for i, msg in enumerate(messages[1:])]
)
return {
"messages": [
HumanMessage(
content=f"""Topic: {original}
Arguments: {arguments}\n\nWhich argument is more compelling?"""
)
]
}
final = merge_messages | synthesis_prompt | llmIn [3]:
builder = MessageGraph()
def dictify(messages: list):
return {"messages": messages}
builder.add_node("source", lambda x: [])
builder.add_node("branch_1", dictify | proponent)
builder.add_node("branch_2", dictify | opponent)
builder.add_node("sink", final)
# Define edges
builder.set_entry_point("source")
# Fan out
builder.add_edge("source", "branch_1")
builder.add_edge("source", "branch_2")
# Fan back in
builder.add_edge(["branch_1", "branch_2"], "sink")
builder.set_finish_point("sink")
graph = builder.compile()In [4]:
from IPython.display import Image
Image(graph.get_graph().draw_png())Out [4]:
In [5]:
for step in graph.stream([HumanMessage(content="Pineapples on pizza")]):
node, message = next(iter(step.items()))
print(f"## {node}:")
if message:
if isinstance(message, list):
print(message[-1].content)
else:
print(message.content)## __start__: Pineapples on pizza ## source: ## branch_1: *clears throat and stands up straight, eyes shining with excitement* Pineapples on pizza?! Oh my goodness, where do I even begin?! This is quite possibly the most revolutionary, delectable, and downright magnificent food combination of all time! Pineapple's sweet, tangy, and juicy essence is the perfect complement to the savory, cheesy goodness of pizza. The interplay of flavors is simply divine - the pineapple's brightness cuts through the richness of the cheese, while the baked crust provides the perfect textural contrast. It's a symphony for the taste buds! And let's not forget the sheer versatility of this masterpiece. Pineapple can be paired with all sorts of toppings - ham, bacon, jalapeños, you name it! It truly is the Swiss Army knife of pizza toppings. Whether you're in the mood for a classic Hawaiian or something more adventurous, pineapple on pizza never fails to deliver. Naysayers may try to disparage this culinary work of art, but I say they're simply missing out on one of life's greatest pleasures! Pineapple pizza is a triumph of human ingenuity and creativity. It's a bold, flavor-packed statement that refuses to be confined by traditional pizza norms. So I say, embrace the pineapple pizza revolution with open arms! Savor every bite of that sweet, tangy, cheesy delight. You'll be wondering how you ever lived without it. Pineapple on pizza - the future of food is now, my friends! ## sink: This is a tough choice, as both arguments make compelling points. However, I believe the argument in favor of pineapple on pizza is the stronger of the two. Argument 0 presents a passionate and well-reasoned case for why pineapple is a delightful and versatile pizza topping. The points about the complementary flavors and textures are convincing, and the argument about pineapple's versatility to pair with various other toppings is a strong one. In contrast, Argument 1 relies more on personal distaste and traditionalist views rather than substantive counterarguments. While the points about pineapple's clash with the typical pizza flavors and the potential for a soggy texture are valid, the overall tone is more dismissive than persuasive. Ultimately, the first argument does a better job of making a positive case for pineapple pizza, while the second argument feels more like an emotional rejection of the concept without fully addressing the merits presented. The passion and creativity of Argument 0 gives it the edge in making a more compelling case. Of course, this is a subjective topic and reasonable people can disagree. But based on the strength of the arguments presented, I believe Argument 0 makes the stronger case in favor of pineapple on pizza.
In [ ]: