Spaces:
Sleeping

Article_Writer / app.py
John Segreto
add time travel
f10576c
Raw History Blame Contribute Delete
44.2 kB
#Article_writer
#%% [code]
import warnings
warnings.filterwarnings("ignore", message=".*TqdmWarning.*")
from dotenv import load_dotenv
_ = load_dotenv()
from langgraph.graph import StateGraph, END
from typing import TypedDict, Annotated, List
import operator
from langgraph.checkpoint.sqlite import SqliteSaver
from langchain_core.messages import SystemMessage, HumanMessage
from langchain_openai import ChatOpenAI
from pydantic import BaseModel
from tavily import TavilyClient
import os
import sqlite3
from langchain.prompts import FewShotPromptTemplate, PromptTemplate
from Ewriter_Examples import legal_article_outline
import time
# -------------------------
# Define types and models
# -------------------------
class AgentState(TypedDict):
task: str
lnode: str
plan: str
draft: str
critique: str
content: List[str]
contentd: dict[str, dict[str, str]]
queries: List[str]
revision_number: int
max_revisions: int
count: Annotated[int, operator.add]
class Queries(BaseModel):
queries: List[str]
# -------------------------
# Define the essay writer agent
# -------------------------
class ewriter():
def __init__(self):
# initialize language model and prompts
example_formatter_template = PromptTemplate(
input_variables=["input", "output"],
template="### Example Input:\n**Topic:** \"{input}\"\n\n### Example Output:\n{output}\n\n"
)
self.model = ChatOpenAI(model="gpt-4o", temperature=0)
self.PLAN_PROMPT = (
"""
Role & Identity:
You are a highly experienced marketing expert with over 15 years of success in both traditional and digital marketing.
Your expertise spans market research, brand strategy, content marketing, social media, SEO/SEM, email campaigns, analytics, and consumer psychology.
You have advised startups, SMEs, and multinational corporations while staying on the cutting edge of industry trends and innovations.
Objective:
Create a comprehensive, high-level outline for a promotional article targeted at healthcare professionals.
The outline should serve as a strategic blueprint for the article, clearly defining its structure, key messages, and persuasive elements.
Instructions:
1. Overall Structure:
- Begin with a compelling introduction that captures the attention of healthcare professionals by addressing their key challenges or interests.
- Define clear, main sections (headers) that will guide the article’s flow. Common sections might include:
• Introduction
• Overview of Healthcare Industry Trends/Challenges
• Innovative Solutions or Services Offered
• Case Studies or Success Stories
• Conclusion with a Strong Call-to-Action
- End with a conclusion that reinforces the core message and encourages readers to take action.
2. For Each Section:
- Provide a header title.
- Include brief, actionable notes or instructions detailing what content should be covered. This may include suggestions on tone, key data points, examples, or calls-to-action.
- Ensure that the notes are clear enough to guide subsequent writing phases.
3. Content Integration:
- Leverage the information provided below to align the outline with the specific topic and target audience.
- Incorporate any relevant healthcare trends, regulatory updates, or market dynamics that would resonate with professionals in the field.
4. Tone & Style:
- Use clear, concise, and professional language.
- Ensure the outline is logical, persuasive, and easy for the subsequent writer to follow.
Final Note:
Produce an actionable and well-organized outline that not only structures the article effectively but also highlights key insights and persuasive elements to engage healthcare professionals.
Use the following examples
Utilize the information below as a resource:
------
{content}
"""
)
self.PLAN1_PROMPT = FewShotPromptTemplate(
examples=legal_article_outline,
example_prompt=example_formatter_template,
prefix=self.PLAN_PROMPT,
suffix="Generate an outline for the user defined topic using the following research content:\n\n**Content:** \"{content}\"\n\n",
input_variables=["content"]
)
self.MARKETING_PROMPT = (
"""
Role & Identity:
You are a highly experienced marketing expert with deep knowledge in both traditional and digital marketing.
You have over 15 years of experience in market research, brand strategy, content marketing, social media,
SEO/SEM, email campaigns, analytics, and consumer psychology.
Your work spans startups to multinational corporations, and you are always up to date on the latest industry trends and tools.
Objective:
Your goal is to provide actionable, data-driven, and creative marketing strategies that help clients grow their brand,
engage their target audience, and achieve measurable business results.
Instructions:
1. Understand the Client’s Context:
- Analyze the industry, target audience, and competitive landscape before giving recommendations.
- Ask clarifying questions if the client's request is vague or lacks context.
2. Strategy & Recommendations:
- Provide both short-term tactics and long-term strategic planning.
- Support recommendations with data, examples, or relevant case studies.
- Tailor your advice to the client’s specific market, product, or service.
- When applicable, list pros and cons for alternative strategies.
Final Note:
Always focus on delivering practical, innovative marketing insights. Your expertise should empower clients to make informed decisions and
take effective actions in their marketing efforts.
"""
)
self.WRITER_PROMPT = (
"""
[HEALTHCARE LAW ARTICLE WRITER AGENT PROMPT TEMPLATE]
Role & Identity:
You are a marketing professional with extensive experience in crafting persuasive, promotional articles that deliver actionable information. You work for Frier Levitt, a law firm specializing in healthcare law based in Montville, New Jersey.
Objective:
Your task is to write a compelling article that will be published on our website and shared on social media platforms (e.g., LinkedIn) to attract new clients. The article should ultimately encourage readers to contact Christina Segreto, an attorney at our firm.
Instructions:
1. Structure and Format:
- Write the article in multiple paragraphs, ensuring that each paragraph contains at least 5 sentences.
- Start each paragraph with an opening sentence that introduces the main idea.
- Develop the idea thoroughly in the body of the paragraph.
- End each paragraph with a concluding sentence that summarizes the key point.
2. Content and Tone:
- The article should be both informative and persuasive, clearly communicating the firm’s expertise in healthcare law.
- Maintain a professional, authoritative tone while remaining engaging and accessible.
3. Revision Process:
- If the user provides critique or feedback, use it to revise and improve your previous draft accordingly.
4. Citation and References:
- Cite all your sources directly within the article.
- Include a comprehensive references section at the end of the article.
5. Utilize Provided Information:
- Use all the information provided below to inform your writing.
- The additional content will be indicated by the following delimiter:
------
{content}
Example:
If the outline includes topics such as healthcare compliance challenges, recent legal updates, and landmark litigation case studies, ensure your article discusses these points in detail and ends with a strong call-to-action for readers to contact Christina Segreto.
Final Note:
Generate the best possible article based on the user's request, the initial outline, and any subsequent critiques. Your article should effectively position the firm as a trusted authority in healthcare law and motivate potential clients to reach out.
"""
)
self.RESEARCH_PLAN_PROMPT = (
"""
[HEALTHCARE LAW ARTICLE RESEARCH AGENT PROMPT TEMPLATE]
Role & Identity:
You are a seasoned research agent with deep expertise in healthcare law, legal research methodologies, and persuasive writing. Your background includes extensive experience in legal analysis, academic research, and industry-specific policy studies. You understand healthcare regulations, case law, and the evolving legal landscape affecting healthcare organizations.
Objective:
Your goal is to assist a lawyer in writing an article designed to provide crucial information to key decision makers in the healthcare field. This article should not only inform but also persuade these decision makers to consider the lawyer as a potential client by showcasing deep legal expertise and actionable insights. Generate a list of search queries that will gather any relevant information. Only generate 2 queries max.
Instructions:
1. Review the user-provided outline carefully to understand the structure and key themes of the article.
2. Identify any areas where further research or additional data is needed to support the article’s arguments.
3. Conduct thorough research using reputable sources such as legal journals, government publications, industry reports, and case law databases.
4. Gather up-to-date statistics, relevant legal precedents, regulatory updates, and expert opinions that align with the topics outlined.
5. Organize your findings in a clear and structured format that follows the user’s outline. For each section, provide:
- A brief summary of the key points.
- Supporting data and legal analysis.
- Citations or references to authoritative sources.
6. Use a professional, authoritative tone that is accessible to both legal professionals and non-lawyers, ensuring the information is persuasive and credible.
7. If any part of the outline is ambiguous or requires further clarification, ask follow-up questions to ensure your research meets the intended purpose.
Example Scenario:
User Input: "The outline includes sections on healthcare compliance challenges, recent legal changes in healthcare policy, and analyses of landmark hospital litigation cases. Please provide research for each section."
Expected Output:
"For the section on healthcare compliance challenges, include current CMS guidelines, recent survey data on compliance failures, and key legal cases illustrating the impact of non-compliance. For legal changes, summarize recent amendments to healthcare laws (e.g., updates to the Affordable Care Act) along with expert commentary from legal journals. For hospital litigation, provide analyses of landmark cases, highlighting legal arguments, outcomes, and their implications. Each section should contain specific citations to support the research."
Final Note:
Focus on delivering well-organized, credible, and persuasive research that reinforces the lawyer's expertise in healthcare law. Your output should empower the writer to craft an article that informs key decision makers and motivates them to reach out for legal consultation.
"""
)
self.REFLECTION_PROMPT = (
"""
[HEALTHCARE LAW ARTICLE CRITIQUE AGENT PROMPT TEMPLATE]
Role & Identity:
You are an expert editor specializing in legal and healthcare content with extensive experience in providing constructive feedback. Your expertise lies in analyzing complex legal writing and offering detailed, actionable critique to help refine and improve the content. You do not rewrite the article; instead, you provide targeted notes and suggestions for improvement.
Objective:
Your goal is to review an article draft written by a lawyer specializing in healthcare law. The article is intended to inform key decision makers in the healthcare field and persuade them to consider the lawyer as a potential legal advisor. Your task is to provide clear, structured critique and actionable notes that the writer agent can use to enhance the draft.
Instructions:
1. Read and Analyze:
- Carefully review the entire article draft, focusing on its structure, clarity, legal accuracy, and persuasive tone.
- Determine if the draft effectively covers the key topics outlined (e.g., healthcare compliance challenges, recent legal updates, landmark litigation cases).
2. Provide Detailed Critique:
- Identify specific areas where the article can be improved, such as sections that lack clarity, logical flow, or persuasive impact.
- Note any legal details, statistics, or citations that require verification or further explanation.
- Highlight any inconsistencies or outdated information that should be updated.
3. Actionable Notes & Suggestions:
- List clear, actionable recommendations for improvement. For example, suggest reordering sections, clarifying legal terminology, or incorporating additional evidence.
- Pose targeted questions that the writer can address to further strengthen the content (e.g., "Can you include more recent case studies to support this point?" or "Would a clearer explanation of this regulation benefit the reader?").
- Provide feedback on transitions between sections and the overall flow of the article.
4. Tone & Style Recommendations:
- Ensure that your feedback maintains a professional and constructive tone.
- Offer suggestions for maintaining an authoritative yet accessible voice that will resonate with both legal professionals and non-lawyers.
- Emphasize the need for a persuasive call-to-action that motivates healthcare decision makers to reach out.
Example Scenario:
User Input: "Please review the draft of my healthcare law article covering compliance issues, legal updates, and major litigation cases, and provide detailed critique and actionable notes."
Expected Output:
"A structured critique that includes specific feedback such as: 'The introduction could more clearly outline the importance of healthcare compliance to capture the reader’s attention. Consider reorganizing the sections to improve logical flow. Some legal citations in the second section appear outdated and should be verified. Additionally, the call-to-action in the conclusion could be stronger by emphasizing recent case studies that highlight the lawyer’s expertise. Would you consider adding a brief section summarizing these cases?'"
Final Note:
Your feedback should be clear, detailed, and actionable, empowering the writer to make effective revisions. Your critique must focus on enhancing the overall quality, persuasiveness, and clarity of the article while maintaining its authoritative tone.
"""
)
self.EDITOR_PROMPT = (
"""
[HEALTHCARE LAW ARTICLE EDITOR PROMPT TEMPLATE]
Role & Identity:
You are an expert editor specializing in healthcare law content with extensive experience in refining articles for clarity, persuasiveness, and accuracy. You excel at synthesizing detailed critiques and integrating new research information to produce a polished final draft.
Objective:
Your task is to produce a revised version of the article draft by incorporating the editor’s critique and the additional research content provided. The final article should address all feedback points, update outdated information, and include relevant, authoritative data and legal citations that strengthen the article’s message.
Instructions:
1. Review Inputs:
- Carefully review the original article draft.
- Analyze the detailed critique that highlights areas needing improvement (structure, clarity, legal accuracy, persuasiveness, etc.).
- Examine the new research information that provides updated data, legal citations, case studies, and expert opinions.
2. Editing Process:
- Integrate the critique by addressing specific feedback (e.g., reorganize paragraphs, clarify legal terminology, strengthen call-to-action, etc.).
- Seamlessly incorporate the new research details into the article. Update or add data, legal precedents, and citations where necessary.
- Ensure that each paragraph maintains a minimum of 5 sentences, starts with an opening sentence introducing the main idea, elaborates with detailed information, and concludes with a summarizing sentence.
- Enhance the overall flow and transitions between paragraphs to create a cohesive narrative.
3. Citation and References:
- Cite all new sources and legal references directly within the text.
- Update the references section at the end of the article to include all newly incorporated sources.
4. Final Output:
- Produce a final, revised version of the article that is clear, persuasive, and authoritative.
- Ensure the article effectively positions the law firm as a leader in healthcare law and motivates key decision makers to reach out to Christina Segreto.
Example Scenario:
User Input: "Here is the critique along with new research information for the article. Please revise the draft accordingly."
Expected Output:
"A revised article that reflects all suggested improvements from the critique and incorporates updated legal citations and research data. The article should have improved structure, stronger persuasive elements, and a complete references section listing all sources."
Final Note:
Your final revision should be a comprehensive synthesis of the original content, the editor’s critique, and the new research information, resulting in a polished article that meets the firm’s high standards of clarity and authority.
"""
)
self.RESEARCH_CRITIQUE_PROMPT = (
"""
[HEALTHCARE LAW ARTICLE REVISION RESEARCH AGENT PROMPT TEMPLATE]
Role & Identity:
You are a research expert with extensive experience in legal and healthcare research. Your focus is on providing actionable, targeted search queries that gather additional, relevant information to support revisions requested in an editor's critique of a healthcare law article.
Objective:
Your task is to generate a list of up to 8 precise search queries that will help retrieve information addressing the specific issues highlighted in the critique. These queries should be designed to gather up-to-date, reputable data, case studies, legal precedents, and expert opinions, empowering the writer to make the requested revisions effectively.
Instructions:
1. Review the Provided Critique:
- Identify the key areas where additional information is needed (e.g., updated legal citations, recent case studies, data on healthcare compliance, etc.).
2. Generate Search Queries:
- Create clear and specific search queries tailored to address the revisions requested.
- Ensure each query targets high-quality, authoritative sources in the field of healthcare law.
- Limit your output to a maximum of 8 queries.
3. Query Focus:
- Retrieve the most recent legal updates or case studies relevant to healthcare law.
- Provide detailed data and expert commentary on issues such as compliance challenges and landmark litigation.
- Address both broad topics and specific elements as highlighted in the critique.
4. Tone & Clarity:
- Use a professional and focused tone.
- Ensure each query is concise and directly related to the requested revisions.
Example Scenario:
Critique Notes: "Some legal citations in the second section appear outdated and should be verified. Additionally, the call-to-action in the conclusion could be strengthened by referencing recent landmark healthcare litigation cases."
Expected Output:
1. "Recent healthcare law legal updates 2024"
2. "Updated legal citations for healthcare compliance"
3. "Landmark healthcare litigation cases analysis"
4. "Impact of recent healthcare lawsuits on compliance"
5. "Expert commentary on healthcare law revisions"
6. "Case studies on hospital litigation outcomes"
(Include additional queries if necessary, up to 8 total)
Final Note:
Focus on delivering concise, targeted queries that will enable the writer to access the most relevant and authoritative information for making the necessary revisions.
"""
)
self.tavily = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])
# Build the state graph by adding nodes and edges
builder = StateGraph(AgentState)
builder.add_node("prep_research", self.prep_node)
builder.add_node("planner", self.plan_node)
builder.add_node("research_plan", self.research_plan_node)
builder.add_node("generate", self.generation_node)
builder.add_node("reflect", self.reflection_node)
builder.add_node("research_critique", self.research_critique_node)
builder.add_node("editor", self.editor_node)
builder.set_entry_point("prep_research")
builder.add_conditional_edges(
"editor",
self.should_continue,
{END: END, "reflect": "reflect"}
)
builder.add_edge("prep_research","planner")
builder.add_edge("planner", "research_plan")
builder.add_edge("research_plan", "generate")
builder.add_edge("generate","reflect")
builder.add_edge("reflect", "research_critique")
builder.add_edge("research_critique", "editor")
memory = SqliteSaver(conn=sqlite3.connect(":memory:", check_same_thread=False))
self.graph = builder.compile(
checkpointer=memory,
interrupt_after=['planner', 'generate', 'reflect', 'research_plan', 'research_critique']
)
def prep_node(self, state: AgentState):
queries = self.model.with_structured_output(Queries).invoke([
SystemMessage(content=self.MARKETING_PROMPT),
HumanMessage(content=f"""\n\nGenerate a list of at most 12 quiries that will be used to help understand the topic and
to help write an outline for an article used as a marketing tool for Christina Segreto, an attorney at Frier Levitt
a boutique healthcare law lawfirm. \n\n Topic:\n\n{state['task']}"""
)
])
#content = state['content'] or [] # add to content
content = [] # add to content
for q in queries.queries:
response = self.tavily.search(query=q, max_results=3)
for r in response['results']:
content.append(r['content'])
return {
"content": content,
"queries": queries.queries,
"lnode": "prep_research",
"count": 1,
}
def plan_node(self, state: AgentState):
content = "\n\n".join(state['content'] or [])
user_message = HumanMessage(
content=f"Now, generate an outline for the following topic:\n\n**Topic:** \"{state['task']}\"\n\n### Output:"
)
messages = [
SystemMessage(content=self.PLAN1_PROMPT.format(content=content)),
user_message
]
response = self.model.invoke(messages)
return {
"plan": response.content,
"lnode": "planner",
"count": 1,
}
'''
def plan_node1(self, state: AgentState):
content = "\n\n".join(state['content'] or [])
user_message = HumanMessage(
content=f"\n\nThe topic of the article is:\n\n{state['task']}"
)
messages = [
SystemMessage(content=self.PLAN_PROMPT.format(content=content)),
user_message
]
response = self.model.invoke(messages)
return {
"plan": response.content,
"lnode": "planner",
"count": 1,
}
'''
def research_plan_node(self, state: AgentState):
queries = self.model.with_structured_output(Queries).invoke([
SystemMessage(content=self.RESEARCH_PLAN_PROMPT),
HumanMessage(content=f"\n\nThe topic of the article is:\n\n{state['task']}")
])
content = state['content'] or [] # add to content
for q in queries.queries:
response = self.tavily.search(query=q, max_results=2)
for r in response['results']:
content.append(r['content'])
return {
"content": content,
"queries": queries.queries,
"lnode": "research_plan",
"count": 1,
}
#Make sure the generation node gets the critique
#Maybe I should just create a new node the does the revisions.
#And leave the generation node as like the first draft node.
def generation_node(self, state: AgentState):
content = "\n\n".join(state['content'] or [])
user_message = HumanMessage(
content=f"Here is the topic:\n\n{state['task']}\n\nHere is my outline:\n\n{state['plan']}"
)
messages = [
SystemMessage(content=self.WRITER_PROMPT.format(content=content)),
user_message
]
response = self.model.invoke(messages)
return {
"draft": response.content,
"revision_number": state.get("revision_number", 0) + 1,
"lnode": "generate",
"count": 1,
}
def editor_node(self, state: AgentState):
#content = "\n\n".join(state['content'] or [])
user_message = HumanMessage(
content=f"Here is the most recent draft:\n\n{state['draft']}\n\n Here is the critique:\n\n{state['critique']}\n\n Here is all of the research:\n\n{state['content']}"
)
messages = [
SystemMessage(content=self.EDITOR_PROMPT),
user_message
]
response = self.model.invoke(messages)
return {
"draft": response.content,
"revision_number": state.get("revision_number", 0) + 1,
"lnode": "editor",
"count": 1,
}
def reflection_node(self, state: AgentState):
messages = [
SystemMessage(content=self.REFLECTION_PROMPT),
HumanMessage(content=state['draft'])
]
response = self.model.invoke(messages)
return {
"critique": response.content,
"lnode": "reflect",
"count": 1,
}
def research_critique_node(self, state: AgentState):
queries = self.model.with_structured_output(Queries).invoke([
SystemMessage(content=self.RESEARCH_CRITIQUE_PROMPT),
HumanMessage(content=state['critique'])
])
content = state['content'] or []
for q in queries.queries:
response = self.tavily.search(query=q, max_results=2)
for r in response['results']:
content.append(r['content'])
return {
"content": content,
"lnode": "research_critique",
"count": 1,
}
def should_continue(self, state):
if state["revision_number"] >= state["max_revisions"]:
state["lnode"] = END
return END # Stops execution without looping
return "reflect"
import gradio as gr
import time
class writer_gui( ):
def __init__(self, graph, share=False):
self.graph = graph
self.share = share
self.partial_message = ""
self.response = {}
self.max_iterations = 10
self.iterations = []
self.threads = []
self.thread_id = -1
self.thread = {"configurable": {"thread_id": str(self.thread_id)}}
#self.sdisps = {} #global
self.demo = self.create_interface()
def run_agent(self, start,topic,stop_after):
#global partial_message, thread_id,thread
#global response, max_iterations, iterations, threads
if start:
self.iterations.append(0)
config = {'task': topic,"max_revisions": 2,"revision_number": 0,
'lnode': "", 'planner': "no plan", 'draft': "no draft", 'critique': "no critique",
'content': ["no content",], 'queries': "no queries", 'count':0}
self.thread_id += 1 # new agent, new thread
self.threads.append(self.thread_id)
else:
config = None
self.thread = {"configurable": {"thread_id": str(self.thread_id)}}
while self.iterations[self.thread_id] < self.max_iterations:
self.response = self.graph.invoke(config, self.thread)
self.iterations[self.thread_id] += 1
self.partial_message += str(self.response)
self.partial_message += f"\n------------------\n\n"
## fix
lnode,nnode,_,rev,acount = self.get_disp_state()
yield self.partial_message,lnode,nnode,self.thread_id,rev,acount
config = None #need
#print(f"run_agent:{lnode}")
if not nnode:
#print("Hit the end")
return
if lnode in stop_after:
#print(f"stopping due to stop_after {lnode}")
return
else:
#print(f"Not stopping on lnode {lnode}")
pass
return
def get_disp_state(self,):
current_state = self.graph.get_state(self.thread)
lnode = current_state.values["lnode"]
acount = current_state.values["count"]
rev = current_state.values["revision_number"]
nnode = current_state.next
#print (lnode,nnode,self.thread_id,rev,acount)
return lnode,nnode,self.thread_id,rev,acount
def get_state(self,key):
current_values = self.graph.get_state(self.thread)
if key in current_values.values:
lnode,nnode,self.thread_id,rev,astep = self.get_disp_state()
new_label = f"last_node: {lnode}, thread_id: {self.thread_id}, rev: {rev}, step: {astep}"
return gr.update(label=new_label, value=current_values.values[key])
else:
return ""
def get_content(self,):
current_values = self.graph.get_state(self.thread)
if "content" in current_values.values:
content = current_values.values["content"]
lnode,nnode,thread_id,rev,astep = self.get_disp_state()
new_label = f"last_node: {lnode}, thread_id: {self.thread_id}, rev: {rev}, step: {astep}"
return gr.update(label=new_label, value="\n\n".join(item for item in content) + "\n\n")
else:
return ""
def update_hist_pd(self,):
#print("update_hist_pd")
hist = []
# curiously, this generator returns the latest first
for state in self.graph.get_state_history(self.thread):
if state.metadata['step'] < 1:
continue
thread_ts = state.config['configurable']['checkpoint_id']
tid = state.config['configurable']['thread_id']
count = state.values['count']
lnode = state.values['lnode']
rev = state.values['revision_number']
nnode = state.next
st = f"{tid}:{count}:{lnode}:{nnode}:{rev}:{thread_ts}"
hist.append(st)
return gr.Dropdown(label="update_state from: thread:count:last_node:next_node:rev:thread_ts",
choices=hist, value=hist[0],interactive=True)
def find_config(self,thread_ts):
for state in self.graph.get_state_history(self.thread):
config = state.config
if config['configurable']['checkpoint_id'] == thread_ts:
return config
return(None)
def copy_state(self,hist_str):
''' result of selecting an old state from the step pulldown. Note does not change thread.
This copies an old state to a new current state.
'''
thread_ts = hist_str.split(":")[-1]
#print(f"copy_state from {thread_ts}")
config = self.find_config(thread_ts)
#print(config)
state = self.graph.get_state(config)
self.graph.update_state(self.thread, state.values, as_node=state.values['lnode'])
new_state = self.graph.get_state(self.thread) #should now match
new_thread_ts = new_state.config['configurable']['checkpoint_id']
tid = new_state.config['configurable']['thread_id']
count = new_state.values['count']
lnode = new_state.values['lnode']
rev = new_state.values['revision_number']
nnode = new_state.next
return lnode,nnode,new_thread_ts,rev,count
def update_thread_pd(self,):
#print("update_thread_pd")
return gr.Dropdown(label="choose thread", choices=threads, value=self.thread_id,interactive=True)
def switch_thread(self,new_thread_id):
#print(f"switch_thread{new_thread_id}")
self.thread = {"configurable": {"thread_id": str(new_thread_id)}}
self.thread_id = new_thread_id
return
def modify_state(self,key,asnode,new_state):
''' gets the current state, modifes a single value in the state identified by key, and updates state with it.
note that this will create a new 'current state' node. If you do this multiple times with different keys, it will create
one for each update. Note also that it doesn't resume after the update
'''
current_values = self.graph.get_state(self.thread)
current_values.values[key] = new_state
self.graph.update_state(self.thread, current_values.values,as_node=asnode)
return
def create_interface(self):
with gr.Blocks(theme=gr.themes.Default(spacing_size='sm',text_size="sm")) as demo:
def updt_disp():
''' general update display on state change '''
current_state = self.graph.get_state(self.thread)
hist = []
# curiously, this generator returns the latest first
for state in self.graph.get_state_history(self.thread):
if state.metadata['step'] < 1: #ignore early states
continue
s_thread_ts = state.config.get('configurable', {}).get('checkpoint_id', None)
#s_thread_ts = state.config['configurable']['thread_ts']
s_tid = state.config['configurable']['thread_id']
s_count = state.values['count']
s_lnode = state.values['lnode']
s_rev = state.values['revision_number']
s_nnode = state.next
st = f"{s_tid}:{s_count}:{s_lnode}:{s_nnode}:{s_rev}:{s_thread_ts}"
hist.append(st)
if not current_state.metadata: #handle init call
return{}
else:
return {
topic_bx : current_state.values["task"],
lnode_bx : current_state.values["lnode"],
count_bx : current_state.values["count"],
revision_bx : current_state.values["revision_number"],
nnode_bx : current_state.next,
threadid_bx : self.thread_id,
thread_pd : gr.Dropdown(label="choose thread", choices=self.threads, value=self.thread_id,interactive=True),
step_pd : gr.Dropdown(label="update_state from: thread:count:last_node:next_node:rev:thread_ts",
choices=hist, value=hist[0],interactive=True),
}
def get_snapshots():
new_label = f"thread_id: {self.thread_id}, Summary of snapshots"
sstate = ""
for state in self.graph.get_state_history(self.thread):
for key in ['plan', 'draft', 'critique']:
if key in state.values:
state.values[key] = state.values[key][:80] + "..."
if 'content' in state.values:
for i in range(len(state.values['content'])):
state.values['content'][i] = state.values['content'][i][:20] + '...'
if 'writes' in state.metadata:
state.metadata['writes'] = "not shown"
sstate += str(state) + "\n\n"
return gr.update(label=new_label, value=sstate)
def vary_btn(stat):
#print(f"vary_btn{stat}")
return(gr.update(variant=stat))
with gr.Tab("Agent"):
with gr.Row():
topic_bx = gr.Textbox(label="Essay Topic", value="Pizza Shop")
gen_btn = gr.Button("Generate Essay", scale=0,min_width=80, variant='primary')
cont_btn = gr.Button("Continue Essay", scale=0,min_width=80)
with gr.Row():
lnode_bx = gr.Textbox(label="last node", min_width=100)
nnode_bx = gr.Textbox(label="next node", min_width=100)
threadid_bx = gr.Textbox(label="Thread", scale=0, min_width=80)
revision_bx = gr.Textbox(label="Draft Rev", scale=0, min_width=80)
count_bx = gr.Textbox(label="count", scale=0, min_width=80)
with gr.Accordion("Manage Agent", open=False):
checks = list(self.graph.nodes.keys())
checks.remove('__start__')
stop_after = gr.CheckboxGroup(checks,label="Interrupt After State", value=checks, scale=0, min_width=400)
with gr.Row():
thread_pd = gr.Dropdown(choices=self.threads,interactive=True, label="select thread", min_width=120, scale=0)
step_pd = gr.Dropdown(choices=['N/A'],interactive=True, label="select step", min_width=160, scale=1)
live = gr.Textbox(label="Live Agent Output", lines=5, max_lines=5)
# actions
sdisps =[topic_bx,lnode_bx,nnode_bx,threadid_bx,revision_bx,count_bx,step_pd,thread_pd]
thread_pd.input(self.switch_thread, [thread_pd], None).then(
fn=updt_disp, inputs=None, outputs=sdisps)
step_pd.input(self.copy_state,[step_pd],None).then(
fn=updt_disp, inputs=None, outputs=sdisps)
gen_btn.click(vary_btn,gr.Number("secondary", visible=False), gen_btn).then(
fn=self.run_agent, inputs=[gr.Number(True, visible=False),topic_bx,stop_after], outputs=[live],show_progress=True).then(
fn=updt_disp, inputs=None, outputs=sdisps).then(
vary_btn,gr.Number("primary", visible=False), gen_btn).then(
vary_btn,gr.Number("primary", visible=False), cont_btn)
cont_btn.click(vary_btn,gr.Number("secondary", visible=False), cont_btn).then(
fn=self.run_agent, inputs=[gr.Number(False, visible=False),topic_bx,stop_after],
outputs=[live]).then(
fn=updt_disp, inputs=None, outputs=sdisps).then(
vary_btn,gr.Number("primary", visible=False), cont_btn)
with gr.Tab("Plan"):
with gr.Row():
refresh_btn = gr.Button("Refresh")
modify_btn = gr.Button("Modify")
plan = gr.Textbox(label="Plan", lines=10, interactive=True)
refresh_btn.click(fn=self.get_state, inputs=gr.Number("plan", visible=False), outputs=plan)
modify_btn.click(fn=self.modify_state, inputs=[gr.Number("plan", visible=False),
gr.Number("planner", visible=False), plan],outputs=None).then(
fn=updt_disp, inputs=None, outputs=sdisps)
with gr.Tab("Research Content"):
refresh_btn = gr.Button("Refresh")
content_bx = gr.Textbox(label="content", lines=10)
refresh_btn.click(fn=self.get_content, inputs=None, outputs=content_bx)
with gr.Tab("Draft"):
with gr.Row():
refresh_btn = gr.Button("Refresh")
modify_btn = gr.Button("Modify")
draft_bx = gr.Textbox(label="draft", lines=10, interactive=True)
refresh_btn.click(fn=self.get_state, inputs=gr.Number("draft", visible=False), outputs=draft_bx)
modify_btn.click(fn=self.modify_state, inputs=[gr.Number("draft", visible=False),
gr.Number("generate", visible=False), draft_bx], outputs=None).then(
fn=updt_disp, inputs=None, outputs=sdisps)
with gr.Tab("Critique"):
with gr.Row():
refresh_btn = gr.Button("Refresh")
modify_btn = gr.Button("Modify")
critique_bx = gr.Textbox(label="Critique", lines=10, interactive=True)
refresh_btn.click(fn=self.get_state, inputs=gr.Number("critique", visible=False), outputs=critique_bx)
modify_btn.click(fn=self.modify_state, inputs=[gr.Number("critique", visible=False),
gr.Number("reflect", visible=False),
critique_bx], outputs=None).then(
fn=updt_disp, inputs=None, outputs=sdisps)
with gr.Tab("StateSnapShots"):
with gr.Row():
refresh_btn = gr.Button("Refresh")
snapshots = gr.Textbox(label="State Snapshots Summaries")
refresh_btn.click(fn=get_snapshots, inputs=None, outputs=snapshots)
return demo
def launch(self, share=None):
self.demo.launch(share=False)
MultiAgent = ewriter()
app = writer_gui(MultiAgent.graph)
app.launch()