Skip to content

Instantly share code, notes, and snippets.

@Nunocky
Created March 29, 2026 02:48
Show Gist options
  • Select an option

  • Save Nunocky/01ccbd80c79f42dafe5ed20491f844e6 to your computer and use it in GitHub Desktop.

Select an option

Save Nunocky/01ccbd80c79f42dafe5ed20491f844e6 to your computer and use it in GitHub Desktop.
langchain の agent workflowの例
# 翻訳+要約くんエージェント
import logging
from typing import TypedDict
from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from langgraph.graph import END, START, StateGraph
from langgraph.pregel import Pregel
# Set up logging for the example
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# logger.setLevel(logging.INFO)
# handler = logging.StreamHandler()
# formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
# handler.setFormatter(formatter)
# logger.addHandler(handler)
class AgentState(TypedDict):
user_input: str # 入力された文章
translated: str # 翻訳された文章
summary: str # 要約された文章
class TranslateSummarizeAgent:
def __init__(self):
self.client = ChatOpenAI()
def create_graph(self) -> Pregel:
"""workflowを定義"""
logger.info("ワークフローを定義しています...")
workflow = StateGraph(AgentState)
workflow.add_node("translate", self.translate)
workflow.add_node("summarize", self.summarize)
workflow.add_edge("translate", "summarize")
workflow.add_edge(START, "translate")
workflow.add_edge("summarize", END)
logger.info("ワークフローの定義が完了しました。")
return workflow.compile()
def translate(self, state: AgentState) -> dict:
"""翻訳処理"""
response = self.client.invoke(
[
SystemMessage("あなたは翻訳者です。入力された文章を翻訳してください。"),
HumanMessage(content=state["user_input"]),
]
)
logger.info(f"翻訳結果: {response.content}")
return {"translated": str(response.content)}
def summarize(self, state: AgentState) -> dict:
"""要約処理"""
response = self.client.invoke(
[
SystemMessage("あなたは要約者です。入力された文章を要約してください。"),
HumanMessage(content=state["translated"]),
]
)
logger.info(f"要約結果: {response.content}")
return {"summary": str(response.content)}
if __name__ == "__main__":
user_input = """Large protests against the Trump administration are taking place in cities across the US, marking the third iteration of No Kings rallies that have previously drawn crowds into the millions.
Organisers say they are protesting against policies imposed by US President Donald Trump, including the war in Iran, federal immigration enforcement and the rising cost of living.
"Trump wants to rule over us as a tyrant. But this is America, and power belongs to the people - not to wannabe kings or their billionaire cronies," organisers said.
A White House spokesperson called the protests "Trump Derangement Therapy Sessions" and said the only people who care "are the reporters who are paid to cover them".
Throughout the day on Saturday, demonstrations took place in nearly every major US city, including New York, Washington DC, and Los Angeles.
Rallies took over the streets of downtown Washington DC throughout the afternoon, with throngs of people marching through the nation's capital. Protestors lined the steps of the the Lincoln Memorial and packed the National Mall.
Like in previous iterations of No Kings, protestors held up effigies of Trump, Vice President JD Vance and other officials in the administration, calling for their ousting and arrest.
One of the flagship No Kings protests on Saturday took place in Minnesota, where two American citizens - Renee Nicole Good and Alex Pretti - were killed by federal immigration agents in January. Their deaths sparked outrage and nationwide protests against the Trump administration's immigration tactics.
Thousands on Saturday filled the streets with signs and a plethora of high-profile Democrats also took a stage outside the State Capitol building in St Paul.
Bruce Springsteen also took the stage and performed his anti-immigration enforcement song titled, "Streets of Minneapolis".
Thousands also crowded New York City's Times Square, marching through Manhattan's Midtown neighbourhood. Police had to shut down the normally busy streets to make way for crowds. In October, the New York Police Department said more than 100,000 people had gathered across all five of the city's boroughs.
The last No Kings rally in October drew crowds of nearly seven million people nationally.
Several US states mobilised the National Guard, but organisers have maintained that the events are peaceful.
Since returning to the White House in January 2025, Trump has expanded the scope of presidential power, using executive orders to dismantle parts of the federal government and deploying National Guard troops to US cities despite objections by state governors.
The president has also called on the administration's top law enforcement officials to prosecute his perceived political enemies.
The president says his actions are necessary to rebuild a country in crisis and has dismissed accusations that he is a behaving like a dictator as hysterical. "They're referring to me as a king. I'm not a king," he said in an interview with Fox News in October.
But critics warn some of the moves by his administration are unconstitutional and a threat to American democracy.
Crowds have gathered both in big cities and small towns. No Kings rallies are kicking off in Boston, Massachusetts, Nashville, Tennessee, and Houston, Texas. More big city protests are expected to kick off throughout the day.
The streets are also lined with people in cities like Shelbyville, Kentucky and Howell, Michigan, which has a population of just about 10,000.
People are holding signs protesting against the war in Iran and Immigration and Customs Enforcement (ICE) in neighbourhoods.
American expats abroad are also gathering to protest. Crowds have formed in Paris, London and Lisbon, where many hold signs calling the president a "fascist" and a "war criminal", as well as calling for his impeachment and removal from office.
"""
agent = TranslateSummarizeAgent()
app = agent.create_graph()
result = app.invoke({"user_input": user_input})
print("入力された文章:", user_input)
print("翻訳結果:", result["translated"])
print("要約結果:", result["summary"])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment