-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathllm.py
More file actions
153 lines (126 loc) · 4.6 KB
/
llm.py
File metadata and controls
153 lines (126 loc) · 4.6 KB
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
import logging
from uuid import UUID
from fastapi import APIRouter, Depends
from app.api.deps import AuthContextDep, SessionDep
from app.api.permissions import Permission, require_permission
from app.core.exception_handlers import HTTPException
from app.crud.jobs import JobCrud
from app.crud.llm import get_llm_calls_by_job_id
from app.models import (
LLMCallRequest,
LLMCallResponse,
LLMJobImmediatePublic,
LLMJobPublic,
)
from app.models.llm.response import LLMResponse, Usage
from app.services.llm.jobs import start_job
from app.utils import APIResponse, validate_callback_url, load_description
logger = logging.getLogger(__name__)
router = APIRouter(tags=["LLM"])
llm_callback_router = APIRouter()
@llm_callback_router.post(
"{$callback_url}",
name="llm_callback",
)
def llm_callback_notification(body: APIResponse[LLMCallResponse]):
"""
Callback endpoint specification for LLM call completion.
The callback will receive:
- On success: APIResponse with success=True and data containing LLMCallResponse
- On failure: APIResponse with success=False and error message
- metadata field will always be included if provided in the request
"""
...
@router.post(
"/llm/call",
description=load_description("llm/llm_call.md"),
response_model=APIResponse[LLMJobImmediatePublic],
callbacks=llm_callback_router.routes,
dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))],
)
def llm_call(
_current_user: AuthContextDep, session: SessionDep, request: LLMCallRequest
):
"""
Endpoint to initiate an LLM call as a background job.
Returns job information for polling.
"""
project_id = _current_user.project_.id
organization_id = _current_user.organization_.id
if request.callback_url:
validate_callback_url(str(request.callback_url))
job_id = start_job(
db=session,
request=request,
project_id=project_id,
organization_id=organization_id,
)
# Fetch job details to return immediate response
job_crud = JobCrud(session=session)
job = job_crud.get(job_id=job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
if request.callback_url:
message = "Your response is being generated and will be delivered via callback."
else:
message = "Your response is being generated"
job_response = LLMJobImmediatePublic(
job_id=job.id,
status=job.status.value,
message=message,
job_inserted_at=job.created_at,
job_updated_at=job.updated_at,
)
return APIResponse.success_response(data=job_response)
@router.get(
"/llm/call/{job_id}",
description=load_description("llm/get_llm_call.md"),
response_model=APIResponse[LLMJobPublic],
dependencies=[Depends(require_permission(Permission.REQUIRE_PROJECT))],
)
def get_llm_call_status(
_current_user: AuthContextDep,
session: SessionDep,
job_id: UUID,
) -> APIResponse[LLMJobPublic]:
"""
Poll for LLM call job status and results.
Returns job information with nested LLM response when complete.
"""
job_crud = JobCrud(session=session)
job = job_crud.get(job_id=job_id)
if not job:
raise HTTPException(status_code=404, detail="Job not found")
llm_call_response = None
if job.status.value == "SUCCESS":
llm_calls = get_llm_calls_by_job_id(
session=session, job_id=job_id, project_id=_current_user.project_.id
)
if llm_calls:
# Get the first LLM call from the list which will be the only call for the job id
# since we initially won't be using this endpoint for llm chains
llm_call = llm_calls[0]
llm_response = LLMResponse(
provider_response_id=llm_call.provider_response_id or "",
conversation_id=llm_call.conversation_id,
provider=llm_call.provider,
model=llm_call.model,
output=llm_call.content,
)
if not llm_call.usage:
raise HTTPException(
status_code=500,
detail="Completed LLM job is missing usage data",
)
llm_call_response = LLMCallResponse(
response=llm_response,
usage=Usage(**llm_call.usage),
provider_raw_response=None,
)
job_response = LLMJobPublic(
job_id=job.id,
status=job.status.value,
llm_response=llm_call_response,
error_message=job.error_message,
)
return APIResponse.success_response(data=job_response)