Coding-With-Raptor/Likendin-Agent
0
1from contextlib import asynccontextmanager2from langsmith.wrappers import OpenAIAgentsTracingProcessor3from agent.linkedin_assistant import create_assistant_agent4from openai.types.responses import ResponseTextDeltaEvent5from fastapi.middleware.cors import CORSMiddleware6from agents import Runner, set_trace_processors7from fastapi.responses import StreamingResponse8from dotenv import find_dotenv, load_dotenv9from fastapi import FastAPI, HTTPException10from pydantic import BaseModel11import json12import os13 14load_dotenv(find_dotenv())15 16os.environ["LANGCHAIN_TRACING_V2"] = "true"17os.environ["LANGCHAIN_API_KEY"] = os.getenv("LANGSMITH_API_KEY")18os.environ["LANGCHAIN_PROJECT"] = "linkedin"19 20set_trace_processors([OpenAIAgentsTracingProcessor()])21 22 23@asynccontextmanager24async def lifespan(app: FastAPI):25 global assistant_agent26 try:27 from agent.linkedin_assistant import create_assistant_agent28 assistant_agent = await create_assistant_agent()29 print("[✓] Assistant agent initialized.")30 yield31 except Exception as e:32 print(f"[✗] Failed to initialize assistant agent: {e}")33 raise # Let FastAPI shutdown cleanly on failure34 35 36app: FastAPI = FastAPI(lifespan=lifespan)37 38# Add CORS middleware39app.add_middleware(40 CORSMiddleware,41 allow_origins=["*"],42 allow_credentials=True,43 allow_methods=["*"],44 allow_headers=["*"],45)46 47# @app.on_event("startup")48# async def startup_event():49# global assistant_agent50# assistant_agent = await create_assistant_agent()51 52@app.post("/run")53async def agent_fastapi(input):54 result = await Runner.run(assistant_agent, input=input)55 print(result.final_output)56 return result.final_output57 58 59async def stream_response(input):60 result = Runner.run_streamed(assistant_agent, input=input)61 async for events in result.stream_events():62 if events.type == "raw_response_event" and isinstance(63 events.data, ResponseTextDeltaEvent64 ):65 chunk = json.dumps(events.data.delta)66 yield chunk67 68 69class InputData(BaseModel):70 input: str71 72 73@app.post("/chat/stream")74async def agent_fastapi_streaming(data: InputData):75 if not data.input:76 raise HTTPException(status_code=400, detail="Message text cannot be empty")77 return StreamingResponse(78 stream_response(data.input), media_type="text/event-stream"79 )80 81 82# if __name__ == "__main__":83# import uvicorn84 85# uvicorn.run(app="main:app", host="0.0.0.0", port=8002, reload=True)86 