llm.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (c) 2006-2025, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2025/02/01 Rbb666 Add license info
  9. * 2025/02/01 Rbb666 Add history support
  10. * 2025/02/10 CXSforHPU Add llm history support
  11. */
  12. #ifndef __LLM_H_
  13. #define __LLM_H_
  14. #include <rtthread.h>
  15. #include <stdio.h>
  16. #include <string.h>
  17. #include <cJSON.h>
  18. #ifndef PKG_LLMCHAT_DBG
  19. #define LLM_DBG(fmt, ...)
  20. #else
  21. #define LLM_DBG(fmt, ...) \
  22. do \
  23. { \
  24. rt_kprintf("[\033[32mLLM\033[0m] "); \
  25. rt_kprintf(fmt, ##__VA_ARGS__); \
  26. } while (0)
  27. #endif
  28. #ifndef LLM_HISTORY_LINES
  29. #define LLM_HISTORY_LINES 5
  30. #endif
  31. #define LLM_CHAT_NUM 10
  32. enum llm_input_stat
  33. {
  34. LLM_WAIT_NORMAL,
  35. LLM_WAIT_SPEC_KEY,
  36. LLM_WAIT_FUNC_KEY,
  37. };
  38. typedef void (*llm_stream_callback_t)(const char *chunk, void *user_data);
  39. struct llm_obj
  40. {
  41. /* thread */
  42. struct rt_thread thread;
  43. rt_uint8_t thread_stack[PKG_LLM_THREAD_STACK_SIZE];
  44. struct rt_semaphore rx_sem;
  45. enum llm_input_stat stat;
  46. int argc;
  47. char llm_history[LLM_HISTORY_LINES][PKG_LLM_CMD_BUFFER_SIZE];
  48. rt_uint16_t history_count;
  49. rt_uint16_t history_current;
  50. char line[PKG_LLM_CMD_BUFFER_SIZE];
  51. rt_uint16_t line_position;
  52. rt_uint8_t line_curpos;
  53. rt_device_t device;
  54. rt_err_t (*rx_indicate)(rt_device_t dev, rt_size_t size);
  55. /* messages */
  56. cJSON *messages;
  57. char *(*get_answer)(struct llm_obj *handle, cJSON *messages);
  58. void *(*send_llm_mb)(char* input_buffer);
  59. rt_mailbox_t inputbuff_mb;
  60. rt_mailbox_t outputbuff_mb;
  61. /* optional streaming callback */
  62. llm_stream_callback_t stream_cb;
  63. void *stream_user_data;
  64. };
  65. typedef struct llm_obj *llm_t;
  66. char *get_llm_answer(llm_t handle, cJSON *messages);
  67. void add_message2messages(const char *input_buffer, char *role,llm_t handle);
  68. cJSON *create_message(const char *input_buffer, char *role);
  69. void clear_messages(llm_t handle);
  70. rt_err_t init_llm(llm_t handle);
  71. llm_t create_llm_t();
  72. void delete_llm_t(llm_t handle);
  73. void display_llm_messages(llm_t handle);
  74. void send_llm_mb(llm_t handle, char *inputBuffer);
  75. #endif