from contextlib import asynccontextmanager from langsmith.wrappers import OpenAIAgentsTracingProcessor from agent.linkedin_assistant import create_assistant_agent from openai.types.responses import ResponseTextDeltaEvent from fastapi.middleware.cors import CORSMiddleware from agents import Runner, set_trace_processors from fastapi.responses import StreamingResponse from dotenv import find_dotenv, load_dotenv from fastapi import FastAPI, HTTPException from pydantic import BaseModel import json import os load_dotenv(find_dotenv()) os.environ["LANGCHAIN_TRACING_V2"] = "true" os.environ["LANGCHAIN_API_KEY"] = os.getenv("LANGSMITH_API_KEY") os.environ["LANGCHAIN_PROJECT"] = "linkedin" set_trace_processors([OpenAIAgentsTracingProcessor()]) @asynccontextmanager async def lifespan(app: FastAPI): global assistant_agent try: from agent.linkedin_assistant import create_assistant_agent assistant_agent = await create_assistant_agent() print("[✓] Assistant agent initialized.") yield except Exception as e: print(f"[✗] Failed to initialize assistant agent: {e}") raise # Let FastAPI shutdown cleanly on failure app: FastAPI = FastAPI(lifespan=lifespan) # Add CORS middleware app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) # @app.on_event("startup") # async def startup_event(): # global assistant_agent # assistant_agent = await create_assistant_agent() @app.post("/run") async def agent_fastapi(input): result = await Runner.run(assistant_agent, input=input) print(result.final_output) return result.final_output async def stream_response(input): result = Runner.run_streamed(assistant_agent, input=input) async for events in result.stream_events(): if events.type == "raw_response_event" and isinstance( events.data, ResponseTextDeltaEvent ): chunk = json.dumps(events.data.delta) yield chunk class InputData(BaseModel): input: str @app.post("/chat/stream") async def agent_fastapi_streaming(data: InputData): if not data.input: raise HTTPException(status_code=400, detail="Message text cannot be empty") return StreamingResponse( stream_response(data.input), media_type="text/event-stream" ) # if __name__ == "__main__": # import uvicorn # uvicorn.run(app="main:app", host="0.0.0.0", port=8002, reload=True)