from langgraph.graph import START, END, StateGraph, MessagesState
from dotenv import load_dotenv
load_dotenv()
from model import State
from chains import (
base_prompt_chain,
user_prompt_chain,
prompt_selector_chain,
post_generetor_chain_without_messages,
post_generator_chain_with_messages,
post_eval_chain,
post_perf_eval_chain
)
def post_generator(state: State) -> State:
"""Agent that generates social media posts based on business details and user configuration."""
messages = state["messages"]
code
if not messages:
generated_post = post_generetor_chain_without_messages.invoke({
"prompt": state['selected_prompt']
})
else:
generated_post = post_generator_chain_with_messages.invoke({
"feedback": state['messages'][-1]
})
return {"post_content": generated_post}
def post_evaluator(state: State) -> State:
"""Agent that evaluates generated social media post"""
def should_continue(state: State) -> State:
"""Determine whether to continue the debate or end it."""
if state["current_round"] >= 3:
next_step_value = "END"
else:
next_step_value = "CONTINUE"
code
return {"next_step": next_step_value}
def go_to_top(state: State) -> State:
"""Determine whether to accept or reject prompt based on post performance"""
if state['prompt_accepted'] == "NOT_ACCEPTED" or state["post_rating"] <= 5:
where_to_go_value = "CONTINUE"
else:
where_to_go_value = "END"
tell me in this code
how can improve functionality and performance without adding any extra nodes
just add some logic or any extra fields etc.
Assistant
Improving Functionality and Performance Without Adding Nodes
Here are several improvements you can make to your existing code without adding new nodes:
1. Add Input Validation and Error Handling
python
def validate_input(state: State) -> bool:
"""Validate input parameters before processing"""
required_fields = ['business_domain', 'business_name', 'platform', 'user_config']
for field in required_fields:
if field not in state or not state[field]:
raise ValueError(f"Missing required field: {field}")
if 'current_round' not in state:
state['current_round'] = 0
return True
2. Enhance State Tracking
Add more fields to track the process:
python
# In your State definition (assuming it's a TypedDict or similar)
class State(TypedDict):
# ... existing fields ...
iteration_history: List[dict] # Track each iteration's results
performance_metrics: dict # Store performance data
improvement_suggestions: List[str] # Store suggestions for improvement
def post_generator(state: State) -> State:
"""Enhanced post generator with more context"""
messages = state.get("messages", [])
# Add more context to the generation
context = {
"business_domain": state['business_domain'],
"business_name": state['business_name'],
"platform": state['platform'],
"user_config": state['user_config'],
"previous_attempts": len(messages) # Track how many attempts have been made
}
if not messages:
generated_post = post_generetor_chain_without_messages.invoke({
"prompt": state['selected_prompt'],
"context": context
})
else:
# Include more feedback context
feedback_history = "\n".join(
f"Round {i+1}: {msg}" for i, msg in enumerate(messages)
)
generated_post = post_generator_chain_with_messages.invoke({
"feedback": state['messages'][-1],
"feedback_history": feedback_history,
"context": context
})
return {"post_content": generated_post}
def should_continue(state: State) -> State:
"""Enhanced router with more termination conditions"""
if state["current_round"] >= 3:
next_step_value = "END"
elif state.get("post_rating", 0) >= 8: # Early exit if post is excellent
next_step_value = "END"
elif state.get("engagement_rate", 0) > 10: # Early exit if engagement is high
next_step_value = "END"
else:
next_step_value = "CONTINUE"
return {"next_step": next_step_value}
7. Add Performance Tracking
python
# Add this to your State initialization
initial_state = {
"business_domain": "Restraurant",
"business_name": "Dosa Charcoal",
"platform": "Instagram",
"user_config": {
"tone": "casual and energetic",
"target_audience": "young professionals",
"content_preferences": ["Authentic south indian dosa", "Good taste", "restaurant ambiance", "No mention of non-veg"]
},
"current_round": 0,
"performance_history": [], # Track performance across iterations
"feedback_history": [] # Track all feedback received
}
8. Add Contextual Awareness
python
def prompt_selector(state: State) -> State:
"""Enhanced prompt selector with more context"""
response = prompt_selector_chain.invoke({
"prompts": state['configured_prompts'],
"business_domain": state['business_domain'],
"business_name": state['business_name'],
"user_config": state['user_config'],
"platform": state['platform'], # Add platform awareness
"previous_attempts": state.get("current_round", 0) # Track how many attempts have been made
})
return {"selected_prompt": response.final_prompt}
These improvements focus on:
Better input validation
More detailed state tracking
Enhanced context passing between steps
More sophisticated evaluation metrics
Early termination conditions
Performance tracking
Better feedback utilization
All of these can be implemented without adding new nodes to your graph, just by enhancing the existing functions and state management.