structured.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import { RunnableBinding } from "../runnables/base.js";
  2. import { ChatPromptTemplate, } from "./chat.js";
  3. function isWithStructuredOutput(x
  4. // eslint-disable-next-line @typescript-eslint/ban-types
  5. ) {
  6. return (typeof x === "object" &&
  7. x != null &&
  8. "withStructuredOutput" in x &&
  9. typeof x.withStructuredOutput === "function");
  10. }
  11. function isRunnableBinding(x) {
  12. return (typeof x === "object" &&
  13. x != null &&
  14. "lc_id" in x &&
  15. Array.isArray(x.lc_id) &&
  16. x.lc_id.join("/") === "langchain_core/runnables/RunnableBinding");
  17. }
  18. export class StructuredPrompt extends ChatPromptTemplate {
  19. get lc_aliases() {
  20. return {
  21. ...super.lc_aliases,
  22. schema: "schema_",
  23. };
  24. }
  25. constructor(input) {
  26. super(input);
  27. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  28. Object.defineProperty(this, "schema", {
  29. enumerable: true,
  30. configurable: true,
  31. writable: true,
  32. value: void 0
  33. });
  34. Object.defineProperty(this, "method", {
  35. enumerable: true,
  36. configurable: true,
  37. writable: true,
  38. value: void 0
  39. });
  40. Object.defineProperty(this, "lc_namespace", {
  41. enumerable: true,
  42. configurable: true,
  43. writable: true,
  44. value: ["langchain_core", "prompts", "structured"]
  45. });
  46. this.schema = input.schema;
  47. this.method = input.method;
  48. }
  49. pipe(coerceable) {
  50. if (isWithStructuredOutput(coerceable)) {
  51. return super.pipe(coerceable.withStructuredOutput(this.schema));
  52. }
  53. if (isRunnableBinding(coerceable) &&
  54. isWithStructuredOutput(coerceable.bound)) {
  55. return super.pipe(new RunnableBinding({
  56. bound: coerceable.bound.withStructuredOutput(this.schema, ...(this.method ? [{ method: this.method }] : [])),
  57. kwargs: coerceable.kwargs ?? {},
  58. config: coerceable.config,
  59. configFactories: coerceable.configFactories,
  60. }));
  61. }
  62. throw new Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`);
  63. }
  64. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  65. static fromMessagesAndSchema(promptMessages, schema, method
  66. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  67. ) {
  68. return StructuredPrompt.fromMessages(promptMessages, { schema, method });
  69. }
  70. }