trygithubactions / main.py
subashpoudel's picture
Included CI CD
583f6dd
raw
history blame
7.98 kB
from fastapi import FastAPI , UploadFile , File , Form
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from src.genai.brainstroming_agent.agent import brainstroming_graph
import pandas as pd
from typing import Optional , List
from src.genai.context_analysis_agent.agent import IntroductionChatbot
from src.genai.business_interaction_agent.agent import BusinessInteractionChatbot
from src.genai.context_analysis_agent.utils.utils import save_to_db
import ast
from src.genai.orchestration_agent.agent import orchestration_chat
from src.genai.orchestration_agent.utils.utils import caption_image , show_analytics
from src.genai.brainstroming_agent.utils.utils import encode_image_to_base64 , generate_final_story, generate_image
from src.genai.idea_to_budget_agent.agent import budget_calculator
from src.genai.ideation_agent.agent import ideation_graph
from langgraph.errors import GraphRecursionError
from src.genai.human_refined_ideation.agent import human_refined_idea
from dummy_state import stored_data, long_term_memory
import json
# Store brainstorming results per thread_id
app = FastAPI()
context_analysis_graph = IntroductionChatbot()
business_interaction_graph = BusinessInteractionChatbot()
idea_graph = ideation_graph()
brainstrom_graph = brainstroming_graph()
human_refine_graph = human_refined_idea()
# orchestrate_graph = orchestration_chat()
class OrchestrationRequest(BaseModel):
message: str
image_base64 : Optional[list] = []
@app.post("/orchestration")
def orchestration_endpoint(request:OrchestrationRequest):
print('Image:',request.image_base64)
result = orchestration_chat(request.message , request.image_base64)
if result.image_caption != '':
stored_data['image_caption']=result.image_caption
if result.video_idea !='' or result.video_idea != 'null':
stored_data['refined_ideation']= result.video_idea
if result.video_story!='' or result.video_story!='null':
stored_data['final_story']= result.video_story
print('Idea:',stored_data['refined_ideation'])
print('Story:', stored_data['final_story'])
return {'tool_response': result.tool ,
'message_response': result.query_response,
'image_caption':result.image_caption,
'video_idea': result.video_idea,
'video_story': result.video_story}
class UserMessage(BaseModel):
message: str
@app.post("/context-analysis")
def context_analysis(msg: UserMessage):
response = context_analysis_graph.chat(msg.message)
if context_analysis_graph.is_complete(response):
details = context_analysis_graph.extract_details()
if type(details) != dict:
details = details.model_dump()
print('Business_details:',details)
if isinstance(details, str):
details= ast.literal_eval(details)
print('Details Type:',type(details))
# save_to_db(details)
stored_data['business_details'] = details
context_analysis_graph.reset()
return {"response": response, "business_details": details, "complete": True}
return {"response": response, "complete": False}
@app.post("/show-analytics")
def show_analytics_endpoint():
response = show_analytics(stored_data['business_details'])
return {'response': response}
@app.post("/business-interaction")
def business_interaction(interaction: str):
response,business_details = business_interaction_graph.chat(interaction , stored_data['business_details'])
stored_data['business_details']=business_details
return {'response': response}
class IdeationRequest(BaseModel):
topic : List[str]
@app.post("/ideation")
def ideation_endpoint():
config={"recursion_limit":15, "configurable": {"thread_id": "ideation_thread123"}}
try:
result = idea_graph.invoke(
{
'business_details': [stored_data['business_details']],
'image_caption': [stored_data['image_caption'] if 'image_caption' in stored_data else ""]
},
config=config,
)
stored_data['final_ideation'] = result['improver_response'][-1]
stored_data['final_ideation']=ast.literal_eval(stored_data['final_ideation'])
return {'response':ast.literal_eval(result['improver_response'][-1])}
except GraphRecursionError:
result = idea_graph.get_state({"configurable": {"thread_id": "ideation_thread123"}})
return {'response': ast.literal_eval(result[0])}
class RefineIdeationRequest(BaseModel):
query: str
thread_id: Optional[str]="refine_ideas_thread"
@app.post("/human-idea-refining")
def human_idea_refine_endpoint(request:RefineIdeationRequest):
stored_data['human_ideation_interactions'].append({"role": "user", "content": request.query})
response = human_refine_graph.invoke(
{
'query': stored_data['human_ideation_interactions'],
'business_details': stored_data["business_details"],
'final_ideation': stored_data.get('final_ideation',["","","",""]),
},config={"configurable": {"thread_id": request.thread_id}}
)
stored_data['human_ideation_interactions'].append({"role": "assistant", "content": response['result']})
stored_data['refined_ideation'] = stored_data['human_ideation_interactions'][-1]['content']
return {'response' : stored_data['human_ideation_interactions'][-1]['content'] }
@app.post("/budget-mapping")
def budget_mapping_endpoint():
result = budget_calculator(stored_data["business_details"],stored_data['final_ideation'])
return {'response':result}
class BrainstormRequest(BaseModel):
preferred_topics: Optional[list] = []
image_base64_list: Optional[list] = []
thread_id: Optional[str]="default-session"
@app.post("/brainstorm")
def brainstroming_endpoint(
request: BrainstormRequest, # 🔥 Full JSON body here
):
idea = (
[stored_data['refined_ideation']]
if stored_data.get('refined_ideation')
else [str(stored_data['final_ideation'])]
if stored_data.get('final_ideation')
else ['''I don't have any idea right now. Create your own **very creative** and **out of the box** video idea and generate the story for now.'''])
result = brainstrom_graph.invoke({
# 'idea': [stored_data.get('refined_ideation', 'final_ideation', )],
'idea': idea,
'images': request.image_base64_list,
'latest_preferred_topics': request.preferred_topics,
'business_details': stored_data['business_details']
},
config={"configurable": {"thread_id": request.thread_id}})
stored_data['brainstroming_response'] = result
return {'response':{
"story": result['stories'][-1],
"brainstorming_topics": result['brainstroming_topics'][-1]
}}
@app.post("/generate-final-story")
def generate_final_story_endpoint():
final_story = generate_final_story(
stored_data.get("brainstroming_response") or stored_data.get("business_details")
)
stored_data['final_story']=final_story
return {
'response': final_story
}
# stored_data['final_story']= '''A cinematic journey follows a street magician\'s
# metamorphosis from a mere trickster to a powerful performer, as he transforms his act with newfound physical strength, effortlessly executing death-defying stunts, and inspiring a captivated crowd to take action, all set against a
# backdrop of urban grandeur and pulsing energy.'''
@app.post("/generate-image")
def generate_image_endpoint():
image = generate_image(str(stored_data.get('final_story','''I don't have any story right now. Just use the business details for now.'''))
,str(stored_data.get('business_details'))
,str(stored_data.get('refined_ideation','''I don't have any idea right now. Just use the business details for now.''')))
stored_data['generated_image']=image
return {
'response':image
}