chatCompletionToMessage.ts 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. import { Message } from '../foundation';
  2. import { ChatCompletion, Choice, ChatCompletionToolCalls, ChatCompletionToolCall, ChatCompletionCustomToolCall } from './interface';
  3. /*
  4. Chat Completion VS. Response
  5. - The former only have content、refusal、function_call、tool_calls;
  6. - The former annotations belongs to content;
  7. - The former function_call and tool_calls do not have call_id and status;
  8. */
  9. export default function chatCompletionToMessage(chatCompletion: ChatCompletion): Message[] {
  10. return chatCompletion.choices.map((choice: Choice) => {
  11. const message = choice.message;
  12. const role = message.role;
  13. const id = chatCompletion.id;
  14. const status = 'completed';
  15. const outputResult = [];
  16. // processing text and refusal
  17. if (message.content !== '' || message.refusal !== '') {
  18. const annotations = (message.annotations?.length
  19. ? message.annotations.map((annotation) => ({
  20. type: annotation.type,
  21. ...(annotation.url_citation || {}),
  22. }))
  23. : []);
  24. const outputMessage = [
  25. message.content !== '' && {
  26. type: 'output_text',
  27. text: message.content,
  28. annotations,
  29. },
  30. message.refusal !== '' && {
  31. type: 'refusal',
  32. refusal: message.refusal,
  33. },
  34. ].filter(Boolean);
  35. outputResult.push({
  36. type: 'message',
  37. id: id,
  38. role: 'assistant',
  39. status: status,
  40. content: outputMessage
  41. });
  42. }
  43. // processing function call
  44. if (message.function_call) {
  45. outputResult.push({
  46. ...message.function_call,
  47. type: 'function_call',
  48. status: 'completed',
  49. });
  50. }
  51. // processing tool calls
  52. if (message?.tool_calls?.length) {
  53. const toolCalls = message.tool_calls.map((toolCall: ChatCompletionToolCalls) => {
  54. if (toolCall.type === 'function') {
  55. return {
  56. status: 'completed',
  57. ...(toolCall as ChatCompletionToolCall).function,
  58. type: 'function_call',
  59. // todo: call_id?
  60. };
  61. }
  62. return {
  63. ...(toolCall as ChatCompletionCustomToolCall).custom,
  64. type: 'custom_call',
  65. };
  66. });
  67. outputResult.push(...toolCalls);
  68. }
  69. // Currently, the Response API does not support voice output, but chat completion does.
  70. if (message.audio) {
  71. outputResult.push({
  72. type: 'audio',
  73. ...message.audio,
  74. });
  75. }
  76. return {
  77. id: id,
  78. role: role,
  79. content: outputResult,
  80. status: status,
  81. };
  82. });
  83. }