File size: 2,513 Bytes
01038c9
 
 
 
 
 
 
 
 
 
 
 
f8fb96c
01038c9
f8fb96c
01038c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc4bf84
01038c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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)