@difizen/libro-prompt-cell 0.1.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 (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1 -0
  3. package/es/index.d.ts +6 -0
  4. package/es/index.d.ts.map +1 -0
  5. package/es/index.js +5 -0
  6. package/es/index.less +54 -0
  7. package/es/libro-llm-render.d.ts +10 -0
  8. package/es/libro-llm-render.d.ts.map +1 -0
  9. package/es/libro-llm-render.js +71 -0
  10. package/es/module.d.ts +3 -0
  11. package/es/module.d.ts.map +1 -0
  12. package/es/module.js +23 -0
  13. package/es/prompt-cell-command-contribution.d.ts +18 -0
  14. package/es/prompt-cell-command-contribution.d.ts.map +1 -0
  15. package/es/prompt-cell-command-contribution.js +62 -0
  16. package/es/prompt-cell-contribution.d.ts +13 -0
  17. package/es/prompt-cell-contribution.d.ts.map +1 -0
  18. package/es/prompt-cell-contribution.js +66 -0
  19. package/es/prompt-cell-model.d.ts +33 -0
  20. package/es/prompt-cell-model.d.ts.map +1 -0
  21. package/es/prompt-cell-model.js +163 -0
  22. package/es/prompt-cell-output-area.d.ts +14 -0
  23. package/es/prompt-cell-output-area.d.ts.map +1 -0
  24. package/es/prompt-cell-output-area.js +74 -0
  25. package/es/prompt-cell-protocol.d.ts +5 -0
  26. package/es/prompt-cell-protocol.d.ts.map +1 -0
  27. package/es/prompt-cell-protocol.js +1 -0
  28. package/es/prompt-cell-script.d.ts +4 -0
  29. package/es/prompt-cell-script.d.ts.map +1 -0
  30. package/es/prompt-cell-script.js +4 -0
  31. package/es/prompt-cell-utils.d.ts +2 -0
  32. package/es/prompt-cell-utils.d.ts.map +1 -0
  33. package/es/prompt-cell-utils.js +7 -0
  34. package/es/prompt-cell-view.d.ts +50 -0
  35. package/es/prompt-cell-view.d.ts.map +1 -0
  36. package/es/prompt-cell-view.js +543 -0
  37. package/es/prompt-output-render.d.ts +6 -0
  38. package/es/prompt-output-render.d.ts.map +1 -0
  39. package/es/prompt-output-render.js +120 -0
  40. package/es/prompt-output-rendermime-contribution.d.ts +13 -0
  41. package/es/prompt-output-rendermime-contribution.d.ts.map +1 -0
  42. package/es/prompt-output-rendermime-contribution.js +22 -0
  43. package/package.json +72 -0
  44. package/src/index.less +54 -0
  45. package/src/index.spec.ts +9 -0
  46. package/src/index.ts +5 -0
  47. package/src/libro-llm-render.tsx +63 -0
  48. package/src/module.ts +35 -0
  49. package/src/prompt-cell-command-contribution.ts +61 -0
  50. package/src/prompt-cell-contribution.ts +34 -0
  51. package/src/prompt-cell-model.ts +117 -0
  52. package/src/prompt-cell-output-area.tsx +59 -0
  53. package/src/prompt-cell-protocol.ts +8 -0
  54. package/src/prompt-cell-script.ts +4 -0
  55. package/src/prompt-cell-utils.ts +6 -0
  56. package/src/prompt-cell-view.tsx +446 -0
  57. package/src/prompt-output-render.tsx +83 -0
  58. package/src/prompt-output-rendermime-contribution.ts +16 -0
@@ -0,0 +1,120 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ function _regeneratorRuntime() { "use strict"; /*! regenerator-runtime -- Copyright (c) 2014-present, Facebook, Inc. -- license (MIT): https://github.com/facebook/regenerator/blob/main/LICENSE */ _regeneratorRuntime = function _regeneratorRuntime() { return e; }; var t, e = {}, r = Object.prototype, n = r.hasOwnProperty, o = Object.defineProperty || function (t, e, r) { t[e] = r.value; }, i = "function" == typeof Symbol ? Symbol : {}, a = i.iterator || "@@iterator", c = i.asyncIterator || "@@asyncIterator", u = i.toStringTag || "@@toStringTag"; function define(t, e, r) { return Object.defineProperty(t, e, { value: r, enumerable: !0, configurable: !0, writable: !0 }), t[e]; } try { define({}, ""); } catch (t) { define = function define(t, e, r) { return t[e] = r; }; } function wrap(t, e, r, n) { var i = e && e.prototype instanceof Generator ? e : Generator, a = Object.create(i.prototype), c = new Context(n || []); return o(a, "_invoke", { value: makeInvokeMethod(t, r, c) }), a; } function tryCatch(t, e, r) { try { return { type: "normal", arg: t.call(e, r) }; } catch (t) { return { type: "throw", arg: t }; } } e.wrap = wrap; var h = "suspendedStart", l = "suspendedYield", f = "executing", s = "completed", y = {}; function Generator() {} function GeneratorFunction() {} function GeneratorFunctionPrototype() {} var p = {}; define(p, a, function () { return this; }); var d = Object.getPrototypeOf, v = d && d(d(values([]))); v && v !== r && n.call(v, a) && (p = v); var g = GeneratorFunctionPrototype.prototype = Generator.prototype = Object.create(p); function defineIteratorMethods(t) { ["next", "throw", "return"].forEach(function (e) { define(t, e, function (t) { return this._invoke(e, t); }); }); } function AsyncIterator(t, e) { function invoke(r, o, i, a) { var c = tryCatch(t[r], t, o); if ("throw" !== c.type) { var u = c.arg, h = u.value; return h && "object" == _typeof(h) && n.call(h, "__await") ? e.resolve(h.__await).then(function (t) { invoke("next", t, i, a); }, function (t) { invoke("throw", t, i, a); }) : e.resolve(h).then(function (t) { u.value = t, i(u); }, function (t) { return invoke("throw", t, i, a); }); } a(c.arg); } var r; o(this, "_invoke", { value: function value(t, n) { function callInvokeWithMethodAndArg() { return new e(function (e, r) { invoke(t, n, e, r); }); } return r = r ? r.then(callInvokeWithMethodAndArg, callInvokeWithMethodAndArg) : callInvokeWithMethodAndArg(); } }); } function makeInvokeMethod(e, r, n) { var o = h; return function (i, a) { if (o === f) throw new Error("Generator is already running"); if (o === s) { if ("throw" === i) throw a; return { value: t, done: !0 }; } for (n.method = i, n.arg = a;;) { var c = n.delegate; if (c) { var u = maybeInvokeDelegate(c, n); if (u) { if (u === y) continue; return u; } } if ("next" === n.method) n.sent = n._sent = n.arg;else if ("throw" === n.method) { if (o === h) throw o = s, n.arg; n.dispatchException(n.arg); } else "return" === n.method && n.abrupt("return", n.arg); o = f; var p = tryCatch(e, r, n); if ("normal" === p.type) { if (o = n.done ? s : l, p.arg === y) continue; return { value: p.arg, done: n.done }; } "throw" === p.type && (o = s, n.method = "throw", n.arg = p.arg); } }; } function maybeInvokeDelegate(e, r) { var n = r.method, o = e.iterator[n]; if (o === t) return r.delegate = null, "throw" === n && e.iterator.return && (r.method = "return", r.arg = t, maybeInvokeDelegate(e, r), "throw" === r.method) || "return" !== n && (r.method = "throw", r.arg = new TypeError("The iterator does not provide a '" + n + "' method")), y; var i = tryCatch(o, e.iterator, r.arg); if ("throw" === i.type) return r.method = "throw", r.arg = i.arg, r.delegate = null, y; var a = i.arg; return a ? a.done ? (r[e.resultName] = a.value, r.next = e.nextLoc, "return" !== r.method && (r.method = "next", r.arg = t), r.delegate = null, y) : a : (r.method = "throw", r.arg = new TypeError("iterator result is not an object"), r.delegate = null, y); } function pushTryEntry(t) { var e = { tryLoc: t[0] }; 1 in t && (e.catchLoc = t[1]), 2 in t && (e.finallyLoc = t[2], e.afterLoc = t[3]), this.tryEntries.push(e); } function resetTryEntry(t) { var e = t.completion || {}; e.type = "normal", delete e.arg, t.completion = e; } function Context(t) { this.tryEntries = [{ tryLoc: "root" }], t.forEach(pushTryEntry, this), this.reset(!0); } function values(e) { if (e || "" === e) { var r = e[a]; if (r) return r.call(e); if ("function" == typeof e.next) return e; if (!isNaN(e.length)) { var o = -1, i = function next() { for (; ++o < e.length;) if (n.call(e, o)) return next.value = e[o], next.done = !1, next; return next.value = t, next.done = !0, next; }; return i.next = i; } } throw new TypeError(_typeof(e) + " is not iterable"); } return GeneratorFunction.prototype = GeneratorFunctionPrototype, o(g, "constructor", { value: GeneratorFunctionPrototype, configurable: !0 }), o(GeneratorFunctionPrototype, "constructor", { value: GeneratorFunction, configurable: !0 }), GeneratorFunction.displayName = define(GeneratorFunctionPrototype, u, "GeneratorFunction"), e.isGeneratorFunction = function (t) { var e = "function" == typeof t && t.constructor; return !!e && (e === GeneratorFunction || "GeneratorFunction" === (e.displayName || e.name)); }, e.mark = function (t) { return Object.setPrototypeOf ? Object.setPrototypeOf(t, GeneratorFunctionPrototype) : (t.__proto__ = GeneratorFunctionPrototype, define(t, u, "GeneratorFunction")), t.prototype = Object.create(g), t; }, e.awrap = function (t) { return { __await: t }; }, defineIteratorMethods(AsyncIterator.prototype), define(AsyncIterator.prototype, c, function () { return this; }), e.AsyncIterator = AsyncIterator, e.async = function (t, r, n, o, i) { void 0 === i && (i = Promise); var a = new AsyncIterator(wrap(t, r, n, o), i); return e.isGeneratorFunction(r) ? a : a.next().then(function (t) { return t.done ? t.value : a.next(); }); }, defineIteratorMethods(g), define(g, u, "Generator"), define(g, a, function () { return this; }), define(g, "toString", function () { return "[object Generator]"; }), e.keys = function (t) { var e = Object(t), r = []; for (var n in e) r.push(n); return r.reverse(), function next() { for (; r.length;) { var t = r.pop(); if (t in e) return next.value = t, next.done = !1, next; } return next.done = !0, next; }; }, e.values = values, Context.prototype = { constructor: Context, reset: function reset(e) { if (this.prev = 0, this.next = 0, this.sent = this._sent = t, this.done = !1, this.delegate = null, this.method = "next", this.arg = t, this.tryEntries.forEach(resetTryEntry), !e) for (var r in this) "t" === r.charAt(0) && n.call(this, r) && !isNaN(+r.slice(1)) && (this[r] = t); }, stop: function stop() { this.done = !0; var t = this.tryEntries[0].completion; if ("throw" === t.type) throw t.arg; return this.rval; }, dispatchException: function dispatchException(e) { if (this.done) throw e; var r = this; function handle(n, o) { return a.type = "throw", a.arg = e, r.next = n, o && (r.method = "next", r.arg = t), !!o; } for (var o = this.tryEntries.length - 1; o >= 0; --o) { var i = this.tryEntries[o], a = i.completion; if ("root" === i.tryLoc) return handle("end"); if (i.tryLoc <= this.prev) { var c = n.call(i, "catchLoc"), u = n.call(i, "finallyLoc"); if (c && u) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } else if (c) { if (this.prev < i.catchLoc) return handle(i.catchLoc, !0); } else { if (!u) throw new Error("try statement without catch or finally"); if (this.prev < i.finallyLoc) return handle(i.finallyLoc); } } } }, abrupt: function abrupt(t, e) { for (var r = this.tryEntries.length - 1; r >= 0; --r) { var o = this.tryEntries[r]; if (o.tryLoc <= this.prev && n.call(o, "finallyLoc") && this.prev < o.finallyLoc) { var i = o; break; } } i && ("break" === t || "continue" === t) && i.tryLoc <= e && e <= i.finallyLoc && (i = null); var a = i ? i.completion : {}; return a.type = t, a.arg = e, i ? (this.method = "next", this.next = i.finallyLoc, y) : this.complete(a); }, complete: function complete(t, e) { if ("throw" === t.type) throw t.arg; return "break" === t.type || "continue" === t.type ? this.next = t.arg : "return" === t.type ? (this.rval = this.arg = t.arg, this.method = "return", this.next = "end") : "normal" === t.type && e && (this.next = e), y; }, finish: function finish(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.finallyLoc === t) return this.complete(r.completion, r.afterLoc), resetTryEntry(r), y; } }, catch: function _catch(t) { for (var e = this.tryEntries.length - 1; e >= 0; --e) { var r = this.tryEntries[e]; if (r.tryLoc === t) { var n = r.completion; if ("throw" === n.type) { var o = n.arg; resetTryEntry(r); } return o; } } throw new Error("illegal catch attempt"); }, delegateYield: function delegateYield(e, r, n) { return this.delegate = { iterator: values(e), resultName: r, nextLoc: n }, "next" === this.method && (this.arg = t), y; } }, e; }
3
+ function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
4
+ function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
5
+ import { concatMultilineString } from '@difizen/libro-common';
6
+ import { NotebookCommands } from '@difizen/libro-jupyter';
7
+ import { CommandRegistry, useInject } from '@difizen/mana-app';
8
+ import React from 'react';
9
+ import { v4 } from 'uuid';
10
+ import { LibroLLMRenderMemo } from "./libro-llm-render.js";
11
+ import { getPythonCode } from "./prompt-cell-utils.js";
12
+ import { jsx as _jsx } from "react/jsx-runtime";
13
+ import { jsxs as _jsxs } from "react/jsx-runtime";
14
+ var getModelOutput = function getModelOutput(data) {
15
+ if (typeof data === 'string' || Array.isArray(data)) {
16
+ return concatMultilineString(data);
17
+ } else {
18
+ return JSON.stringify(data);
19
+ }
20
+ };
21
+ export var PromptOutputRender = function PromptOutputRender(props) {
22
+ var model = props.model;
23
+ var renderHTMLRef = /*#__PURE__*/React.createRef();
24
+ var commandRegistry = useInject(CommandRegistry);
25
+ if (!model.data['application/vnd.libro.prompt+json']) {
26
+ return null;
27
+ }
28
+ var _ref = model.data['application/vnd.libro.prompt+json'],
29
+ data = _ref.data;
30
+ if (!data) {
31
+ return null;
32
+ }
33
+ var modelData = getModelOutput(data);
34
+ var sourceArr = getPythonCode(modelData !== null && modelData !== void 0 ? modelData : '');
35
+ var handleOutput = /*#__PURE__*/function () {
36
+ var _ref2 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee3() {
37
+ var libro, insertIndex;
38
+ return _regeneratorRuntime().wrap(function _callee3$(_context3) {
39
+ while (1) switch (_context3.prev = _context3.next) {
40
+ case 0:
41
+ libro = model.cell.parent;
42
+ insertIndex = libro.model.cells.findIndex(function (c) {
43
+ return c.id === model.cell.id;
44
+ });
45
+ _context3.next = 4;
46
+ return Promise.all(sourceArr.map( /*#__PURE__*/function () {
47
+ var _ref3 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee(value, index) {
48
+ var newView;
49
+ return _regeneratorRuntime().wrap(function _callee$(_context) {
50
+ while (1) switch (_context.prev = _context.next) {
51
+ case 0:
52
+ _context.next = 2;
53
+ return libro.addCell({
54
+ id: v4(),
55
+ cell: {
56
+ cell_type: 'code',
57
+ source: value,
58
+ metadata: {}
59
+ }
60
+ }, insertIndex + index + 1);
61
+ case 2:
62
+ newView = _context.sent;
63
+ return _context.abrupt("return", newView);
64
+ case 4:
65
+ case "end":
66
+ return _context.stop();
67
+ }
68
+ }, _callee);
69
+ }));
70
+ return function (_x, _x2) {
71
+ return _ref3.apply(this, arguments);
72
+ };
73
+ }()));
74
+ case 4:
75
+ _context3.next = 6;
76
+ return Promise.all(sourceArr.map( /*#__PURE__*/function () {
77
+ var _ref4 = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime().mark(function _callee2(_, index) {
78
+ return _regeneratorRuntime().wrap(function _callee2$(_context2) {
79
+ while (1) switch (_context2.prev = _context2.next) {
80
+ case 0:
81
+ _context2.next = 2;
82
+ return commandRegistry.executeCommand(NotebookCommands['RunCell'].id, libro.model.cells[insertIndex + index + 1], libro);
83
+ case 2:
84
+ case "end":
85
+ return _context2.stop();
86
+ }
87
+ }, _callee2);
88
+ }));
89
+ return function (_x3, _x4) {
90
+ return _ref4.apply(this, arguments);
91
+ };
92
+ }()));
93
+ case 6:
94
+ case "end":
95
+ return _context3.stop();
96
+ }
97
+ }, _callee3);
98
+ }));
99
+ return function handleOutput() {
100
+ return _ref2.apply(this, arguments);
101
+ };
102
+ }();
103
+ return /*#__PURE__*/_jsxs("div", {
104
+ className: "libro-prompt-output-render-container",
105
+ children: [/*#__PURE__*/_jsx("div", {
106
+ className: "prompt-output-render",
107
+ ref: renderHTMLRef,
108
+ children: /*#__PURE__*/_jsx("div", {
109
+ className: "libro-prompt-output-llm-render",
110
+ children: /*#__PURE__*/_jsx(LibroLLMRenderMemo, {
111
+ data: modelData
112
+ })
113
+ })
114
+ }), sourceArr.length > 0 && /*#__PURE__*/_jsx("span", {
115
+ onClick: handleOutput,
116
+ className: "libro-prompt-output-btn",
117
+ children: "\u63D2\u5165\u5E76\u8FD0\u884C"
118
+ })]
119
+ });
120
+ };
@@ -0,0 +1,13 @@
1
+ /// <reference types="react" resolution-mode="require"/>
2
+ import type { BaseOutputView } from '@difizen/libro-jupyter';
3
+ import { RenderMimeContribution } from '@difizen/libro-jupyter';
4
+ export declare class LibroPromptOutputMimeTypeContribution implements RenderMimeContribution {
5
+ canHandle: (model: BaseOutputView) => number;
6
+ renderType: string;
7
+ safe: boolean;
8
+ mimeTypes: string[];
9
+ render: import("react").FC<{
10
+ model: BaseOutputView;
11
+ }>;
12
+ }
13
+ //# sourceMappingURL=prompt-output-rendermime-contribution.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"prompt-output-rendermime-contribution.d.ts","sourceRoot":"","sources":["../src/prompt-output-rendermime-contribution.ts"],"names":[],"mappings":";AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,wBAAwB,CAAC;AAKhE,qBACa,qCAAsC,YAAW,sBAAsB;IAClF,SAAS,UAAW,cAAc,YAEhC;IACF,UAAU,SAAwB;IAClC,IAAI,UAAQ;IACZ,SAAS,WAAyC;IAClD,MAAM;;OAAsB;CAC7B"}
@@ -0,0 +1,22 @@
1
+ function _typeof(o) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (o) { return typeof o; } : function (o) { return o && "function" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? "symbol" : typeof o; }, _typeof(o); }
2
+ var _dec, _class;
3
+ function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, _toPropertyKey(descriptor.key), descriptor); } }
4
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
5
+ function _toPropertyKey(arg) { var key = _toPrimitive(arg, "string"); return _typeof(key) === "symbol" ? key : String(key); }
6
+ function _toPrimitive(input, hint) { if (_typeof(input) !== "object" || input === null) return input; var prim = input[Symbol.toPrimitive]; if (prim !== undefined) { var res = prim.call(input, hint || "default"); if (_typeof(res) !== "object") return res; throw new TypeError("@@toPrimitive must return a primitive value."); } return (hint === "string" ? String : Number)(input); }
7
+ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
8
+ import { RenderMimeContribution } from '@difizen/libro-jupyter';
9
+ import { singleton } from '@difizen/mana-app';
10
+ import { PromptOutputRender } from "./prompt-output-render.js";
11
+ export var LibroPromptOutputMimeTypeContribution = (_dec = singleton({
12
+ contrib: RenderMimeContribution
13
+ }), _dec(_class = /*#__PURE__*/_createClass(function LibroPromptOutputMimeTypeContribution() {
14
+ _classCallCheck(this, LibroPromptOutputMimeTypeContribution);
15
+ this.canHandle = function (model) {
16
+ return 200;
17
+ };
18
+ this.renderType = 'promptOutputRender';
19
+ this.safe = true;
20
+ this.mimeTypes = ['application/vnd.libro.prompt+json'];
21
+ this.render = PromptOutputRender;
22
+ })) || _class);
package/package.json ADDED
@@ -0,0 +1,72 @@
1
+ {
2
+ "name": "@difizen/libro-prompt-cell",
3
+ "version": "0.1.1",
4
+ "description": "",
5
+ "keywords": [
6
+ "libro",
7
+ "notebook"
8
+ ],
9
+ "repository": "git@github.com:difizen/libro.git",
10
+ "license": "MIT",
11
+ "type": "module",
12
+ "exports": {
13
+ ".": {
14
+ "typings": "./es/index.d.ts",
15
+ "default": "./es/index.js"
16
+ },
17
+ "./mock": {
18
+ "typings": "./es/mock/index.d.ts",
19
+ "default": "./es/mock/index.js"
20
+ },
21
+ "./es/mock": {
22
+ "typings": "./es/mock/index.d.ts",
23
+ "default": "./es/mock/index.js"
24
+ },
25
+ "./package.json": "./package.json"
26
+ },
27
+ "main": "es/index.js",
28
+ "module": "es/index.js",
29
+ "typings": "es/index.d.ts",
30
+ "files": [
31
+ "es",
32
+ "src"
33
+ ],
34
+ "dependencies": {
35
+ "@difizen/libro-code-editor": "^0.1.1",
36
+ "@difizen/libro-jupyter": "^0.1.1",
37
+ "@difizen/libro-rendermime": "^0.1.1",
38
+ "@difizen/libro-codemirror": "^0.1.1",
39
+ "@difizen/libro-common": "^0.1.1",
40
+ "@difizen/libro-core": "^0.1.1",
41
+ "@difizen/mana-app": "latest",
42
+ "highlight.js": "^11.8.0",
43
+ "marked": "^5.1.1",
44
+ "marked-highlight": "^2.0.1",
45
+ "marked-katex-extension": "^3.0.0",
46
+ "uuid": "^9.0.0",
47
+ "react-dom": "^18.2.0"
48
+ },
49
+ "peerDependencies": {
50
+ "react": "^18.2.0",
51
+ "antd": "^5.8.6"
52
+ },
53
+ "devDependencies": {
54
+ "@types/marked": "^5.0.1",
55
+ "@types/react": "^18.2.25",
56
+ "@types/uuid": "^9.0.2",
57
+ "@types/react-dom": "^18.2.4"
58
+ },
59
+ "scripts": {
60
+ "setup": "father build",
61
+ "build": "father build",
62
+ "test": ": Note: lint task is delegated to test:* scripts",
63
+ "test:vitest": "vitest run",
64
+ "test:jest": "jest",
65
+ "coverage": ": Note: lint task is delegated to coverage:* scripts",
66
+ "coverage:vitest": "vitest run --coverage",
67
+ "coverage:jest": "jest --coverage",
68
+ "lint": ": Note: lint task is delegated to lint:* scripts",
69
+ "lint:eslint": "eslint src",
70
+ "lint:tsc": "tsc --noEmit"
71
+ }
72
+ }
package/src/index.less ADDED
@@ -0,0 +1,54 @@
1
+ .libro-llm-hljs {
2
+ overflow-x: auto;
3
+ white-space: pre-wrap !important;
4
+ word-wrap: break-word !important;
5
+ text-shadow: unset !important;
6
+ color: var(--mana-libro-editor-variable-color) !important;
7
+
8
+ .hljs-title.function_ {
9
+ color: var(--mana-libro-editor-def-color);
10
+ }
11
+
12
+ .hljs-keyword {
13
+ color: var(--mana-libro-editor-keyword-color);
14
+ }
15
+
16
+ .hljs-number {
17
+ color: var(--mana-libro-editor-number-color);
18
+ }
19
+
20
+ .hljs-comment {
21
+ color: var(--mana-libro-editor-comment-color);
22
+ }
23
+
24
+ .hljs-string {
25
+ color: var(--mana-libro-editor-string-color);
26
+ }
27
+
28
+ .hljs-built_in {
29
+ color: var(--mana-libro-editor-builtin-color);
30
+ }
31
+ }
32
+
33
+ .libro-llm-output-render {
34
+ p {
35
+ color: var(--mana-libro-llm-response-output-text-color);
36
+ }
37
+ }
38
+
39
+ .libro-prompt-output-render-container {
40
+ padding: 10px 24px;
41
+ }
42
+
43
+ .libro-prompt-output-llm-render {
44
+ .libro-llm-output-render pre {
45
+ background: #f4f6fb;
46
+ padding: 16px;
47
+ }
48
+ }
49
+
50
+ .libro-prompt-output-btn {
51
+ cursor: pointer;
52
+ color: #1677ff;
53
+ margin-left: 24px;
54
+ }
@@ -0,0 +1,9 @@
1
+ import assert from 'assert';
2
+
3
+ import 'reflect-metadata';
4
+
5
+ describe('libro-prompt-cell', () => {
6
+ it('#import', () => {
7
+ assert(true);
8
+ });
9
+ });
package/src/index.ts ADDED
@@ -0,0 +1,5 @@
1
+ export * from './prompt-cell-contribution.js';
2
+ export * from './prompt-cell-model.js';
3
+ export * from './prompt-cell-protocol.js';
4
+ export * from './prompt-cell-view.js';
5
+ export * from './module.js';
@@ -0,0 +1,63 @@
1
+ import { ToolbarRender } from '@difizen/mana-app';
2
+ import hljs from 'highlight.js';
3
+ import { marked } from 'marked';
4
+ import { markedHighlight } from 'marked-highlight';
5
+ import markedKatex from 'marked-katex-extension';
6
+ import React, { useEffect, useRef, memo, useState, useMemo } from 'react';
7
+ import 'highlight.js/styles/default.css';
8
+ import { createPortal } from 'react-dom';
9
+ import './index.less';
10
+
11
+ marked.use(
12
+ markedKatex({
13
+ throwOnError: false,
14
+ output: 'mathml',
15
+ }),
16
+ markedHighlight({
17
+ langPrefix: 'libro-llm-hljs code-block language-',
18
+ highlight(code: string, lang: string) {
19
+ const language = hljs.getLanguage(lang) ? lang : 'python';
20
+ return hljs.highlight(code, { language }).value;
21
+ },
22
+ }),
23
+ );
24
+
25
+ export const LibroLLMRender: React.FC<{ data: string }> = (props: { data: string }) => {
26
+ const { data } = props;
27
+
28
+ const renderMarkdownRef = useRef<HTMLDivElement>(null);
29
+ // const LLMExtraRender = useInject<LLMExtraRenderProvider>(LLMExtraRenderProvider);
30
+ const [renderExtraList, setRenderExtraList] = useState<HTMLDivElement[]>([]);
31
+ const codeToolbarArgs = useMemo(() => {
32
+ return [data, 'CodeToolbar'];
33
+ }, [data]);
34
+
35
+ useEffect(() => {
36
+ if (!renderMarkdownRef.current) {
37
+ return;
38
+ }
39
+ renderMarkdownRef.current.innerHTML = marked.parse(data);
40
+
41
+ const hljsElements =
42
+ renderMarkdownRef.current.getElementsByClassName('libro-llm-hljs');
43
+
44
+ for (let i = 0; i < hljsElements.length; i++) {
45
+ const newElement = document.createElement('div');
46
+ const newRenderExtraList = [...renderExtraList, newElement];
47
+ setRenderExtraList(newRenderExtraList);
48
+ const hljsElement = hljsElements.item(i);
49
+ if (hljsElement) {
50
+ hljsElement.parentNode?.insertBefore(newElement, hljsElement.nextSibling);
51
+ }
52
+ }
53
+ }, [data, renderExtraList]);
54
+
55
+ return (
56
+ <div className="libro-llm-output-render" ref={renderMarkdownRef}>
57
+ {renderExtraList.map((element) => {
58
+ return createPortal(<ToolbarRender data={codeToolbarArgs} />, element);
59
+ })}
60
+ </div>
61
+ );
62
+ };
63
+ export const LibroLLMRenderMemo = memo(LibroLLMRender);
package/src/module.ts ADDED
@@ -0,0 +1,35 @@
1
+ import { CellOptions, LibroModule, OutputModule } from '@difizen/libro-core';
2
+ import { LibroRenderMimeModule } from '@difizen/libro-rendermime';
3
+ import { ManaModule } from '@difizen/mana-app';
4
+
5
+ import { PromptCellContribution } from './prompt-cell-contribution.js';
6
+ import { LibroPromptCellModel } from './prompt-cell-model.js';
7
+ import { LibroPromptOutputArea } from './prompt-cell-output-area.js';
8
+ import { LibroPromptCellModelFactory } from './prompt-cell-protocol.js';
9
+ import { LibroPromptCellView } from './prompt-cell-view.js';
10
+ import { LibroPromptOutputMimeTypeContribution } from './prompt-output-rendermime-contribution.js';
11
+
12
+ export const LibroPromptCellModule = ManaModule.create()
13
+ .register(
14
+ PromptCellContribution,
15
+ LibroPromptCellView,
16
+ LibroPromptCellModel,
17
+ LibroPromptOutputArea,
18
+ LibroPromptOutputMimeTypeContribution,
19
+
20
+ {
21
+ token: LibroPromptCellModelFactory,
22
+ useFactory: (ctx) => {
23
+ return (options: CellOptions) => {
24
+ const child = ctx.container.createChild();
25
+ child.register({
26
+ token: CellOptions,
27
+ useValue: options,
28
+ });
29
+ const model = child.get(LibroPromptCellModel);
30
+ return model;
31
+ };
32
+ },
33
+ },
34
+ )
35
+ .dependOn(LibroModule, OutputModule, LibroRenderMimeModule);
@@ -0,0 +1,61 @@
1
+ import type { CellView, NotebookView } from '@difizen/libro-core';
2
+ import { LibroCommandRegister, LibroCellView, LibroView } from '@difizen/libro-core';
3
+ import type { CommandRegistry } from '@difizen/mana-app';
4
+ import {
5
+ CommandContribution,
6
+ inject,
7
+ KeybindingContribution,
8
+ KeybindingRegistry,
9
+ singleton,
10
+ } from '@difizen/mana-app';
11
+
12
+ export const LibroPromptCellCommands = {
13
+ ChangeCellToPrompt: {
14
+ id: 'notebook:change-cell-to-prompt',
15
+ label: `Change to Prompt`,
16
+ keybind: 'p',
17
+ when: 'commandMode',
18
+ },
19
+ };
20
+
21
+ @singleton({ contrib: [CommandContribution, KeybindingContribution] })
22
+ export class LibroPromptCellCommandContribution
23
+ implements CommandContribution, KeybindingContribution
24
+ {
25
+ @inject(LibroCommandRegister)
26
+ protected readonly libroCommand: LibroCommandRegister;
27
+ constructor(@inject(KeybindingRegistry) keybindRegistry: KeybindingRegistry) {
28
+ // 快捷键命中时默认阻止事件冒泡
29
+ keybindRegistry.preventDefault = true;
30
+ keybindRegistry.stopPropagation = true;
31
+ }
32
+
33
+ registerCommands(command: CommandRegistry): void {
34
+ this.libroCommand.registerLibroCommand(
35
+ command,
36
+ LibroPromptCellCommands.ChangeCellToPrompt,
37
+ {
38
+ execute: (cell: CellView | undefined, libro: NotebookView | undefined) => {
39
+ if (
40
+ !cell ||
41
+ !libro ||
42
+ !(cell instanceof LibroCellView) ||
43
+ !(libro instanceof LibroView)
44
+ ) {
45
+ return;
46
+ }
47
+ libro.invertCell(cell, 'prompt');
48
+ },
49
+ isEnabled: (cell, libro) => {
50
+ if (!libro || !(libro instanceof LibroView) || libro.model.readOnly) {
51
+ return false;
52
+ }
53
+ return true;
54
+ },
55
+ },
56
+ );
57
+ }
58
+ registerKeybindings(keybindings: KeybindingRegistry) {
59
+ this.libroCommand.registerKeybinds(keybindings, LibroPromptCellCommands);
60
+ }
61
+ }
@@ -0,0 +1,34 @@
1
+ import type { CellModel } from '@difizen/libro-core';
2
+ import type { CellMeta, CellOptions } from '@difizen/libro-core';
3
+ import { CellViewContribution, CellModelContribution } from '@difizen/libro-core';
4
+ import { inject } from '@difizen/mana-app';
5
+ import { singleton } from '@difizen/mana-app';
6
+
7
+ import { LibroPromptCellModelFactory } from './prompt-cell-protocol.js';
8
+ import { LibroPromptCellView } from './prompt-cell-view.js';
9
+
10
+ @singleton({ contrib: [CellModelContribution, CellViewContribution] })
11
+ export class PromptCellContribution
12
+ implements CellModelContribution, CellViewContribution
13
+ {
14
+ @inject(LibroPromptCellModelFactory)
15
+ libroCellModelFactory: LibroPromptCellModelFactory;
16
+
17
+ cellMeta: CellMeta = {
18
+ type: 'prompt',
19
+ name: 'Propmt',
20
+ order: 'f',
21
+ nbformatType: 'code',
22
+ };
23
+
24
+ canHandle(options: CellOptions, libroType?: string): number {
25
+ return libroType === this.cellMeta.type ? 2000 : -1;
26
+ }
27
+
28
+ async createModel(options: CellOptions): Promise<CellModel> {
29
+ const model = this.libroCellModelFactory(options);
30
+ return model;
31
+ }
32
+
33
+ view = LibroPromptCellView;
34
+ }
@@ -0,0 +1,117 @@
1
+ import { concatMultilineString } from '@difizen/libro-common';
2
+ import type {
3
+ ICellMetadata,
4
+ ExecutionCount,
5
+ ICodeCellMetadata,
6
+ } from '@difizen/libro-common';
7
+ import type { ICodeCell } from '@difizen/libro-common';
8
+ import type { ExecutableCellModel } from '@difizen/libro-core';
9
+ import { LibroCellModel } from '@difizen/libro-core';
10
+ import { CellOptions } from '@difizen/libro-core';
11
+ import type { ExecutionMeta } from '@difizen/libro-jupyter';
12
+ import { Emitter } from '@difizen/mana-app';
13
+ import { transient } from '@difizen/mana-app';
14
+ import { prop } from '@difizen/mana-app';
15
+ import { ViewManager } from '@difizen/mana-app';
16
+ import { inject } from '@difizen/mana-app';
17
+ import type { Event as ManaEvent } from '@difizen/mana-app';
18
+
19
+ export interface PromptCellMetadata extends ICodeCellMetadata {
20
+ execution: ExecutionMeta;
21
+ }
22
+
23
+ @transient()
24
+ export class LibroPromptCellModel
25
+ extends LibroCellModel
26
+ implements ExecutableCellModel
27
+ {
28
+ @prop()
29
+ executeCount: ExecutionCount;
30
+
31
+ @prop()
32
+ hasExecutedSuccess = false;
33
+ @prop()
34
+ hasExecutedError = false;
35
+ @prop()
36
+ override metadata: Partial<PromptCellMetadata | ICellMetadata>;
37
+ @prop()
38
+ kernelExecuting = false;
39
+
40
+ modelType: string;
41
+ @prop()
42
+ executing: boolean;
43
+ @prop()
44
+ hasOutputHidden: boolean;
45
+ @prop()
46
+ hasOutputsScrolled: boolean;
47
+
48
+ // Emitter Msg
49
+ msgChangeEmitter: Emitter<any>;
50
+
51
+ get msgChange(): ManaEvent<any> {
52
+ return this.msgChangeEmitter.event;
53
+ }
54
+
55
+ viewManager: ViewManager;
56
+
57
+ constructor(
58
+ @inject(CellOptions) options: CellOptions,
59
+ @inject(ViewManager) viewManager: ViewManager,
60
+ ) {
61
+ super(options);
62
+ this.viewManager = viewManager;
63
+ this.executing = false;
64
+ this.msgChangeEmitter = new Emitter<any>();
65
+ this.executeCount = (options.cell as ICodeCell).execution_count || null;
66
+ this.hasOutputHidden = false;
67
+ this.hasOutputsScrolled = false;
68
+ this.mimeType = 'text/x-python';
69
+ this.metadata = options?.cell?.metadata || {};
70
+ this.fromSource(concatMultilineString(options?.cell?.source));
71
+ }
72
+
73
+ fromSource(source: string) {
74
+ try {
75
+ const run = source.split('%%prompt \n')[1];
76
+ const runValue = JSON.parse(run);
77
+ this.value = runValue.prompt;
78
+ this.modelType = runValue.model_name;
79
+ } catch {
80
+ () => {
81
+ //
82
+ };
83
+ }
84
+ }
85
+
86
+ override toJSON(): Omit<ICodeCell, 'outputs'> {
87
+ // const outputs = this.outputArea?.toJSON() ?? this.outputs;
88
+ const promptObj = {
89
+ model_name: this.modelType || 'CodeGPT',
90
+ prompt: this.value,
91
+ };
92
+ const encodeValue = `%%prompt \n${JSON.stringify(promptObj)}`;
93
+
94
+ return {
95
+ id: this.id,
96
+ cell_type: this.type,
97
+ source: encodeValue,
98
+ metadata: this.metadata,
99
+ execution_count: this.executeCount,
100
+ // outputs: this.outputs,
101
+ };
102
+ }
103
+
104
+ clearExecution(): void {
105
+ this.executeCount = null;
106
+ this.metadata = {};
107
+ }
108
+
109
+ override dispose() {
110
+ super.dispose();
111
+ this.msgChangeEmitter.dispose();
112
+ }
113
+
114
+ getSource() {
115
+ return this.value;
116
+ }
117
+ }