ctod 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/.api-key +1 -0
  2. package/.nyc_output/42919e68-b472-4a5d-b2d3-5d5153f28467.json +1 -0
  3. package/.nyc_output/processinfo/42919e68-b472-4a5d-b2d3-5d5153f28467.json +1 -0
  4. package/.nyc_output/processinfo/index.json +1 -0
  5. package/.output/.output/stores//344/270/200/345/240/264/346/234/237/345/276/205/345/267/262/344/271/205/347/232/204/345/222/214/350/247/243/cover-0.png +1 -0
  6. package/.output/.output/stores//344/270/200/345/240/264/346/234/237/345/276/205/345/267/262/344/271/205/347/232/204/345/222/214/350/247/243/cover-1.png +1 -0
  7. package/.output/.output/stores//344/270/200/345/240/264/346/234/237/345/276/205/345/267/262/344/271/205/347/232/204/345/222/214/350/247/243/story-config.json +4 -0
  8. package/.output/.output/stores//344/270/200/345/240/264/346/234/237/345/276/205/345/267/262/344/271/205/347/232/204/345/222/214/350/247/243/story.json +22 -0
  9. package/.output/.output/stores//345/276/236/351/273/221/346/232/227/350/265/260/345/220/221/345/205/211/346/230/216/cover-0.png +1 -0
  10. package/.output/.output/stores//345/276/236/351/273/221/346/232/227/350/265/260/345/220/221/345/205/211/346/230/216/cover-1.png +1 -0
  11. package/.output/.output/stores//345/276/236/351/273/221/346/232/227/350/265/260/345/220/221/345/205/211/346/230/216/story-config.json +4 -0
  12. package/.output/.output/stores//345/276/236/351/273/221/346/232/227/350/265/260/345/220/221/345/205/211/346/230/216/story.json +24 -0
  13. package/.output/.output/stores//347/240/264/347/242/216/347/232/204/345/271/273/350/261/241/cover-0.png +1 -0
  14. package/.output/.output/stores//347/240/264/347/242/216/347/232/204/345/271/273/350/261/241/cover-1.png +1 -0
  15. package/.output/.output/stores//347/240/264/347/242/216/347/232/204/345/271/273/350/261/241/story-config.json +4 -0
  16. package/.output/.output/stores//347/240/264/347/242/216/347/232/204/345/271/273/350/261/241/story.json +24 -0
  17. package/.output/.output/stores//350/227/235/350/241/223/345/256/266/347/232/204/351/235/210/346/204/237/cover-0.png +1 -0
  18. package/.output/.output/stores//350/227/235/350/241/223/345/256/266/347/232/204/351/235/210/346/204/237/cover-1.png +1 -0
  19. package/.output/.output/stores//350/227/235/350/241/223/345/256/266/347/232/204/351/235/210/346/204/237/story-config.json +4 -0
  20. package/.output/.output/stores//350/227/235/350/241/223/345/256/266/347/232/204/351/235/210/346/204/237/story.json +28 -0
  21. package/.output/.output/stores//350/250/230/346/206/266/345/225/206/344/272/272/cover-0.png +1 -0
  22. package/.output/.output/stores//350/250/230/346/206/266/345/225/206/344/272/272/cover-1.png +1 -0
  23. package/.output/.output/stores//350/250/230/346/206/266/345/225/206/344/272/272/story-config.json +4 -0
  24. package/.output/.output/stores//350/250/230/346/206/266/345/225/206/344/272/272/story.json +18 -0
  25. package/.output/.output/stores//350/250/255/350/250/210/350/210/207/351/226/213/347/231/274/347/232/204/346/214/221/346/210/260/content.json +22 -0
  26. package/.output/.output/talks//344/273/245/347/254/221/350/251/261/347/202/272/345/237/272/347/244/216/347/232/204/351/235/242/350/251/246/content.json +30 -0
  27. package/.output/.output/talks//344/273/245/347/254/221/350/251/261/347/202/272/345/237/272/347/244/216/347/232/204/351/235/242/350/251/246/cover-1684055229695.png +0 -0
  28. package/.output/.output/talks//345/234/250/346/224/277/346/262/273/345/200/231/351/201/270/344/272/272/350/276/257/350/253/226/344/270/255/347/232/204/350/252/252/346/234/215/346/200/247/346/272/235/351/200/232/content.json +30 -0
  29. package/.output/.output/talks//345/234/250/346/224/277/346/262/273/345/200/231/351/201/270/344/272/272/350/276/257/350/253/226/344/270/255/347/232/204/350/252/252/346/234/215/346/200/247/346/272/235/351/200/232/cover-1684056611678.png +0 -0
  30. package/.output/.output/talks//346/224/276/351/254/206/347/232/204/345/200/231/351/201/270/344/272/272/351/200/262/350/241/214/346/224/277/346/262/273/350/276/257/350/253/226/content.json +36 -0
  31. package/.output/.output/talks//346/224/276/351/254/206/347/232/204/345/200/231/351/201/270/344/272/272/351/200/262/350/241/214/346/224/277/346/262/273/350/276/257/350/253/226/cover-1684055140609.png +0 -0
  32. package/.output/.output/talks//346/224/277/346/262/273/347/254/221/350/251/261/content.json +30 -0
  33. package/.output/.output/talks//346/224/277/346/262/273/347/254/221/350/251/261/cover-1684056246465.png +0 -0
  34. package/.output/.output/talks//350/251/274/350/253/247/345/256/266/351/225/267/346/225/231/345/270/253/346/234/203/350/255/260/content.json +26 -0
  35. package/.output/.output/talks//350/251/274/350/253/247/345/256/266/351/225/267/346/225/231/345/270/253/346/234/203/350/255/260/cover-1685785935121.png +0 -0
  36. package/.output/.output/talks//350/262/241/345/213/231/351/241/247/345/225/217/350/253/256/350/251/242/content.json +26 -0
  37. package/.output/.output/talks//350/262/241/345/213/231/351/241/247/345/225/217/350/253/256/350/251/242/cover-1685785115833.png +0 -0
  38. package/.output/.output/talks//351/206/253/347/224/237/345/222/214/347/227/205/344/272/272/350/250/216/350/253/226/346/202/262/345/202/267/content.json +32 -0
  39. package/.output/.output/talks//351/206/253/347/224/237/345/222/214/347/227/205/344/272/272/350/250/216/350/253/226/346/202/262/345/202/267/cover-1684055075942.png +0 -0
  40. package/dist/index.js +1 -1
  41. package/package.json +1 -1
  42. package/examples/basic.ts +0 -89
  43. package/examples/llama.cpp.ts +0 -56
  44. package/examples/plugin.ts +0 -118
  45. package/lib/broker/chat.ts +0 -435
  46. package/lib/core/parser.ts +0 -62
  47. package/lib/core/plugin.ts +0 -46
  48. package/lib/core/translator.ts +0 -115
  49. package/lib/ctod.ts +0 -71
  50. package/lib/index.ts +0 -41
  51. package/lib/plugins/index.ts +0 -38
  52. package/lib/plugins/limiter.ts +0 -103
  53. package/lib/plugins/print-log.ts +0 -35
  54. package/lib/plugins/retry.ts +0 -25
  55. package/lib/plugins/role.ts +0 -28
  56. package/lib/service/llama3.cpp/completion.ts +0 -313
  57. package/lib/service/llama3.cpp/index.ts +0 -53
  58. package/lib/service/openai/chat.ts +0 -244
  59. package/lib/service/openai/images-generation.ts +0 -64
  60. package/lib/service/openai/index.ts +0 -97
  61. package/lib/service/openai/vision.ts +0 -111
  62. package/lib/shims.d.ts +0 -4
  63. package/lib/templates.ts +0 -71
  64. package/lib/types.ts +0 -4
  65. package/lib/utils/error.ts +0 -14
  66. package/lib/utils/validate.ts +0 -64
  67. package/logo.ai +2 -1141
  68. package/logo.png +0 -0
  69. package/types/examples/basic.d.ts +0 -1
  70. package/types/examples/chat-demo.d.ts +0 -2
  71. package/types/examples/chat-for-llama.cpp-demo.d.ts +0 -2
  72. package/types/examples/chat-with-json-schema-demo.d.ts +0 -2
  73. package/types/examples/llama.cpp.d.ts +0 -2
  74. package/types/examples/plugin-demo.d.ts +0 -2
  75. package/types/examples/plugin.d.ts +0 -2
  76. package/types/examples/stream-for-llama.cpp-demo.d.ts +0 -2
  77. package/types/examples/vision-demo.d.ts +0 -2
  78. package/types/lib/broker/chat.d.ts +0 -150
  79. package/types/lib/core/parser.d.ts +0 -32
  80. package/types/lib/core/plugin.d.ts +0 -34
  81. package/types/lib/core/translator.d.ts +0 -67
  82. package/types/lib/ctod.d.ts +0 -32
  83. package/types/lib/index.d.ts +0 -34
  84. package/types/lib/plugins/index.d.ts +0 -47
  85. package/types/lib/plugins/limiter.d.ts +0 -36
  86. package/types/lib/plugins/print-log.d.ts +0 -5
  87. package/types/lib/plugins/retry.d.ts +0 -6
  88. package/types/lib/plugins/role.d.ts +0 -5
  89. package/types/lib/service/llama3.cpp/completion.d.ts +0 -61
  90. package/types/lib/service/llama3.cpp/index.d.ts +0 -19
  91. package/types/lib/service/openai/chat.d.ts +0 -110
  92. package/types/lib/service/openai/completion.d.ts +0 -59
  93. package/types/lib/service/openai/images-generation.d.ts +0 -35
  94. package/types/lib/service/openai/index.d.ts +0 -29
  95. package/types/lib/service/openai/vision.d.ts +0 -74
  96. package/types/lib/templates.d.ts +0 -20
  97. package/types/lib/types.d.ts +0 -1
  98. package/types/lib/utils/error.d.ts +0 -11
  99. package/types/lib/utils/validate.d.ts +0 -16
@@ -0,0 +1,4 @@
1
+ {
2
+ "style": "Science Fiction",
3
+ "ending": "Ambiguous ending"
4
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "enUsOutline": "In a dystopian future where memories can be bought and sold, a memory dealer is offered a vast amount of money to acquire a particular set of memories. His quest takes him to forgotten lands and timeless realms, finally leading him to a stunning revelation about the nature of memories and reality.",
3
+ "zhTwOutline": "在一個允許買賣記憶的反烏托邦未來,一位記憶交易者被獻上巨款,換取一份特定的記憶。他的探索帶他走向被遺忘的土地與永恆的境域,最終使他對記憶和現實的本質有了驚人的領悟。",
4
+ "enUsTitle": "The Memory Merchant",
5
+ "zhTwTitle": "記憶商人",
6
+ "enUsContent": [
7
+ "In a dystopian future ravaged by war and decay, memories, once the most personal of possessions, have become just another commodity. Our protagonist, a memory dealer, sells beautiful memories to the wealthy and desperate, longing for an escape from their bleak reality.",
8
+ "One day, a mysterious woman offers him a fortune for a specific set of memories. These memories belong to an old man who passed away a long time ago, and finding them requires a journey to the forgotten corners of the world.",
9
+ "In his quest, he navigates through long abandoned cities and ravaged landscapes, and even steps into timeless, surreal realms where colours, sounds and memories blend into an immersive reality. He encounters strange creatures, stubborn gatekeepers of memory realms, and faces trials and tribulations.",
10
+ "In the climactic end, he acquires the coveted memories and is about to deliver them when he's struck by a stunning revelation. All along, what he perceived as reality was in fact, a memory realm crafted by his own subconscious. The ambiguous ending leaves the viewer questioning the nature of reality and the power of memories."
11
+ ],
12
+ "zhTwContent": [
13
+ "在一個被戰爭與頹廢蹂躪的反烏托邦未來,記憶——曾是最個人化的資產,如今僅成為另一種商品。我們的主角,一位記憶交易者,向富人與絕望者出售美好的記憶,讓他們可以從慘白的現實中逃脫。",
14
+ "有一天,一名神秘的女子給他提供了一筆財富,以取得一套特定的記憶。這些記憶屬於一位很久以前過世的老人,要找到他們,需要一段旅程,走向世界被遺忘的角落。",
15
+ "在他的探索中,他穿越了被遺棄的城市和被破壞的景觀,甚至走進了時無休止、超現實的境域,那裡的色彩、聲音和記憶融為一體,創造出一種身臨其境的現實。他遇到奇怪的生物,是記憶境域中的倔強守門者,面臨著考驗和困難。",
16
+ "在高潮的結尾,他獲得了令人垂涎的記憶,正要交付的時候,他被一個驚人的啟示所打擊。始終,他所認知的現實,其實是由他自己的潛意識構建的一個記憶境域。模糊的結局讓觀者對現實的本質和記憶的力量產生疑問。"
17
+ ]
18
+ }
@@ -0,0 +1,22 @@
1
+ {
2
+ "enUsOutline": "A frustrated meeting between a designer and a developer",
3
+ "zhTwOutline": "一個設計師和開發人員之間感到沮喪的會議",
4
+ "enUsTitle": "The Design vs Development Struggle",
5
+ "zhTwTitle": "設計與開發的挑戰",
6
+ "enUsContent": [
7
+ "Designer: Why is it taking so long for you to implement my designs?",
8
+ "Developer: Your designs don't take into account the limitations of the codebase.",
9
+ "Designer: But I gave you detailed specs and examples!",
10
+ "Developer: Specs can only go so far. Sometimes, we have to work within the constraints of the existing system.",
11
+ "Designer: This is so frustrating! I feel like my vision is being compromised.",
12
+ "Developer: I know it's frustrating, but you need to understand that development doesn't happen in a vacuum. We have to be realistic about what we can achieve."
13
+ ],
14
+ "zhTwContent": [
15
+ "設計師:為什麼你要花這麼長的時間來實現我的設計?",
16
+ "開發人員:你的設計沒有考慮到代碼庫的限制。",
17
+ "設計師:但是我給了你詳細的規格和範例!",
18
+ "開發人員:規格只能做到這種程度。有時候,我們必須在現有系統的限制下工作。",
19
+ "設計師:這太令人沮喪了!我覺得我的設計被犧牲了。",
20
+ "開發人員:我知道這很令人沮喪,但你需要明白開發不是孤立的。我們必須對我們能夠達到的目標保持現實。"
21
+ ]
22
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "enUsOutline": "Job interview for a software engineer position between two curious individuals based on a joke",
3
+ "zhTwOutline": "兩個有好奇心的人根據笑話進行軟體工程師職位面試",
4
+ "enUsTitle": "Joke-based Interview",
5
+ "zhTwTitle": "以笑話為基礎的面試",
6
+ "enUsContent": [
7
+ "Interviewer: So, tell me about a time when you had to debug a particularly difficult issue.",
8
+ "Interviewee: Sure, well, there was this one time where the code just kept telling me 'Knock, knock.'",
9
+ "Interviewer: (confused) Knock, knock?",
10
+ "Interviewee: Yeah, it was a joke! I finally realized that my co-worker had put a 'Who's there?' comment in the code.",
11
+ "Interviewer: (laughs) Well, I hope you were able to solve it!",
12
+ "Interviewee: Of course! (laughs)",
13
+ "Interviewer: Great. So, can you walk me through your experience with implementing data structures?",
14
+ "Interviewee: Absolutely. For example, have you heard the one about the linked list...",
15
+ "Interviewer: (smiling) Oh boy.",
16
+ "Interviewee: (laughs)"
17
+ ],
18
+ "zhTwContent": [
19
+ "面試官:來,請告訴我一個你解決過特別困難問題的經驗。",
20
+ "應徵者:當然可以。那有一次,程式總是告訴我「叩叩」。",
21
+ "面試官:(困惑)叩叩?",
22
+ "應徵者:是的,這是個笑話!最後,我發現我的同事在程式碼裡寫了一個「誰在那裡?」的注釋。",
23
+ "面試官:(笑)好的,希望你能解決它!",
24
+ "應徵者:當然可以!(笑)",
25
+ "面試官:太好了。那你能介紹一下你對實現資料結構的經驗嗎?",
26
+ "應徵者:當然可以。比如,你聽說過關於鏈表的那個笑話嗎……",
27
+ "面試官:(微笑)哦,天哪。",
28
+ "應徵者:(笑)"
29
+ ]
30
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "enUsOutline": "Two curious individuals engage in a political candidate debate with a focus on persuasive communication.",
3
+ "zhTwOutline": "兩位好奇的人進行一場政治候選人辯論,著重於說服性溝通。",
4
+ "enUsTitle": "Persuasive Communication in Political Candidate Debate",
5
+ "zhTwTitle": "在政治候選人辯論中的說服性溝通",
6
+ "enUsContent": [
7
+ "Person 1: Good evening, ladies and gentlemen. We are gathered here tonight for a political candidate debate. Our focus tonight is on the candidates' ability to communicate persuasively.",
8
+ "Person 2: Yes, that's right. Communication is key in politics, and the candidates' ability to persuade voters can make all the difference.",
9
+ "Person 1: Our first question is for Candidate A. What is your stance on immigration, and how do you plan to address the issue?",
10
+ "Candidate A: Thank you for the question. I believe that immigration is a complex issue that requires a comprehensive solution. My plan involves border security measures, a path to citizenship for undocumented immigrants, and increased resources for immigration courts.",
11
+ "Person 2: Candidate B, what is your response to Candidate A's plan?",
12
+ "Candidate B: I believe that border security is the most important aspect of addressing immigration. We need to secure our borders before even considering any sort of path to citizenship.",
13
+ "Person 1: Candidate A, how do you respond to that claim?",
14
+ "Candidate A: While I agree that border security is important, we cannot ignore the fact that there are millions of undocumented immigrants currently living in the United States. We need to address this issue through a comprehensive approach.",
15
+ "Person 2: It's clear that both candidates have different approaches to addressing immigration. But at the end of the day, it will be up to the voters to decide which approach they believe is most persuasive.",
16
+ "Person 1: That's right. Thank you to both candidates for sharing your views on this important issue."
17
+ ],
18
+ "zhTwContent": [
19
+ "人物1:晚上好,女士們先生們。我們今晚聚集在這裡進行一場政治候選人辯論。我們的重點在於候選人的說服能力。",
20
+ "人物2:是的,正確。在政治中,溝通是關鍵,候選人說服選民的能力可以決定一切。",
21
+ "人物1:我們的第一個問題是問A候選人。您對移民的立場是什麼,您打算如何解決這個問題?",
22
+ "A候選人:感謝問題。我認為移民是一個複雜的問題,需要綜合解決方案。我的計劃包括邊境安全措施,非法移民的公民路徑,以及增加移民法庭的資源。",
23
+ "人物2:B候選人,您對A候選人的計劃有何回應?",
24
+ "B候選人:我認為邊境安全是解決移民問題最重要的方面。在考慮任何形式的公民路徑之前,我們需要先保護我們的邊境。",
25
+ "人物1:A候選人,您對這個要求有何回應?",
26
+ "A候選人:儘管我同意邊境安全很重要,但我們不能忽視現在有數百萬無證移民居住在美國的現實。我們需要通過綜合方法來解決這個問題。",
27
+ "人物2:很明顯,兩位候選人對解決移民問題有不同的方法。但在結束的時候,這將由選民決定哪種方法是最有說服力的。",
28
+ "人物1:沒錯。感謝兩位候選人就這個重要問題分享您們的觀點。"
29
+ ]
30
+ }
@@ -0,0 +1,36 @@
1
+ {
2
+ "enUsOutline": "Two relaxed individuals engaging in a political debate between candidates",
3
+ "zhTwOutline": "兩個放鬆的人進行政治候選人之間的辯論",
4
+ "enUsTitle": "Political Debate with Relaxed Candidates",
5
+ "zhTwTitle": "放鬆的候選人進行政治辯論",
6
+ "enUsContent": [
7
+ "Moderator: Good evening! Welcome to tonight's political debate between our two relaxed candidates. We want to remind everyone that this is a civil and respectful discussion even though the candidates might disagree on some issues.",
8
+ "Candidate 1: Thank you, moderator. I appreciate the opportunity to share my views with the audience today.",
9
+ "Candidate 2: Yes, thank you, moderator. I am excited to have this debate and hopefully shed some light on some important topics.",
10
+ "Moderator: Great! So, let’s start with the first question. What is your stance on gun control?",
11
+ "Candidate 1: Well, I believe in the Second Amendment, but I also believe in background checks and limiting access to high powered weapons.",
12
+ "Candidate 2: And I agree with my opponent. We need common sense gun laws that protect our citizens while still allowing people to exercise their Second Amendment rights.",
13
+ "Moderator: Excellent points from both candidates. Our next question is about healthcare reform. What is your plan to improve our healthcare system?",
14
+ "Candidate 1: I support a universal healthcare system that ensures equal access to healthcare for all citizens, regardless of their income or status.",
15
+ "Candidate 2: Although I agree with my opponent’s goal of creating a more equal healthcare system, I also believe that we need to work on making healthcare more affordable for everyone. We need to find a balance between affordability and quality healthcare.",
16
+ "Moderator: Thank you, both candidates, for your insightful answers. Our last question is about climate change. What is your plan to combat climate change?",
17
+ "Candidate 1: Climate change is real and we need to act now. I support investing in renewable energy and reducing our carbon footprint.",
18
+ "Candidate 2: I couldn't agree more. We need to take responsibility for our actions and invest in sustainable, clean energy to protect our planet for future generations.",
19
+ "Moderator: Excellent answers from both candidates. That concludes tonight's debate. Thank you again, candidates, for participating in this important discussion."
20
+ ],
21
+ "zhTwContent": [
22
+ "主持人:晚上好!歡迎來到今晚的政治辯論,這是我們兩位放鬆的候選人之間的辯論。我們要提醒大家,即使候選人在某些問題上可能有意見不一致,這仍然是一個文明、尊重的討論。",
23
+ "候選人1:感謝主持人,我很高興有機會在今天向觀眾分享我的觀點。",
24
+ "候選人2:是的,謝謝主持人。我很激動能夠進行這場辯論,並希望能對一些重要的話題進行充分的討論。",
25
+ "主持人:太好了!那麼,讓我們從第一個問題開始。您對槍支管制持何種立場?",
26
+ "候選人1:嗯,我相信第二修正案,但我也相信背景檢查和限制高功率武器的使用。",
27
+ "候選人2:我同意我的對手。我們需要一些常識性的槍支法律,既保護我們的公民,同時又允許人們行使他們的第二修正案權利。",
28
+ "主持人:候選人的觀點都很好。接下來的問題是關於醫療保健改革。您有何計劃以改善我們的醫療保健系統?",
29
+ "候選人1:我支持一個普及醫療保健制度,確保所有公民平等獲得醫療保健,而不論他們的收入或地位。",
30
+ "候選人2:雖然我同意我的對手創造更平等的醫療保健系統的目標,但我也認為我們需要努力讓每個人都能夠負擔得起醫療保健。我們需要在價格和質量醫療之間找到平衡點。",
31
+ "主持人:感謝候選人提供深入的回答。我們最後的問題是關於氣候變化。您有何計劃抗擊氣候變化?",
32
+ "候選人1:氣候變化是真實存在的,我們需要立即行動。我支持投資於可再生能源和減少我們的碳足跡。",
33
+ "候選人2:我完全同意。我們需要對我們的行為負責,並投資於可持續、清潔的能源,以保護我們的地球為後代。",
34
+ "主持人:兩位候選人的答案都很出色。辯論到此結束。再次感謝候選人參與這個重要的討論。"
35
+ ]
36
+ }
@@ -0,0 +1,30 @@
1
+ {
2
+ "enUsOutline": "Two relaxed individuals having a debate between political candidates with a joke as the starting point.",
3
+ "zhTwOutline": "兩位輕鬆的人以笑話作為起點進行政治候選人辯論。",
4
+ "enUsTitle": "The Political Punchline",
5
+ "zhTwTitle": "政治笑話",
6
+ "enUsContent": [
7
+ "'I heard a joke the other day about a politician and a squirrel,' said John.",
8
+ "'Oh really? Do tell,' replied Kelly.",
9
+ "'Well, the politician was holding a press conference when suddenly a squirrel fell from a tree and landed at his feet. The politician quickly scooped up the squirrel and held it up for the cameras, saying, 'I promise to take care of this little guy just like I promise to take care of all my constituents!''",
10
+ "Kelly laughed, 'That's a good one. Speaking of politicians, have you decided who you're voting for yet?'",
11
+ "'I'm still undecided,' said John, 'I've been watching the debates but they all seem to be making promises like taking care of squirrels.'",
12
+ "Kelly rolled her eyes, 'I know what you mean. It's hard to take any of them seriously.'",
13
+ "'Exactly. They don't seem to have any concrete plans or solutions.'",
14
+ "'Well, we still have some time to decide. Maybe they'll surprise us.'",
15
+ "John chuckled, 'Maybe they'll all start carrying around squirrels on the campaign trail.'",
16
+ "Kelly laughed, 'Now that would definitely get them some attention.'"
17
+ ],
18
+ "zhTwContent": [
19
+ "「我前幾天聽到一個政客和一隻松鼠的笑話,」約翰說道。",
20
+ "「真的嗎?說來聽聽。」凱莉回答。",
21
+ "「這個政客正在舉行記者會的時候,突然有一隻松鼠從樹上掉下來,摔到了他的腳下。政客很快把松鼠撿起來,拿給攝影機拍照,說:『我承諾照顧這個小傢伙,就像我承諾照顧我的選民一樣!』」",
22
+ "凱莉笑了起來:「這真是搞笑。說起政客來,你已經決定要投誰了嗎?」",
23
+ "「我還沒有決定。」約翰說:「我看了辯論,但他們似乎只是像照顧松鼠一樣的承諾。」",
24
+ "凱莉翻了翻白眼:「我知道你的意思。很難認真對待他們。」",
25
+ "「正是。他們似乎沒有任何具體的計劃或解決方案。」",
26
+ "「好吧,我們還有一些時間可以決定。也許他們會給我們帶來驚喜。」",
27
+ "約翰笑了起來:「也許他們都會在競選活動中攜帶松鼠。」",
28
+ "凱莉笑了:「那肯定會吸引人們的注意。」"
29
+ ]
30
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "enUsOutline": "A humorous parent-teacher conference between two nervous people.",
3
+ "zhTwOutline": "兩個緊張的人進行的詼諧家長教師會議。",
4
+ "enUsTitle": "Humorous Parent-Teacher Conference",
5
+ "zhTwTitle": "詼諧家長教師會議",
6
+ "enUsContent": [
7
+ "Parent: Hi, I'm the parent of Johnny. Is he doing okay in your class?",
8
+ "Teacher: Yes, Johnny is a great student. But I noticed he has a lot of nervous ticks. Does he have any anxiety issues?",
9
+ "Parent: No, he's just nervous because he doesn't want to disappoint me.",
10
+ "Teacher: I see. You know, I was a nervous student too. One time I was so nervous, I accidentally called my teacher 'mom'.",
11
+ "Parent: (laughing) That's hilarious. I remember when I was in school, I was so nervous that I couldn't even form a sentence. I just kept saying 'um' and 'uh'.",
12
+ "Teacher: (also laughing) Oh, I remember those days. But don't worry, Johnny is doing great and we'll keep working with him to build his confidence.",
13
+ "Parent: Thanks, that's a relief to hear. I'll try not to be too hard on him.",
14
+ "Teacher: (smiling) Great, let's work together to help Johnny succeed."
15
+ ],
16
+ "zhTwContent": [
17
+ "家長:嗨,我是Johnny的家長。他在你的課堂上表現如何?",
18
+ "老師:是的,Johnny是個很好的學生。但我注意到他有很多緊張的習慣。他有焦慮問題嗎?",
19
+ "家長:沒有,他只是緊張,因為他不想讓我失望。",
20
+ "老師:我明白了。你知道嗎,我也是一個緊張的學生。有一次,我太緊張了,不小心叫老師“媽媽”。",
21
+ "家長:(笑了)太好笑了。我記得我在學校時也很緊張,甚至無法說話。我只能一直說“嗯”和“啊”。",
22
+ "老師:(也笑了)哦,我記得那些日子。但不用擔心,Johnny表現不錯,我們會繼續和他一起努力,建立他的自信心。",
23
+ "家長:謝謝,聽到這是一個放心。我會試著不對他太嚴格。",
24
+ "老師:(微笑)很好,讓我們一起努力幫助Johnny成功。"
25
+ ]
26
+ }
@@ -0,0 +1,26 @@
1
+ {
2
+ "enUsOutline": "Consultation with a financial advisor between two happy people starting from Formal.",
3
+ "zhTwOutline": "兩個 Happy 的人進行 Formal 級別的財務顧問諮詢。",
4
+ "enUsTitle": "A Consultation with a Financial Advisor",
5
+ "zhTwTitle": "財務顧問諮詢",
6
+ "enUsContent": [
7
+ "Person 1: Good afternoon, I'm happy to meet you to discuss my financial situation. My name is Sarah.",
8
+ "Person 2: Good afternoon, Sarah. It's nice to meet you as well. My name is John and I'm a financial advisor.",
9
+ "Person 1: I'm looking for some advice on investments. I have some savings and I don't know what to do with them.",
10
+ "Person 2: Sure, we can definitely help you with that. Can you tell me a bit more about your financial goals?",
11
+ "Person 1: Yes, I'm looking for something that can provide a stable income in the long term.",
12
+ "Person 2: That's definitely achievable. We offer a variety of investment options that can provide a stable income. Would you like to go through them with me?",
13
+ "Person 1: Yes, please. I'm interested in learning more.",
14
+ "Person 2: Great, let's start with some low-risk options..."
15
+ ],
16
+ "zhTwContent": [
17
+ "人1:下午好,我很高興能見到您討論我的財務狀況。我的名字是Sarah。",
18
+ "人2:下午好,Sarah。很高興遇見您。我叫John,是一個財務顧問。",
19
+ "人1:我正在尋求一些關於投資的建議。我有一些儲蓄,但我不知道該怎麼處理它們。",
20
+ "人2:當然,我們絕對可以幫助您。您能告訴我更多關於您的財務目標的信息嗎?",
21
+ "人1:是的,我正在尋找一些能夠提供長期穩定收入的投資方式。",
22
+ "人2:那肯定是可以實現的。我們提供各種能夠提供穩定收入的投資選擇。您想和我一起了解一下嗎?",
23
+ "人1:好的,請。我很感興趣了解更多。",
24
+ "人2:太好了,讓我們從一些低風險的選擇開始..."
25
+ ]
26
+ }
@@ -0,0 +1,32 @@
1
+ {
2
+ "enUsOutline": "A discussion between a doctor and a patient who are both feeling sad.",
3
+ "zhTwOutline": "一位醫生和一位病人進行對話,兩人都感到悲傷。",
4
+ "enUsTitle": "Doctor and patient discussing sadness",
5
+ "zhTwTitle": "醫生和病人討論悲傷",
6
+ "enUsContent": [
7
+ "Doctor: Good morning, how are you feeling today?",
8
+ "Patient: Honestly, not great. I've been feeling really sad and hopeless lately.",
9
+ "Doctor: I'm sorry to hear that. Can you tell me more about what's been going on?",
10
+ "Patient: It just feels like nothing is going right in my life. I've been struggling at work and my relationships aren't going well either.",
11
+ "Doctor: I see. Have you been experiencing any physical symptoms like changes in appetite or sleep patterns?",
12
+ "Patient: Yeah, I haven't been sleeping well and I haven't had much of an appetite.",
13
+ "Doctor: I understand how difficult this can be. I would like to recommend a therapist who can help you work through your feelings and develop coping strategies.",
14
+ "Patient: Okay, thank you. What else can I do to start feeling better?",
15
+ "Doctor: It's important to take care of yourself physically as well. Make sure you're getting enough sleep, eating healthily, and engaging in physical activity that you enjoy.",
16
+ "Patient: Alright, thank you for your help.",
17
+ "Doctor: Of course. Remember, it's okay to not be okay and seeking help is a brave step in the right direction."
18
+ ],
19
+ "zhTwContent": [
20
+ "醫生:早上好,你今天感覺如何?",
21
+ "病人:老實說,感覺不太好。最近我一直感到非常悲傷和絕望。",
22
+ "醫生:聽到這樣的消息我很難受。你能告訴我更多關於發生了什麼事情嗎?",
23
+ "病人:感覺就好像我的生活一切都不如意。我在工作上很辛苦,關係也不太好。",
24
+ "醫生:我了解。你有沒有感到身體上的症狀,像是食慾或是睡眠狀況的改變?",
25
+ "病人:對,我睡得不好,食慾也沒有很好。",
26
+ "醫生:我知道這樣很困難。我想推薦一名治療師,幫助你處理你的情感並且開發應對策略。",
27
+ "病人:好的,謝謝。做些什麼可以讓我感覺更好嗎?",
28
+ "醫生:注意身體健康也很重要。確保你有足夠的睡眠,吃健康飲食並且進行你喜歡的身體活動。",
29
+ "病人:好的,謝謝你的幫助。",
30
+ "醫生:當然。記住,沒關係不好,尋求幫助是朝正確的方向迈出的勇敢一步。"
31
+ ]
32
+ }
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ctod=t():e.ctod=t()}(this||("undefined"!=typeof window?window:global),(()=>(()=>{"use strict";var e={177:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBroker=void 0;const n=a(306),r=a(572),o=a(235),s=a(165);t.ChatBroker=class{__hookType;log;hook=new r.Hook;params;plugins={};installed=!1;translator;event=new r.Event;constructor(e){this.log=new r.Log(e.name??"no name"),this.params=e,this.translator=new o.Translator({...e,parsers:[n.TextParser.JsonMessage()]})}_install(){if(!1===this.installed){this.installed=!0;const e={log:this.log,attach:this.hook.attach.bind(this.hook),attachAfter:this.hook.attachAfter.bind(this.hook),translator:this.translator};if(this.params.plugins){this.plugins="function"==typeof this.params.plugins?this.params.plugins():this.params.plugins;for(let t in this.plugins)this.plugins[t].instance._params.onInstall({...e,params:this.plugins[t].params,receive:this.plugins[t].receive})}this.params.install?.(e)}}async cancel(e){e?this.event.emit("cancel",{requestId:e}):this.event.emit("cancelAll",{})}requestWithId(e){this._install();let t=r.flow.createUuid(),a=null,n=!1,o=!1,i=[this.event.on("cancel",(({requestId:e})=>{e===t&&c()})),this.event.on("cancelAll",(()=>{c()}))],l=()=>i.forEach((e=>e.off())),c=()=>{!1===n&&(o&&a&&a(),n=!0,l())},u=e=>{a=e},p=async()=>{let i=this.translator.getValidate(),l=null,c={},p=new Map,d=await this.translator.compile(e,{schema:i}),h=[],f=[];d.prompt&&f.push({role:"user",content:d.prompt});for(let e in this.plugins)c[e]={send:a=>this.plugins[e].send({id:t,data:a})};return await this.hook.notify("start",{id:t,data:e,schema:i,plugins:c,messages:f,metadata:p,setPreMessages:e=>{h=e.map((e=>({...e,content:Array.isArray(e.content)?e.content.join("\n"):e.content})))},changeMessages:e=>{f=e},changeOutputSchema:e=>{this.translator.changeOutputSchema(e),i=this.translator.getValidate()}}),f=[...h,...f],await r.flow.asyncWhile((async({count:r,doBreak:c})=>{if(r>=99)return c();let d="",h="",m=!1,g=f.filter((e=>"user"===e.role)).slice(-1)[0]?.content||"";try{await this.hook.notify("talkBefore",{id:t,data:e,messages:f,metadata:p,lastUserMessage:g});const y=this.params.request(f,{id:t,count:r,schema:i,onCancel:u,metadata:p,isRetry:m});if(n)a&&a();else try{o=!0,d=await y,h=d}finally{o=!1}!1===n&&(await this.hook.notify("talkAfter",{id:t,data:e,response:d,messages:f,parseText:h,metadata:p,lastUserMessage:g,parseFail:e=>{throw new s.ParserError(e,[])},changeParseText:e=>{h=e}}),l=(await this.translator.parse(h)).output,await this.hook.notify("succeeded",{id:t,output:l,metadata:p})),await this.hook.notify("done",{id:t,metadata:p}),c()}catch(e){if(!(e instanceof s.ParserError))throw await this.hook.notify("done",{id:t,metadata:p}),e;if(await this.hook.notify("parseFailed",{id:t,error:e.error,count:r,response:d,messages:f,metadata:p,lastUserMessage:g,parserFails:e.parserFails,retry:()=>{m=!0},changeMessages:e=>{f=e}}),!1===m)throw await this.hook.notify("done",{id:t,metadata:p}),e}})),l};return{id:t,request:(async()=>{try{return await p()}finally{l()}})()}}async request(e){const{request:t}=this.requestWithId(e);return await t}}},306:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TextParser=void 0;const r=n(a(865));class o{params;static JsonMessage(){return new o({name:"JsonMessage",handler:async e=>{try{return JSON.parse(e)}catch(t){const a=/{(?:[^{}]|(?:{[^{}]*}))*}/,n=e.match(a)?.[0]||"";return r.default.parse(n)}}})}constructor(e){this.params=e}get name(){return this.params.name}async read(e){return await this.params.handler(e)}}t.TextParser=o},198:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBrokerPlugin=void 0;const n=a(572);t.ChatBrokerPlugin=class{_event=new n.Event;_params;constructor(e){this._params=e}use(e){return{instance:this,params:e,send:e=>{this._event.emit("receive",e)},receive:e=>{this._event.on("receive",e)},__receiveData:null}}}},235:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Translator=void 0;const n=a(357),r=a(165);t.Translator=class{params;constructor(e){this.params=e}get __schemeType(){return null}get __outputType(){return null}async compile(e,t){const a=this.params.input?(0,n.validate)(e,this.params.input):e,r=this.params.question?await this.params.question(a,t):"";return{scheme:a,prompt:Array.isArray(r)?r.join("\n"):r}}getValidate(){return{input:this.params.input,output:this.params.output}}changeOutputSchema(e){this.params.output=e}async parse(e){let t,a="",o=[];for(let n of this.params.parsers)try{t=await n.read(e),a=n.name}catch(e){t=void 0,o.push({name:n.name,error:e})}try{return{output:(0,n.validate)(t,this.params.output),parserName:a,parserFails:o}}catch(e){throw new r.ParserError(e,o)}}}},697:function(e,t,a){var n=this&&this.__createBinding||(Object.create?function(e,t,a,n){void 0===n&&(n=a);var r=Object.getOwnPropertyDescriptor(t,a);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,n,r)}:function(e,t,a,n){void 0===n&&(n=a),e[n]=t[a]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&n(t,e,a);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CtoD=void 0;const s=a(177),i=o(a(622));t.CtoD=class{params;constructor(e){this.params=e}createBrokerBuilder(e){return{create:t=>new s.ChatBroker({output:()=>({}),install:a=>{e?.install?.(a),a.attach("start",(async({id:e,plugins:a,data:n,metadata:r,changeMessages:o,changeOutputSchema:s})=>{const l=await t({id:e,data:n,plugins:a,yup:i,setMessages:e=>{o(e.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.join("\n"):e.content}))))},metadata:r});s((()=>l))}))},plugins:this.params.plugins?.(),request:this.params.request})}}}},665:function(e,t,a){var n=this&&this.__createBinding||(Object.create?function(e,t,a,n){void 0===n&&(n=a);var r=Object.getOwnPropertyDescriptor(t,a);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,n,r)}:function(e,t,a,n){void 0===n&&(n=a),e[n]=t[a]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&n(t,e,a);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ctod=t.Translator=t.ChatBrokerPlugin=t.ChatBroker=t.TextParser=t.Llama3Cpp=t.OpenAI=t.defineYupSchema=t.validateToJsonSchema=t.CtoD=t.templates=t.plugins=void 0,t.plugins=o(a(374)),t.templates=o(a(854));var s=a(697);Object.defineProperty(t,"CtoD",{enumerable:!0,get:function(){return s.CtoD}});var i=a(357);Object.defineProperty(t,"validateToJsonSchema",{enumerable:!0,get:function(){return i.validateToJsonSchema}}),Object.defineProperty(t,"defineYupSchema",{enumerable:!0,get:function(){return i.defineYupSchema}});var l=a(984);Object.defineProperty(t,"OpenAI",{enumerable:!0,get:function(){return l.OpenAI}});var c=a(887);Object.defineProperty(t,"Llama3Cpp",{enumerable:!0,get:function(){return c.Llama3Cpp}});var u=a(306);Object.defineProperty(t,"TextParser",{enumerable:!0,get:function(){return u.TextParser}});var p=a(177);Object.defineProperty(t,"ChatBroker",{enumerable:!0,get:function(){return p.ChatBroker}});var d=a(198);Object.defineProperty(t,"ChatBrokerPlugin",{enumerable:!0,get:function(){return d.ChatBrokerPlugin}});var h=a(235);Object.defineProperty(t,"Translator",{enumerable:!0,get:function(){return h.Translator}});const f=o(a(374)),m=o(a(854)),g=a(984),y=a(697),_=a(887),v=a(235),b=a(306),w=a(177),C=a(198),O=a(357);t.ctod={CtoD:y.CtoD,OpenAI:g.OpenAI,Llama3Cpp:_.Llama3Cpp,plugins:f,templates:m,ChatBroker:w.ChatBroker,Translator:v.Translator,TextParser:b.TextParser,ChatBrokerPlugin:C.ChatBrokerPlugin,defineYupSchema:O.defineYupSchema,validateToJsonSchema:O.validateToJsonSchema},e.exports=t.ctod,e.exports.ctod=t.ctod,t.default=t.ctod},374:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RolePlugin=t.LimiterPluginGlobState=t.LimiterPlugin=t.RetryPlugin=t.PrintLogPlugin=void 0;const r=n(a(92)),o=n(a(354)),s=n(a(270)),i=n(a(724));t.PrintLogPlugin=o.default,t.RetryPlugin=r.default,t.LimiterPlugin=s.default.plugin,t.LimiterPluginGlobState=s.default,t.RolePlugin=i.default},270:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198),r=a(572),o={limit:3,interval:6e4},s={event:new r.Event,schedule:null,waitTimes:[],waitQueue:[]};t.default={event:s.event,config:o,closeSchedule:()=>{s.schedule&&(s.schedule.close(),s.schedule=null)},plugin:new n.ChatBrokerPlugin({name:"limiter",params:()=>({}),receiveData:()=>({}),onInstall({attach:e}){null==s.schedule&&(s.schedule=new r.Schedule,s.schedule.add("calc queue",1e3,(async()=>{const e=Date.now();if(s.waitTimes=s.waitTimes.filter((t=>e-t<o.interval)),s.waitTimes.length!==o.limit){let e=s.waitQueue.shift();e&&(s.waitTimes.push(Date.now()),s.event.emit("run",{id:e}))}else s.waitTimes[0]&&s.event.emit("waitTimeChange",{waitTime:Math.floor(60-(e-s.waitTimes[0])/1e3)})})),s.schedule.play()),e("talkBefore",(async()=>{const e=r.flow.createUuid();return s.waitQueue.push(e),new Promise((t=>{s.event.on("run",(({id:a},{off:n})=>{a===e&&(n(),t())}))}))}))}})}},354:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198);t.default=new n.ChatBrokerPlugin({name:"print-log",params:e=>({detail:e.boolean().default(!1)}),receiveData:()=>({}),onInstall({params:e,log:t,attach:a}){a("talkBefore",(async({lastUserMessage:a,messages:n})=>{t.print("Send:",{color:"green"}),e.detail?t.print("\n"+JSON.stringify(n,null,4)):t.print("\n"+a)})),a("talkAfter",(async({parseText:e})=>{t.print("Receive:",{color:"cyan"}),t.print("\n"+e)})),a("succeeded",(async({output:e})=>{t.print("Output:",{color:"yellow"});try{t.print("\n"+JSON.stringify(e,null,4))}catch(a){t.print("\n"+e)}}))}})},92:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198);t.default=new n.ChatBrokerPlugin({name:"retry",params:e=>({retry:e.number().required().default(1),printWarn:e.boolean().required().default(!0)}),receiveData:()=>({}),onInstall({log:e,attach:t,params:a}){t("parseFailed",(async({count:t,retry:n,messages:r,changeMessages:o})=>{t<=a.retry&&(a.printWarn&&e.print(`Is Failed, Retry ${t} times.`),o(r),n())}))}})},724:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198);t.default=new n.ChatBrokerPlugin({name:"role",params:e=>({role:e.string().required()}),receiveData:()=>({}),onInstall({attach:e,params:t}){e("start",(async({messages:e,changeMessages:a})=>{a([{role:"user",content:`你現在是${t.role}。`},{role:"assistant",content:`沒問題,我現在是${t.role},有什麼可以幫你的嗎?`},...e])}))}})},129:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Llama3CppCompletion=void 0;const n=a(572),r=a(4);class o{core;streamAbortControllers=[];constructor(e){this.core=e}createAbortController(){const e=new AbortController,t=n.flow.createUuid();return this.streamAbortControllers.push({id:t,controller:e}),{signal:e.signal,controllerId:t}}removeAbortController(e){this.streamAbortControllers=this.streamAbortControllers.filter((t=>t.id!==e))}async stream(e){const{signal:t,controllerId:a}=this.createAbortController(),n=()=>{this.removeAbortController(a),e.onEnd()};fetch(`${this.core.config.baseUrl}/${e.path}`,{method:"POST",body:JSON.stringify(e.data),signal:t,headers:{"Content-Type":"application/json",...this.core.config.headers}}).then((async t=>{if(t.body){let a=t.body.getReader(),r=!1,o="";for(;!r;){const{value:t,done:n}=await a.read();if(t){o+=new TextDecoder("utf-8").decode(t);const a=o.split("\n\n");o=a.pop()||"",a.forEach((t=>{if(t.includes("[DONE]")&&(r=!0),t.startsWith("data:"))try{const a=JSON.parse(t.replace("data: ",""));e.onMessage(a)}catch(t){e.onWarn(t)}}))}n&&(r=!0)}n()}else e.onError(new Error("Body not found."))})).catch((t=>{t instanceof Error&&t.message.includes("The user aborted a request")?n():e.onError(t)}))}async fetch(e){const{signal:t,controllerId:a}=this.createAbortController();try{return{data:(await this.core.core._axios.post(`${this.core.config.baseUrl}/${e.path}`,e.data,{signal:t,headers:{"Content-Type":"application/json",...this.core.config.headers}})).data}}finally{this.removeAbortController(a)}}cancel(){this.streamAbortControllers.forEach((e=>e.controller.abort())),this.streamAbortControllers=[]}export(){return{cancel:this.cancel.bind(this)}}}t.Llama3CppCompletion=class{core;config={baseUrl:"",headers:{},autoConvertTraditionalChinese:!0};constructor(e){this.core=e}setConfig(e){this.config={...this.config,...e}}completion(e){const t=[];for(let{role:a,content:n}of e.messages)"system"===a&&t.push(`<|start_header_id|>system<|end_header_id|>\n\n${n}\n\n`),"user"===a&&t.push(`<|start_header_id|>user<|end_header_id|>\n\n${n?.replaceAll("\n","\\n")??""}`),"assistant"===a&&t.push("<|start_header_id|>assistant<|end_header_id|>\n\n"+n);const a=e.messages.at(-1)||"",n=new o(this);return{...n.export(),run:async()=>{const o=await n.fetch({path:"completion",data:{...e.options||{},prompt:this.config.autoConvertTraditionalChinese?(0,r.sify)(t.join("\n")):t.join("\n")}}),s=this.config.autoConvertTraditionalChinese?(0,r.tify)(o.data.content):o.data.content;return{message:s,fullMessage:`${a}${s}`}}}}completionStream(e){const t=[];for(let{role:a,content:n}of e.messages)"system"===a&&t.push(`<|start_header_id|>system<|end_header_id|>\n\n${n}\n\n`),"user"===a&&t.push(`<|start_header_id|>user<|end_header_id|>\n\n${n?.replaceAll("\n","\\n")??""}`),"assistant"===a&&t.push("<|start_header_id|>assistant<|end_header_id|>\n\n"+n);const a=new o(this);return a.stream({path:"completion",onEnd:e.onEnd||(()=>null),onMessage:t=>{e.onMessage({message:this.config.autoConvertTraditionalChinese?(0,r.tify)(t.content):t.content})},onWarn:e.onWarn||(()=>null),onError:e.onError||(()=>null),data:{...e.options||{},prompt:this.config.autoConvertTraditionalChinese?(0,r.sify)(t.join("\n")):t.join("\n"),stream:!0}}),a.export()}talk(e){const t=new o(this);return{...t.export(),run:async()=>{const a=(await t.fetch({path:"v1/chat/completions",data:{...e.options||{},response_format:e.response_format,messages:e.messages.map((e=>({role:e.role,content:this.config.autoConvertTraditionalChinese?(0,r.sify)(e.content):e.content})))}})).data.choices[0].message.content||"";return{message:this.config.autoConvertTraditionalChinese?(0,r.tify)(a):a}}}}talkStream(e){const t=new o(this);return t.stream({path:"v1/chat/completions",onEnd:e.onEnd||(()=>null),onMessage:t=>{let a=t.choices[0].delta.content;a&&e.onMessage({message:this.config.autoConvertTraditionalChinese?(0,r.tify)(a):a})},onWarn:e.onWarn||(()=>null),onError:e.onError||(()=>null),data:{...e.options||{},stream:!0,messages:e.messages.map((e=>({role:e.role,content:this.config.autoConvertTraditionalChinese?(0,r.sify)(e.content):e.content})))}}),t.export()}}},887:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Llama3Cpp=void 0;const r=n(a(938)),o=a(4),s=a(357),i=a(129);class l{_axios=r.default.create();static createChatRequest(e){return async(t,{schema:a,onCancel:n})=>{const r=(new l).createCompletion(),i="function"==typeof e.config?await e.config():e.config;r.setConfig(i);let c=(0,s.validateToJsonSchema)(a.output);r.config.autoConvertTraditionalChinese&&(c=JSON.parse((0,o.sify)(JSON.stringify(c))));const{run:u,cancel:p}=r.talk({options:e.talkOptions,messages:t,response_format:{type:"json_object",schema:c}});n(p);const{message:d}=await u();return d}}setAxios(e){this._axios=e}createCompletion(){return new i.Llama3CppCompletion(this)}}t.Llama3Cpp=l},228:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIChat=void 0;const n=a(572);t.OpenAIChat=class{openai;config={n:1,model:"gpt-4o",temperature:1,maxTokens:void 0,forceJsonFormat:!0};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async moderations(e){const t=await this.openai._axios.post("https://api.openai.com/v1/moderations",{input:e},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}});return{isSafe:!1===t.data.results?.[0]?.flagged,result:t.data}}async talk(e=[],t){const a=n.json.jpjs(e),r=["gpt-4-turbo-preview","gpt-4-turbo","gpt-4o","gpt-4o-mini","gpt-3.5-turbo-1106"].includes(this.config.model);let o;r&&this.config.forceJsonFormat&&(o={type:"json_object"}),r&&this.config.forceJsonFormat&&t?.jsonSchema&&(o={type:"json_schema",json_schema:t.jsonSchema});const s=await this.openai._axios.post("https://api.openai.com/v1/chat/completions",{model:this.config.model,n:this.config.n,messages:a,response_format:o,temperature:this.config.temperature},{signal:t?.abortController?.signal,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}}),i=s.data.choices||[],l=i[0]?.message||{role:"assistant",content:""};return a.push(l),{id:s?.data.id,text:l.content,newMessages:a,isDone:"stop"===i[0]?.finish_reason,apiReseponse:s.data}}talkStream(e){const t=new AbortController;return fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`},body:JSON.stringify({model:this.config.model,stream:!0,messages:e.messages}),signal:t.signal}).then((async t=>{const a=t.body?.pipeThrough(new TextDecoderStream).getReader();if(!a)throw new Error("Can not get reader");for(;;){const{value:t,done:n}=await a.read();if(n)break;const r=t.split("\n");for(let t of r)if(0!==t.length&&!t.startsWith(":")){if("data: [DONE]"===t){e.onEnd();break}try{const a=JSON.parse(t.substring(6)).choices[0].delta.content;e.onMessage(a)}catch(t){e.onWarn(t)}}}})).catch((t=>{"AbortError"===t.name?e.onEnd():e.onError(t)})),{cancel:()=>t.abort()}}async keepTalk(e,t=[]){const a=await this.talk([...t,{role:"user",content:Array.isArray(e)?e.join("\n"):e}]);return{result:a,nextTalk:e=>this.keepTalk(e,a.newMessages)}}}},11:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIImagesGeneration=void 0,t.OpenAIImagesGeneration=class{openai;config={model:"dall-e-2",size:"1024x1024"};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async create(e){return(await this.openai._axios.post("https://api.openai.com/v1/images/generations",{prompt:e,n:1,size:this.config.size,model:this.config.model,response_format:"b64_json"},{timeout:3e5,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}})).data}}},984:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAI=void 0;const r=n(a(938)),o=a(38),s=a(228),i=a(11),l=a(357);class c{_axios=r.default.create();_apiKey="";static createChatRequest(e,t={},a){return async(n,{onCancel:r})=>{const o=new c("string"==typeof e?e:await e()),s=o.createChat(),i=new AbortController;a&&a.axios&&o.setAxios(a.axios),s.setConfig("function"==typeof t?await t():t),r((()=>i.abort()));const{text:l}=await s.talk(n,{abortController:i});return l}}static createChatRequestWithJsonSchema(e){return async(t,{schema:a,onCancel:n})=>{const r=new c("string"==typeof e.apiKey?e.apiKey:await e.apiKey()),o=r.createChat(),s=new AbortController;e.config&&o.setConfig("function"==typeof e.config?await e.config():e.config),e.axios&&r.setAxios(e.axios),n((()=>s.abort()));const i=(0,l.validateToJsonSchema)(a.output),{text:u}=await o.talk(t,{abortController:s,jsonSchema:{name:"data",strict:!0,schema:i}});return u}}constructor(e=""){this._apiKey=e}setAxios(e){this._axios=e}setConfiguration(e){this._apiKey=e}createChat(){return new s.OpenAIChat(this)}createVision(){return new o.OpenAIVision(this)}createImagesGeneration(){return new i.OpenAIImagesGeneration(this)}}t.OpenAI=c},38:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIVision=void 0,t.OpenAIVision=class{openai;config={model:"gpt-4-vision-preview",maxTokens:void 0,temperature:1};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async view(e){const t=await this.openai._axios.post("https://api.openai.com/v1/chat/completions",{model:this.config.model,n:1,messages:e,max_tokens:this.config.maxTokens,temperature:this.config.temperature},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}}),a=t.data.choices||[],n=a[0]?.message||{role:"assistant",content:""};return{id:t?.data.id,text:n.content,apiReseponse:t.data}}}},854:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.requireJsonResponseWithJsonSchema=t.requireJsonResponseWithHandlebars=t.requireJsonResponse=void 0;const r=n(a(156)),o=a(572);t.requireJsonResponse=(e,t)=>[...Array.isArray(e)?e:[e],"Please respond using the following JSON format and minify the JSON without including any explanation: ","{",Object.entries(t).map((([e,t])=>[`/* ${t.desc} */`,`"${e}": ${JSON.stringify(t.example)}`].join("\n"))).join(",\n"),"}"].join("\n"),t.requireJsonResponseWithHandlebars=(e,a,n)=>{const s=r.default.create();return s.registerHelper("DATA",(function(e){return JSON.stringify(e)})),s.registerHelper("ENV",(function(e){return this.__envs&&e?this.__envs[e]:""})),s.registerHelper("INPUT",(function(){return JSON.stringify(o.record.omit(this,["__envs"]))})),s.registerHelper("JOIN",(function(e){return Array.isArray(e)?e.join():JSON.stringify(e)})),s.compile((0,t.requireJsonResponse)(a,n))(e)},t.requireJsonResponseWithJsonSchema=(e,t)=>[...Array.isArray(e)?e:[e],"Please provide JSON data according to the following JSON Schema format:",JSON.stringify(t)].join("\n")},165:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParserError=void 0,t.ParserError=class{isParserError=!0;parserFails=[];error;constructor(e,t){this.error=e,this.parserFails=t}}},357:function(e,t,a){var n=this&&this.__createBinding||(Object.create?function(e,t,a,n){void 0===n&&(n=a);var r=Object.getOwnPropertyDescriptor(t,a);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,n,r)}:function(e,t,a,n){void 0===n&&(n=a),e[n]=t[a]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&n(t,e,a);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.validateToJsonSchema=t.defineYupSchema=t.validate=t.definedValidateSchema=void 0;const s=o(a(622)),i=a(250);t.definedValidateSchema=function(e){return e},t.validate=function(e,t){return s.object(t(s)).required().validateSync(e||{})},t.defineYupSchema=e=>e(s),t.validateToJsonSchema=e=>{const t=e=>{if(e.default&&delete e.default,e.properties)for(let a in e.properties)e.properties[a].default&&delete e.properties[a].default,t(e.properties[a]);e.items&&t(e.items)},a=e=>{if("object"===e.type){e.additionalProperties=!1;for(const t in e.properties)a(e.properties[t])}else"array"===e.type&&a(e.items)},n=(0,i.convertSchema)(s.object(e(s)));return t(n),a(n),n}},250:e=>{e.exports=require("@sodaru/yup-to-json-schema")},938:e=>{e.exports=require("axios")},4:e=>{e.exports=require("chinese-conv")},156:e=>{e.exports=require("handlebars")},865:e=>{e.exports=require("json5")},572:e=>{e.exports=require("power-helper")},622:e=>{e.exports=require("yup")}},t={};return function a(n){var r=t[n];if(void 0!==r)return r.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,a),o.exports}(665)})()));
1
+ !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.ctod=t():e.ctod=t()}(this||("undefined"!=typeof window?window:global),(()=>(()=>{"use strict";var e={177:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBroker=void 0;const n=a(306),r=a(572),o=a(235),s=a(165);t.ChatBroker=class{__hookType;log;hook=new r.Hook;params;plugins={};installed=!1;translator;event=new r.Event;constructor(e){this.log=new r.Log(e.name??"no name"),this.params=e,this.translator=new o.Translator({...e,parsers:[n.TextParser.JsonMessage()]})}_install(){if(!1===this.installed){this.installed=!0;const e={log:this.log,attach:this.hook.attach.bind(this.hook),attachAfter:this.hook.attachAfter.bind(this.hook),translator:this.translator};if(this.params.plugins){this.plugins="function"==typeof this.params.plugins?this.params.plugins():this.params.plugins;for(let t in this.plugins)this.plugins[t].instance._params.onInstall({...e,params:this.plugins[t].params,receive:this.plugins[t].receive})}this.params.install?.(e)}}async cancel(e){e?this.event.emit("cancel",{requestId:e}):this.event.emit("cancelAll",{})}requestWithId(e){this._install();let t=r.flow.createUuid(),a=null,n=!1,o=!1,i=[this.event.on("cancel",(({requestId:e})=>{e===t&&c()})),this.event.on("cancelAll",(()=>{c()}))],l=()=>i.forEach((e=>e.off())),c=()=>{!1===n&&(o&&a&&a(),n=!0,l())},u=e=>{a=e},p=async()=>{let i=this.translator.getValidate(),l=null,c={},p=new Map,d=await this.translator.compile(e,{schema:i}),h=[],f=[];d.prompt&&f.push({role:"user",content:d.prompt});for(let e in this.plugins)c[e]={send:a=>this.plugins[e].send({id:t,data:a})};return await this.hook.notify("start",{id:t,data:e,schema:i,plugins:c,messages:f,metadata:p,setPreMessages:e=>{h=e.map((e=>({...e,content:Array.isArray(e.content)?e.content.join("\n"):e.content})))},changeMessages:e=>{f=e},changeOutputSchema:e=>{this.translator.changeOutputSchema(e),i=this.translator.getValidate()}}),f=[...h,...f],await r.flow.asyncWhile((async({count:r,doBreak:c})=>{if(r>=99)return c();let d="",h="",m=!1,g=f.filter((e=>"user"===e.role)).slice(-1)[0]?.content||"";try{await this.hook.notify("talkBefore",{id:t,data:e,messages:f,metadata:p,lastUserMessage:g});const y=this.params.request(f,{id:t,count:r,schema:i,onCancel:u,metadata:p,isRetry:m});if(n)a&&a();else try{o=!0,d=await y,h=d}finally{o=!1}!1===n&&(await this.hook.notify("talkAfter",{id:t,data:e,response:d,messages:f,parseText:h,metadata:p,lastUserMessage:g,parseFail:e=>{throw new s.ParserError(e,[])},changeParseText:e=>{h=e}}),l=(await this.translator.parse(h)).output,await this.hook.notify("succeeded",{id:t,output:l,metadata:p})),await this.hook.notify("done",{id:t,metadata:p}),c()}catch(e){if(!(e instanceof s.ParserError))throw await this.hook.notify("done",{id:t,metadata:p}),e;if(await this.hook.notify("parseFailed",{id:t,error:e.error,count:r,response:d,messages:f,metadata:p,lastUserMessage:g,parserFails:e.parserFails,retry:()=>{m=!0},changeMessages:e=>{f=e}}),!1===m)throw await this.hook.notify("done",{id:t,metadata:p}),e}})),l};return{id:t,request:(async()=>{try{return await p()}finally{l()}})()}}async request(e){const{request:t}=this.requestWithId(e);return await t}}},306:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TextParser=void 0;const r=n(a(865));class o{params;static JsonMessage(){return new o({name:"JsonMessage",handler:async e=>{try{return JSON.parse(e)}catch(t){const a=/{(?:[^{}]|(?:{[^{}]*}))*}/,n=e.match(a)?.[0]||"";return r.default.parse(n)}}})}constructor(e){this.params=e}get name(){return this.params.name}async read(e){return await this.params.handler(e)}}t.TextParser=o},198:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ChatBrokerPlugin=void 0;const n=a(572);t.ChatBrokerPlugin=class{_event=new n.Event;_params;constructor(e){this._params=e}use(e){return{instance:this,params:e,send:e=>{this._event.emit("receive",e)},receive:e=>{this._event.on("receive",e)},__receiveData:null}}}},235:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Translator=void 0;const n=a(357),r=a(165);t.Translator=class{params;constructor(e){this.params=e}get __schemeType(){return null}get __outputType(){return null}async compile(e,t){const a=this.params.input?(0,n.validate)(e,this.params.input):e,r=this.params.question?await this.params.question(a,t):"";return{scheme:a,prompt:Array.isArray(r)?r.join("\n"):r}}getValidate(){return{input:this.params.input,output:this.params.output}}changeOutputSchema(e){this.params.output=e}async parse(e){let t,a="",o=[];for(let n of this.params.parsers)try{t=await n.read(e),a=n.name}catch(e){t=void 0,o.push({name:n.name,error:e})}try{return{output:(0,n.validate)(t,this.params.output),parserName:a,parserFails:o}}catch(e){throw new r.ParserError(e,o)}}}},697:function(e,t,a){var n=this&&this.__createBinding||(Object.create?function(e,t,a,n){void 0===n&&(n=a);var r=Object.getOwnPropertyDescriptor(t,a);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,n,r)}:function(e,t,a,n){void 0===n&&(n=a),e[n]=t[a]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&n(t,e,a);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.CtoD=void 0;const s=a(177),i=o(a(622));t.CtoD=class{params;constructor(e){this.params=e}createBrokerBuilder(e){return{create:t=>new s.ChatBroker({output:()=>({}),install:a=>{e?.install?.(a),a.attach("start",(async({id:e,plugins:a,data:n,metadata:r,changeMessages:o,changeOutputSchema:s})=>{const l=await t({id:e,data:n,plugins:a,yup:i,setMessages:e=>{o(e.map((e=>({role:e.role,content:Array.isArray(e.content)?e.content.join("\n"):e.content}))))},metadata:r});s((()=>l))}))},plugins:this.params.plugins?()=>this.params.plugins():void 0,request:this.params.request})}}}},665:function(e,t,a){var n=this&&this.__createBinding||(Object.create?function(e,t,a,n){void 0===n&&(n=a);var r=Object.getOwnPropertyDescriptor(t,a);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,n,r)}:function(e,t,a,n){void 0===n&&(n=a),e[n]=t[a]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&n(t,e,a);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.ctod=t.Translator=t.ChatBrokerPlugin=t.ChatBroker=t.TextParser=t.Llama3Cpp=t.OpenAI=t.defineYupSchema=t.validateToJsonSchema=t.CtoD=t.templates=t.plugins=void 0,t.plugins=o(a(374)),t.templates=o(a(854));var s=a(697);Object.defineProperty(t,"CtoD",{enumerable:!0,get:function(){return s.CtoD}});var i=a(357);Object.defineProperty(t,"validateToJsonSchema",{enumerable:!0,get:function(){return i.validateToJsonSchema}}),Object.defineProperty(t,"defineYupSchema",{enumerable:!0,get:function(){return i.defineYupSchema}});var l=a(984);Object.defineProperty(t,"OpenAI",{enumerable:!0,get:function(){return l.OpenAI}});var c=a(887);Object.defineProperty(t,"Llama3Cpp",{enumerable:!0,get:function(){return c.Llama3Cpp}});var u=a(306);Object.defineProperty(t,"TextParser",{enumerable:!0,get:function(){return u.TextParser}});var p=a(177);Object.defineProperty(t,"ChatBroker",{enumerable:!0,get:function(){return p.ChatBroker}});var d=a(198);Object.defineProperty(t,"ChatBrokerPlugin",{enumerable:!0,get:function(){return d.ChatBrokerPlugin}});var h=a(235);Object.defineProperty(t,"Translator",{enumerable:!0,get:function(){return h.Translator}});const f=o(a(374)),m=o(a(854)),g=a(984),y=a(697),_=a(887),v=a(235),b=a(306),w=a(177),C=a(198),O=a(357);t.ctod={CtoD:y.CtoD,OpenAI:g.OpenAI,Llama3Cpp:_.Llama3Cpp,plugins:f,templates:m,ChatBroker:w.ChatBroker,Translator:v.Translator,TextParser:b.TextParser,ChatBrokerPlugin:C.ChatBrokerPlugin,defineYupSchema:O.defineYupSchema,validateToJsonSchema:O.validateToJsonSchema},e.exports=t.ctod,e.exports.ctod=t.ctod,t.default=t.ctod},374:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RolePlugin=t.LimiterPluginGlobState=t.LimiterPlugin=t.RetryPlugin=t.PrintLogPlugin=void 0;const r=n(a(92)),o=n(a(354)),s=n(a(270)),i=n(a(724));t.PrintLogPlugin=o.default,t.RetryPlugin=r.default,t.LimiterPlugin=s.default.plugin,t.LimiterPluginGlobState=s.default,t.RolePlugin=i.default},270:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198),r=a(572),o={limit:3,interval:6e4},s={event:new r.Event,schedule:null,waitTimes:[],waitQueue:[]};t.default={event:s.event,config:o,closeSchedule:()=>{s.schedule&&(s.schedule.close(),s.schedule=null)},plugin:new n.ChatBrokerPlugin({name:"limiter",params:()=>({}),receiveData:()=>({}),onInstall({attach:e}){null==s.schedule&&(s.schedule=new r.Schedule,s.schedule.add("calc queue",1e3,(async()=>{const e=Date.now();if(s.waitTimes=s.waitTimes.filter((t=>e-t<o.interval)),s.waitTimes.length!==o.limit){let e=s.waitQueue.shift();e&&(s.waitTimes.push(Date.now()),s.event.emit("run",{id:e}))}else s.waitTimes[0]&&s.event.emit("waitTimeChange",{waitTime:Math.floor(60-(e-s.waitTimes[0])/1e3)})})),s.schedule.play()),e("talkBefore",(async()=>{const e=r.flow.createUuid();return s.waitQueue.push(e),new Promise((t=>{s.event.on("run",(({id:a},{off:n})=>{a===e&&(n(),t())}))}))}))}})}},354:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198);t.default=new n.ChatBrokerPlugin({name:"print-log",params:e=>({detail:e.boolean().default(!1)}),receiveData:()=>({}),onInstall({params:e,log:t,attach:a}){a("talkBefore",(async({lastUserMessage:a,messages:n})=>{t.print("Send:",{color:"green"}),e.detail?t.print("\n"+JSON.stringify(n,null,4)):t.print("\n"+a)})),a("talkAfter",(async({parseText:e})=>{t.print("Receive:",{color:"cyan"}),t.print("\n"+e)})),a("succeeded",(async({output:e})=>{t.print("Output:",{color:"yellow"});try{t.print("\n"+JSON.stringify(e,null,4))}catch(a){t.print("\n"+e)}}))}})},92:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198);t.default=new n.ChatBrokerPlugin({name:"retry",params:e=>({retry:e.number().required().default(1),printWarn:e.boolean().required().default(!0)}),receiveData:()=>({}),onInstall({log:e,attach:t,params:a}){t("parseFailed",(async({count:t,retry:n,messages:r,changeMessages:o})=>{t<=a.retry&&(a.printWarn&&e.print(`Is Failed, Retry ${t} times.`),o(r),n())}))}})},724:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0});const n=a(198);t.default=new n.ChatBrokerPlugin({name:"role",params:e=>({role:e.string().required()}),receiveData:()=>({}),onInstall({attach:e,params:t}){e("start",(async({messages:e,changeMessages:a})=>{a([{role:"user",content:`你現在是${t.role}。`},{role:"assistant",content:`沒問題,我現在是${t.role},有什麼可以幫你的嗎?`},...e])}))}})},129:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.Llama3CppCompletion=void 0;const n=a(572),r=a(4);class o{core;streamAbortControllers=[];constructor(e){this.core=e}createAbortController(){const e=new AbortController,t=n.flow.createUuid();return this.streamAbortControllers.push({id:t,controller:e}),{signal:e.signal,controllerId:t}}removeAbortController(e){this.streamAbortControllers=this.streamAbortControllers.filter((t=>t.id!==e))}async stream(e){const{signal:t,controllerId:a}=this.createAbortController(),n=()=>{this.removeAbortController(a),e.onEnd()};fetch(`${this.core.config.baseUrl}/${e.path}`,{method:"POST",body:JSON.stringify(e.data),signal:t,headers:{"Content-Type":"application/json",...this.core.config.headers}}).then((async t=>{if(t.body){let a=t.body.getReader(),r=!1,o="";for(;!r;){const{value:t,done:n}=await a.read();if(t){o+=new TextDecoder("utf-8").decode(t);const a=o.split("\n\n");o=a.pop()||"",a.forEach((t=>{if(t.includes("[DONE]")&&(r=!0),t.startsWith("data:"))try{const a=JSON.parse(t.replace("data: ",""));e.onMessage(a)}catch(t){e.onWarn(t)}}))}n&&(r=!0)}n()}else e.onError(new Error("Body not found."))})).catch((t=>{t instanceof Error&&t.message.includes("The user aborted a request")?n():e.onError(t)}))}async fetch(e){const{signal:t,controllerId:a}=this.createAbortController();try{return{data:(await this.core.core._axios.post(`${this.core.config.baseUrl}/${e.path}`,e.data,{signal:t,headers:{"Content-Type":"application/json",...this.core.config.headers}})).data}}finally{this.removeAbortController(a)}}cancel(){this.streamAbortControllers.forEach((e=>e.controller.abort())),this.streamAbortControllers=[]}export(){return{cancel:this.cancel.bind(this)}}}t.Llama3CppCompletion=class{core;config={baseUrl:"",headers:{},autoConvertTraditionalChinese:!0};constructor(e){this.core=e}setConfig(e){this.config={...this.config,...e}}completion(e){const t=[];for(let{role:a,content:n}of e.messages)"system"===a&&t.push(`<|start_header_id|>system<|end_header_id|>\n\n${n}\n\n`),"user"===a&&t.push(`<|start_header_id|>user<|end_header_id|>\n\n${n?.replaceAll("\n","\\n")??""}`),"assistant"===a&&t.push("<|start_header_id|>assistant<|end_header_id|>\n\n"+n);const a=e.messages.at(-1)||"",n=new o(this);return{...n.export(),run:async()=>{const o=await n.fetch({path:"completion",data:{...e.options||{},prompt:this.config.autoConvertTraditionalChinese?(0,r.sify)(t.join("\n")):t.join("\n")}}),s=this.config.autoConvertTraditionalChinese?(0,r.tify)(o.data.content):o.data.content;return{message:s,fullMessage:`${a}${s}`}}}}completionStream(e){const t=[];for(let{role:a,content:n}of e.messages)"system"===a&&t.push(`<|start_header_id|>system<|end_header_id|>\n\n${n}\n\n`),"user"===a&&t.push(`<|start_header_id|>user<|end_header_id|>\n\n${n?.replaceAll("\n","\\n")??""}`),"assistant"===a&&t.push("<|start_header_id|>assistant<|end_header_id|>\n\n"+n);const a=new o(this);return a.stream({path:"completion",onEnd:e.onEnd||(()=>null),onMessage:t=>{e.onMessage({message:this.config.autoConvertTraditionalChinese?(0,r.tify)(t.content):t.content})},onWarn:e.onWarn||(()=>null),onError:e.onError||(()=>null),data:{...e.options||{},prompt:this.config.autoConvertTraditionalChinese?(0,r.sify)(t.join("\n")):t.join("\n"),stream:!0}}),a.export()}talk(e){const t=new o(this);return{...t.export(),run:async()=>{const a=(await t.fetch({path:"v1/chat/completions",data:{...e.options||{},response_format:e.response_format,messages:e.messages.map((e=>({role:e.role,content:this.config.autoConvertTraditionalChinese?(0,r.sify)(e.content):e.content})))}})).data.choices[0].message.content||"";return{message:this.config.autoConvertTraditionalChinese?(0,r.tify)(a):a}}}}talkStream(e){const t=new o(this);return t.stream({path:"v1/chat/completions",onEnd:e.onEnd||(()=>null),onMessage:t=>{let a=t.choices[0].delta.content;a&&e.onMessage({message:this.config.autoConvertTraditionalChinese?(0,r.tify)(a):a})},onWarn:e.onWarn||(()=>null),onError:e.onError||(()=>null),data:{...e.options||{},stream:!0,messages:e.messages.map((e=>({role:e.role,content:this.config.autoConvertTraditionalChinese?(0,r.sify)(e.content):e.content})))}}),t.export()}}},887:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.Llama3Cpp=void 0;const r=n(a(938)),o=a(4),s=a(357),i=a(129);class l{_axios=r.default.create();static createChatRequest(e){return async(t,{schema:a,onCancel:n})=>{const r=(new l).createCompletion(),i="function"==typeof e.config?await e.config():e.config;r.setConfig(i);let c=(0,s.validateToJsonSchema)(a.output);r.config.autoConvertTraditionalChinese&&(c=JSON.parse((0,o.sify)(JSON.stringify(c))));const{run:u,cancel:p}=r.talk({options:e.talkOptions,messages:t,response_format:{type:"json_object",schema:c}});n(p);const{message:d}=await u();return d}}setAxios(e){this._axios=e}createCompletion(){return new i.Llama3CppCompletion(this)}}t.Llama3Cpp=l},228:(e,t,a)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIChat=void 0;const n=a(572);t.OpenAIChat=class{openai;config={n:1,model:"gpt-4o",temperature:1,maxTokens:void 0,forceJsonFormat:!0};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async moderations(e){const t=await this.openai._axios.post("https://api.openai.com/v1/moderations",{input:e},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}});return{isSafe:!1===t.data.results?.[0]?.flagged,result:t.data}}async talk(e=[],t){const a=n.json.jpjs(e),r=["gpt-4-turbo-preview","gpt-4-turbo","gpt-4o","gpt-4o-mini","gpt-3.5-turbo-1106"].includes(this.config.model);let o;r&&this.config.forceJsonFormat&&(o={type:"json_object"}),r&&this.config.forceJsonFormat&&t?.jsonSchema&&(o={type:"json_schema",json_schema:t.jsonSchema});const s=await this.openai._axios.post("https://api.openai.com/v1/chat/completions",{model:this.config.model,n:this.config.n,messages:a,response_format:o,temperature:this.config.temperature},{signal:t?.abortController?.signal,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}}),i=s.data.choices||[],l=i[0]?.message||{role:"assistant",content:""};return a.push(l),{id:s?.data.id,text:l.content,newMessages:a,isDone:"stop"===i[0]?.finish_reason,apiReseponse:s.data}}talkStream(e){const t=new AbortController;return fetch("https://api.openai.com/v1/chat/completions",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`},body:JSON.stringify({model:this.config.model,stream:!0,messages:e.messages}),signal:t.signal}).then((async t=>{const a=t.body?.pipeThrough(new TextDecoderStream).getReader();if(!a)throw new Error("Can not get reader");for(;;){const{value:t,done:n}=await a.read();if(n)break;const r=t.split("\n");for(let t of r)if(0!==t.length&&!t.startsWith(":")){if("data: [DONE]"===t){e.onEnd();break}try{const a=JSON.parse(t.substring(6)).choices[0].delta.content;e.onMessage(a)}catch(t){e.onWarn(t)}}}})).catch((t=>{"AbortError"===t.name?e.onEnd():e.onError(t)})),{cancel:()=>t.abort()}}async keepTalk(e,t=[]){const a=await this.talk([...t,{role:"user",content:Array.isArray(e)?e.join("\n"):e}]);return{result:a,nextTalk:e=>this.keepTalk(e,a.newMessages)}}}},11:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIImagesGeneration=void 0,t.OpenAIImagesGeneration=class{openai;config={model:"dall-e-2",size:"1024x1024"};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async create(e){return(await this.openai._axios.post("https://api.openai.com/v1/images/generations",{prompt:e,n:1,size:this.config.size,model:this.config.model,response_format:"b64_json"},{timeout:3e5,headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}})).data}}},984:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAI=void 0;const r=n(a(938)),o=a(38),s=a(228),i=a(11),l=a(357);class c{_axios=r.default.create();_apiKey="";static createChatRequest(e,t={},a){return async(n,{onCancel:r})=>{const o=new c("string"==typeof e?e:await e()),s=o.createChat(),i=new AbortController;a&&a.axios&&o.setAxios(a.axios),s.setConfig("function"==typeof t?await t():t),r((()=>i.abort()));const{text:l}=await s.talk(n,{abortController:i});return l}}static createChatRequestWithJsonSchema(e){return async(t,{schema:a,onCancel:n})=>{const r=new c("string"==typeof e.apiKey?e.apiKey:await e.apiKey()),o=r.createChat(),s=new AbortController;e.config&&o.setConfig("function"==typeof e.config?await e.config():e.config),e.axios&&r.setAxios(e.axios),n((()=>s.abort()));const i=(0,l.validateToJsonSchema)(a.output),{text:u}=await o.talk(t,{abortController:s,jsonSchema:{name:"data",strict:!0,schema:i}});return u}}constructor(e=""){this._apiKey=e}setAxios(e){this._axios=e}setConfiguration(e){this._apiKey=e}createChat(){return new s.OpenAIChat(this)}createVision(){return new o.OpenAIVision(this)}createImagesGeneration(){return new i.OpenAIImagesGeneration(this)}}t.OpenAI=c},38:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.OpenAIVision=void 0,t.OpenAIVision=class{openai;config={model:"gpt-4-vision-preview",maxTokens:void 0,temperature:1};constructor(e){this.openai=e}setConfig(e){Object.assign(this.config,e)}async view(e){const t=await this.openai._axios.post("https://api.openai.com/v1/chat/completions",{model:this.config.model,n:1,messages:e,max_tokens:this.config.maxTokens,temperature:this.config.temperature},{headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.openai._apiKey}`}}),a=t.data.choices||[],n=a[0]?.message||{role:"assistant",content:""};return{id:t?.data.id,text:n.content,apiReseponse:t.data}}}},854:function(e,t,a){var n=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.requireJsonResponseWithJsonSchema=t.requireJsonResponseWithHandlebars=t.requireJsonResponse=void 0;const r=n(a(156)),o=a(572);t.requireJsonResponse=(e,t)=>[...Array.isArray(e)?e:[e],"Please respond using the following JSON format and minify the JSON without including any explanation: ","{",Object.entries(t).map((([e,t])=>[`/* ${t.desc} */`,`"${e}": ${JSON.stringify(t.example)}`].join("\n"))).join(",\n"),"}"].join("\n"),t.requireJsonResponseWithHandlebars=(e,a,n)=>{const s=r.default.create();return s.registerHelper("DATA",(function(e){return JSON.stringify(e)})),s.registerHelper("ENV",(function(e){return this.__envs&&e?this.__envs[e]:""})),s.registerHelper("INPUT",(function(){return JSON.stringify(o.record.omit(this,["__envs"]))})),s.registerHelper("JOIN",(function(e){return Array.isArray(e)?e.join():JSON.stringify(e)})),s.compile((0,t.requireJsonResponse)(a,n))(e)},t.requireJsonResponseWithJsonSchema=(e,t)=>[...Array.isArray(e)?e:[e],"Please provide JSON data according to the following JSON Schema format:",JSON.stringify(t)].join("\n")},165:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.ParserError=void 0,t.ParserError=class{isParserError=!0;parserFails=[];error;constructor(e,t){this.error=e,this.parserFails=t}}},357:function(e,t,a){var n=this&&this.__createBinding||(Object.create?function(e,t,a,n){void 0===n&&(n=a);var r=Object.getOwnPropertyDescriptor(t,a);r&&!("get"in r?!t.__esModule:r.writable||r.configurable)||(r={enumerable:!0,get:function(){return t[a]}}),Object.defineProperty(e,n,r)}:function(e,t,a,n){void 0===n&&(n=a),e[n]=t[a]}),r=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),o=this&&this.__importStar||function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var a in e)"default"!==a&&Object.prototype.hasOwnProperty.call(e,a)&&n(t,e,a);return r(t,e),t};Object.defineProperty(t,"__esModule",{value:!0}),t.validateToJsonSchema=t.defineYupSchema=t.validate=t.definedValidateSchema=void 0;const s=o(a(622)),i=a(250);t.definedValidateSchema=function(e){return e},t.validate=function(e,t){return s.object(t(s)).required().validateSync(e||{})},t.defineYupSchema=e=>e(s),t.validateToJsonSchema=e=>{const t=e=>{if(e.default&&delete e.default,e.properties)for(let a in e.properties)e.properties[a].default&&delete e.properties[a].default,t(e.properties[a]);e.items&&t(e.items)},a=e=>{if("object"===e.type){e.additionalProperties=!1;for(const t in e.properties)a(e.properties[t])}else"array"===e.type&&a(e.items)},n=(0,i.convertSchema)(s.object(e(s)));return t(n),a(n),n}},250:e=>{e.exports=require("@sodaru/yup-to-json-schema")},938:e=>{e.exports=require("axios")},4:e=>{e.exports=require("chinese-conv")},156:e=>{e.exports=require("handlebars")},865:e=>{e.exports=require("json5")},572:e=>{e.exports=require("power-helper")},622:e=>{e.exports=require("yup")}},t={};return function a(n){var r=t[n];if(void 0!==r)return r.exports;var o=t[n]={exports:{}};return e[n].call(o.exports,o,o.exports,a),o.exports}(665)})()));
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ctod",
3
- "version": "0.7.0",
3
+ "version": "0.7.1",
4
4
  "description": "CtoD Is Chat To Data Utils.",
5
5
  "main": "./dist/index.js",
6
6
  "scripts": {
package/examples/basic.ts DELETED
@@ -1,89 +0,0 @@
1
- import fs from 'fs'
2
- import { CtoD, OpenAI } from '../lib/index'
3
-
4
- /**
5
- * @test npx esno ./examples/basic.ts
6
- */
7
-
8
- const apiKey = fs.readFileSync('./.api-key', 'utf-8').trim()
9
-
10
- const ctod = new CtoD({
11
- request: OpenAI.createChatRequestWithJsonSchema({
12
- apiKey,
13
- config: {
14
- model: 'gpt-4o'
15
- }
16
- })
17
- })
18
-
19
- const brokerBuilder = ctod.createBrokerBuilder<{
20
- indexes: string[]
21
- question: string
22
- }>({
23
- install: ({ attach }) => {
24
- attach('start', async({ setPreMessages }) => {
25
- setPreMessages([
26
- {
27
- role: 'system',
28
- content: '你現在是一位擅長分類索引的藥師'
29
- }
30
- ])
31
- })
32
- }
33
- })
34
-
35
- const broker = brokerBuilder.create(async({ yup, data, setMessages }) => {
36
- const { indexes, question } = data
37
- setMessages([
38
- {
39
- role: 'user',
40
- content: [
41
- '我有以下索引',
42
- `${JSON.stringify(indexes)}`,
43
- `請幫我解析"${question}"可能是哪個索引`,
44
- '且相關性由高到低排序並給予分數,分數由 0 ~ 1'
45
- ]
46
- }
47
- ])
48
- const item = yup.object({
49
- name: yup.string().required().meta({
50
- jsonSchema: {
51
- description: '索引名稱'
52
- }
53
- }),
54
- score: yup.number().required().meta({
55
- jsonSchema: {
56
- description: '評比分數'
57
- }
58
- })
59
- }).required()
60
- return {
61
- indexes: yup.array(item).required().meta({
62
- jsonSchema: {
63
- description: '由高到低排序的索引'
64
- }
65
- })
66
- }
67
- })
68
-
69
- broker.request({
70
- indexes: ['胃痛', '腰痛', '頭痛', '喉嚨痛', '四肢疼痛'],
71
- question: '喝咖啡,吃甜食,胃食道逆流'
72
- }).then(e => {
73
- console.log('輸出結果:', e.indexes)
74
- /*
75
- [
76
- {
77
- name: '胃痛',
78
- score: 1
79
- },
80
- {
81
- name: '喉嚨痛',
82
- score: 0.7
83
- },
84
- ...
85
- ]
86
- */
87
- }).catch(error => {
88
- console.error('Error:', error)
89
- })
@@ -1,56 +0,0 @@
1
- // eslint-disable-next-line @typescript-eslint/triple-slash-reference
2
- /// <reference path="../lib/shims.d.ts" />
3
- import { CtoD, Llama3Cpp } from '../lib/index'
4
-
5
- /**
6
- * @test npx esno ./examples/llama.cpp.ts
7
- */
8
-
9
- const ctod = new CtoD({
10
- request: Llama3Cpp.createChatRequest({
11
- config: {
12
- baseUrl: 'http://localhost:12333'
13
- }
14
- })
15
- })
16
-
17
- const brokerBuilder = ctod.createBrokerBuilder<{
18
- scene: string
19
- }>({
20
- install: ({ attach }) => {
21
- attach('start', async({ setPreMessages }) => {
22
- setPreMessages([
23
- {
24
- role: 'system',
25
- content: '你現在是一個遊戲設計師'
26
- },
27
- {
28
- role: 'user',
29
- content: '我在設計一個互動式遊戲,但我現在對於劇情下一步要發生什麼事情遇到了困難'
30
- },
31
- {
32
- role: 'assistant',
33
- content: '沒問題,我來幫你想想看。'
34
- }
35
- ])
36
- })
37
- }
38
- })
39
-
40
- const broker = brokerBuilder.create(async({ yup, data, setMessages }) => {
41
- setMessages([
42
- {
43
- role: 'user',
44
- content: data.scene || '任意發揮'
45
- }
46
- ])
47
- return {
48
- next: yup.array().of(yup.string().required()).required()
49
- }
50
- })
51
-
52
- broker.request({
53
- scene: '今天小紅帽遇到了大野狼,大野狼要吃掉小紅帽,小紅帽要怎麼辦?給我三個下一步要發生的事件'
54
- }).then(result => {
55
- console.log(result.next)
56
- })