trygithubactions / main.py
subashpoudel's picture
Next commit
fa8520f
raw
history blame
6.3 kB
from fastapi import FastAPI , UploadFile , File , Form
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from brainstroming_agent.agent import brainstroming_graph
import pandas as pd
from typing import Optional , List
from context_analysis_agent.agent import IntroductionChatbot
from business_interaction_agent.agent import BusinessInteractionChatbot
from context_analysis_agent.utils.utils import save_to_db
import ast
from orchestration_agent.agent import orchestration_chat
from orchestration_agent.utils.utils import caption_image
from brainstroming_agent.utils.utils import encode_image_to_base64 , generate_final_story, generate_image
from idea_to_budget_agent.agent import budget_calculator
from ideation_agent.agent import ideation_graph
from langgraph.errors import GraphRecursionError
from human_refined_ideation.agent import human_refined_idea
from dummy_state import stored_data
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)
stored_data['image_caption']= result.image_caption
return {'tool_response': result.tool , 'message_response': result.message, 'image_caption':result.image_caption}
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
return {"response": response, "business_details": details, "complete": True}
return {"response": response, "complete": False}
@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']]
},
config=config,
)
stored_data['final_ideation'] = result['improver_response'][-1]
stored_data['final_ideation']=ast.literal_eval(stored_data['final_ideation'])
return {'response':result}
except GraphRecursionError:
result = idea_graph.get_state({"configurable": {"thread_id": "ideation_thread123"}})
return {'response': 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['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
):
result = brainstrom_graph.invoke({
'idea': [stored_data['refined_ideation']],
'images': request.image_base64_list,
'latest_preferred_topics': request.preferred_topics,
'business_details': (lambda d: d['business_details'] if 'business_details' in d else {})(stored_data)
},
config={"configurable": {"thread_id": request.thread_id}})
stored_data['brainstroming_response'] = result
return {'response': result}
@app.post("/generate-final-story")
def generate_final_story_endpoint():
final_story = generate_final_story(stored_data["brainstroming_response"])
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['final_story'])
,str(stored_data['business_details'])
,str(stored_data['refined_ideation']))
stored_data['generated_image']=image
return {
'response':image
}