Process a ChatKit endpoint request with context supplied by the app.
Return 400 for malformed JSON, 404 for a missing resource, 409 for a
thread-state conflict, and 422 for an invalid or unsupported request.
Close the event stream on disconnect.
An app-supplied streaming response takes ownership of its result. It must
await result.aclose() when the response ends or the client disconnects.
Source code in chatkit/fastapi.py
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
154
155
156 | async def process_request[TContext](
server: ChatKitServer[TContext],
request: Request,
context: TContext,
*,
streaming_response: Callable[
[StreamingResult], Response
] = ChatKitStreamingResponse,
) -> Response:
"""Process a ChatKit endpoint request with context supplied by the app.
Return 400 for malformed JSON, 404 for a missing resource, 409 for a
thread-state conflict, and 422 for an invalid or unsupported request.
Close the event stream on disconnect.
An app-supplied streaming response takes ownership of its result. It must
await `result.aclose()` when the response ends or the client disconnects.
"""
try:
operation = parse_request(await request.body())
result = await server.process(operation, context)
except InvalidRequestError as error:
errors = error.validation_error.errors(
include_input=False, include_context=False, include_url=False
)
if any(issue["type"] == "json_invalid" for issue in errors):
return JSONResponse(
{"detail": "Malformed JSON request body."}, status_code=400
)
detail = []
for issue in errors:
location = list(issue["loc"])
issue_type = issue["type"]
message = issue["msg"]
if issue_type == "union_tag_invalid":
message = "Unknown value for the type field."
if not location:
message = "Unknown ChatKit operation."
elif issue_type == "union_tag_not_found" and not location:
message = "ChatKit operation is required."
if (
issue_type in ("union_tag_invalid", "union_tag_not_found")
and not location
):
location = ["type"]
if location[:4] == [
"threads.add_structured_input",
"params",
"input",
"answers",
]:
# The mapping keys are application-supplied question IDs.
location = location[:4]
detail.append({
"location": location,
"message": message,
"type": issue_type,
})
return JSONResponse({"detail": detail}, status_code=422)
except NotFoundError:
return JSONResponse({"detail": "ChatKit resource not found."}, status_code=404)
except ConflictError:
return JSONResponse(
{"detail": "The request conflicts with the current thread state."},
status_code=409,
)
except (InvalidOperationError, UnsupportedOperationError) as error:
return JSONResponse({"detail": str(error)}, status_code=422)
if isinstance(result, StreamingResult):
try:
return streaming_response(result)
except BaseException:
await result.aclose()
raise
return Response(content=encode_message(result), media_type="application/json")
|