( # pyright: ignore[reportUnusedFunction]
http_request: Request, body: CreateChatCompletionRequest
)
| 16007 | |
| 16008 | @app.post("/v1/chat/completions") |
| 16009 | async def create_chat_completion( # pyright: ignore[reportUnusedFunction] |
| 16010 | http_request: Request, body: CreateChatCompletionRequest |
| 16011 | ): |
| 16012 | service: CompletionService = app.state.service |
| 16013 | formatter = service.formatter |
| 16014 | try: |
| 16015 | parts = formatter.completion_request_from_chat_request( |
| 16016 | body, |
| 16017 | ) |
| 16018 | except CompletionRequestValidationError as exc: |
| 16019 | raise bad_request(exc) from exc |
| 16020 | template_functions = ( |
| 16021 | [function.to_template_function() for function in body.functions] |
| 16022 | if body.functions is not None |
| 16023 | else None |
| 16024 | ) |
| 16025 | template_tools = ( |
| 16026 | [tool.to_template_tool() for tool in body.tools] |
| 16027 | if body.tools is not None |
| 16028 | else None |
| 16029 | ) |
| 16030 | try: |
| 16031 | request = service.request_from_prepared( |
| 16032 | payload=parts.payload, |
| 16033 | prompt_text=parts.prompt_text, |
| 16034 | prompt_plan=parts.prompt_plan, |
| 16035 | grammar_text=parts.grammar_text, |
| 16036 | chat_tool_name=parts.tool_name, |
| 16037 | ) |
| 16038 | stream, cancel = service.submit_request(request) |
| 16039 | except CompletionRequestValidationError as exc: |
| 16040 | raise bad_request(exc) from exc |
| 16041 | if body.stream: |
| 16042 | started_indices: set[int] = set() |
| 16043 | |
| 16044 | def chat_chunk_payloads( |
| 16045 | completion_chunk: CompletionChunk, |
| 16046 | ) -> Iterable[BaseModel | Dict[str, Any]]: |
| 16047 | return formatter.convert_completion_chunk_to_chat_chunks( |
| 16048 | completion_chunk, |
| 16049 | started_indices, |
| 16050 | parts.tool_name, |
| 16051 | functions=template_functions, |
| 16052 | tools=template_tools, |
| 16053 | parsed_states=parsed_states, |
| 16054 | generation_prompt=parts.generation_prompt, |
| 16055 | ) |
| 16056 | |
| 16057 | parsed_states: Dict[int, Dict[str, Any]] = {} |
| 16058 | return StreamingResponse( |
| 16059 | stream_sse_chunks( |
| 16060 | formatter, |
| 16061 | http_request, |
| 16062 | stream, |
| 16063 | cancel, |
| 16064 | chat_chunk_payloads, |
| 16065 | ), |
| 16066 | media_type="text/event-stream", |
nothing calls this directly
no test coverage detected
searching dependent graphs…