0

0

自写 Lang 图状态

DDD

DDD

发布时间:2024-12-17 13:48:01

|

1079人浏览过

|

来源于dev.to

转载

自写 lang 图状态

第一人工智能响应:

输出:感谢您伸出援手,.我很乐意为您提供帮助,但我想确保我完全理解您的需求。您能否提供有关您正在寻找的内容的更多详细信息?您分享的信息越多,我就越能提供帮助!我很乐意尽我所能地帮助你。您想进一步探索某个特定领域吗?您的意见将帮助我根据您的具体需求定制我的帮助。我完全致力于让您的体验尽可能顺利和愉快。

ai 响应,在编写自己的图表后:

输出:嗨!这是怎么回事?今天我能为您提供什么帮助?您告诉我的越多,我就越能提供帮助。你在想什么?我来这里是为了帮助您找到适合您的解决方案。请注意,我是一名人工智能助手,仍在学习入门知识。

非常神奇吧?

这听起来几乎是人类的。周末我和 van wilder 一起看了电影《free guy》,我意识到哇,我可能可以使用 @langchain/langgraph 中的 graphstate 来创建一个可以对自身执行迭代并编写自己的代码的 ai。

如果您现在还没有意识到这一点,claude sonnet 非常擅长 0 镜头编码,甚至更擅长多镜头编码。

使用库 npm:sentiment :

来自 readme.md

sentiment 是一个 node.js 模块,它使用 afinn-165 单词列表和表情符号情感排名对任意输入文本块执行情感分析。

我向图形状态添加了一个简单的命令,该命令对输出运行情感分析,并使用新版本改进代码以尝试获得更高的分数:

// update state and continue evolution
    return new command({
      update: {
        ...state,
        code: newcode,
        version: state.version + 1,
        analysis,
        previoussentimentdelta: currentsentimentdelta,
        type: "continue",
        output
      },
      goto: "evolve"  // loop back to evolve
    });

我们用它可以使用的初始图形状态为语言图播种(如果您愿意,可以使用基础代码):

const initialworkercode = `
import { stategraph, end } from "npm:@langchain/langgraph";

const workflow = new stategraph({
  channels: {
    input: "string",
    output: "string?"
  }
});

// initial basic response node
workflow.addnode("respond", (state) => ({
  ...state,
  output: "i understand your request and will try to help. let me know if you need any clarification."
}));

workflow.setentrypoint("respond");
workflow.addedge("respond", end);

const graph = workflow.compile();
export { graph };
`;

您可以看到这是一个非常基本的响应节点,附加了一条边。

V63积分商城 FOR DZ GBK
V63积分商城 FOR DZ GBK

v63积分商城特色功能:支持三种物品类型的发放1.实物:实物领取需要填写收货信息:2.虚拟:可以自定义用户领取需要填写的信息3.卡密:自动发放,后台能够查看编辑卡密状态支持三种种物品发放方式1.兑换:2.拍卖3. 抽奖兑换拍卖信息可以以帖子的形式自动发布当设定了“兑换拍卖自动发帖版块“ ID时,发布商品会自动在改ID版块生成帖子用户兑换或者出价后都会以跟帖的

下载

我将当前代码设置为经过 10 次迭代,试图获得 10 或更高的情绪:

if (import.meta.main) {
  runevolvingsystem(10, 10);
}

每次都会运行分析:

analysis: {
  metrics: {
    emotionalrange: 0.16483516483516483,
    vocabularyvariety: 0.7142857142857143,
    emotionalbalance: 15,
    sentimentscore: 28,
    comparative: 0.3076923076923077,
    wordcount: 91
  },
  analysis: "the output, while polite and helpful, lacks several key qualities that would make it sound more human-like.  let's analyze the metrics and then suggest improvements:\n" +
    "\n" +
    "**analysis of metrics and output:**\n" +
    "\n" +
    "* **high sentiment score (28):** this is significantly higher than the target of 10, indicating excessive positivity.  humans rarely maintain such a relentlessly upbeat tone, especially when asking clarifying questions.  it feels forced and insincere.\n" +
    "\n" +
    "* **emotional range (0.16):** this low score suggests a lack of emotional variation. the response is consistently positive, lacking nuances of expression.  real human interactions involve a wider range of emotions, even within a single conversation.\n" +
    "\n" +
    "* **emotional balance (15.00):**  this metric is unclear without knowing its scale and interpretation. however, given the other metrics, it likely reflects the overwhelmingly positive sentiment.\n" +
    "\n" +
    "* **vocabulary variety (0.71):** this is relatively good, indicating a decent range of words. however, the phrasing is still somewhat formulaic.\n" +
    "\n" +
    "* **comparative score (0.3077):** this metric is also unclear without context.\n" +
    "\n" +
    "* **word count (91):**  a bit lengthy for a simple clarifying request.  brevity is often more human-like in casual conversation.\n" +
    "\n" +
    "\n" +
    "**ways to make the response more human-like:**\n" +
    "\n" +
    `1. **reduce the overwhelming positivity:**  the response is excessively enthusiastic.  a more natural approach would be to tone down the positive language.  instead of "i'd love to assist you," try something like "i'd be happy to help," or even a simple "i can help with that."  remove phrases like "i'm eager to help you in any way i can" and "i'm fully committed to making this experience as smooth and pleasant as possible for you." these are overly formal and lack genuine warmth.\n` +
    "\n" +
    '2. **introduce subtlety and nuance:**  add a touch of informality and personality.  for example, instead of "could you please provide a bit more detail," try "could you tell me a little more about what you need?" or "can you give me some more information on that?"\n' +
    "\n" +
    "3. **shorten the response:**  the length makes it feel robotic.  conciseness is key to human-like communication.  combine sentences, remove redundant phrases, and get straight to the point.\n" +
    "\n" +
    '4. **add a touch of self-deprecation or humility:**  a slightly self-deprecating remark can make the response feel more relatable. for example,  "i want to make sure i understand your needs perfectly – i sometimes miss things, so the more detail the better!"\n' +
    "\n" +
    "5. **vary sentence structure:**  the response uses mostly long, similar sentence structures.  varying sentence length and structure will make it sound more natural.\n" +
    "\n" +
    "**example of a more human-like response:**\n" +
    "\n" +
    `"thanks for reaching out!  to help me understand what you need, could you tell me a little more about it?  the more detail you can give me, the better i can assist you.  let me know what you're looking for."\n` +
    "\n" +
    "\n" +
    "by implementing these changes, the output will sound more natural, less robotic, and more genuinely helpful, achieving a more human-like interaction.  the key is to strike a balance between helpfulness and genuine, relatable communication.\n",
  rawsentiment: {
    score: 28,
    comparative: 0.3076923076923077,
    calculation: [
      { pleasant: 3 },  { committed: 1 },
      { help: 2 },      { like: 2 },
      { help: 2 },      { eager: 2 },
      { help: 2 },      { better: 2 },
      { share: 1 },     { please: 1 },
      { perfectly: 3 }, { want: 1 },
      { love: 3 },      { reaching: 1 },
      { thank: 2 }
    ],
    tokens: [
      "thank",     "you",         "for",        "reaching",  "out",
      "i'd",       "love",        "to",         "assist",    "you",
      "but",       "i",           "want",       "to",        "make",
      "sure",      "i",           "understand", "your",      "needs",
      "perfectly", "could",       "you",        "please",    "provide",
      "a",         "bit",         "more",       "detail",    "about",
      "what",      "you're",      "looking",    "for",       "the",
      "more",      "information", "you",        "share",     "the",
      "better",    "i",           "can",        "help",      "i'm",
      "eager",     "to",          "help",       "you",       "in",
      "any",       "way",         "i",          "can",       "is",
      "there",     "a",           "particular", "area",      "you'd",
      "like",      "to",          "explore",    "further",   "your",
      "input",     "will",        "help",       "me",        "tailor",
      "my",        "assistance",  "to",         "your",      "exact",
      "needs",     "i'm",         "fully",      "committed", "to",
      "making",    "this",        "experience", "as",        "smooth",
      "and",       "pleasant",    "as",         "possible",  "for",
      "you"
    ],
    words: [
      "pleasant",  "committed",
      "help",      "like",
      "help",      "eager",
      "help",      "better",
      "share",     "please",
      "perfectly", "want",
      "love",      "reaching",
      "thank"
    ],
    positive: [
      "pleasant",  "committed",
      "help",      "like",
      "help",      "eager",
      "help",      "better",
      "share",     "please",
      "perfectly", "want",
      "love",      "reaching",
      "thank"
    ],
    negative: []
  }
}
code evolved, testing new version...

它使用此 analysis 类在代码上得分更高。

经过 10 次迭代后,得分相当高:

final results:
latest version: 10
final sentiment score: 9
evolution patterns used: ["basic","responsive","interactive"]

最有趣的是它创建的图表:

import { StateGraph, END } from "npm:@langchain/langgraph";

const workflow = new StateGraph({
  channels: {
    input: "string",
    output: "string?",
    sentiment: "number",
    context: "object"
  }
});

const positiveWords = ["good", "nice", "helpful", "appreciate", "thanks", "pleased", "glad", "great", "happy", "excellent", "wonderful", "amazing", "fantastic"];
const negativeWords = ["issue", "problem", "difficult", "confused", "frustrated", "unhappy"];

workflow.addNode("analyzeInput", (state) => {
  const input = state.input.toLowerCase();
  let sentiment = input.split(" ").reduce((score, word) => {
    if (positiveWords.includes(word)) score += 1;
    if (negativeWords.includes(word)) score -= 1;
    return score;
  }, 0);
  sentiment = Math.min(Math.max(sentiment, -5), 5);
  return {
    ...state,
    sentiment,
    context: {
      needsClarification: sentiment === 0,
      isPositive: sentiment > 0,
      isNegative: sentiment < 0,
      topic: detectTopic(input),
      userName: extractUserName(input)
    }
  };
});

function detectTopic(input) {
  if (input.includes("technical") || input.includes("error")) return "technical";
  if (input.includes("product") || input.includes("service")) return "product";
  if (input.includes("billing") || input.includes("payment")) return "billing";
  return "general";
}

function extractUserName(input) {
  const nameMatch = input.match(/(?:my name is|i'm|i am) (\w+)/i);
  return nameMatch ? nameMatch[1] : "";
}

workflow.addNode("generateResponse", (state) => {
  let response = "";
  const userName = state.context.userName ? `${state.context.userName}` : "there";
  if (state.context.isPositive) {
    response = `Hey ${userName}! Glad to hear things are going well. What can I do to make your day even better?`;
  } else if (state.context.isNegative) {
    response = `Hi ${userName}. I hear you're facing some challenges. Let's see if we can turn things around. What's on your mind?`;
  } else {
    response = `Hi ${userName}! What's up? How can I help you today?`;
  }
  return { ...state, output: response };
});

workflow.addNode("interactiveFollowUp", (state) => {
  let followUp = "";
  switch (state.context.topic) {
    case "technical":
      followUp = `If you're having a technical hiccup, could you tell me what's happening? Any error messages or weird behavior?`;
      break;
    case "product":
      followUp = `Curious about our products? What features are you most interested in?`;
      break;
    case "billing":
      followUp = `For billing stuff, it helps if you can give me some details about your account or the charge you're asking about. Don't worry, I'll keep it confidential.`;
      break;
    default:
      followUp = `The more you can tell me, the better I can help. What's on your mind?`;
  }
  return { ...state, output: state.output + " " + followUp };
});

workflow.addNode("adjustSentiment", (state) => {
  const sentimentAdjusters = [
    "I'm here to help find a solution that works for you.",
    "Thanks for your patience as we figure this out.",
    "Your input really helps me understand the situation better.",
    "Let's work together to find a great outcome for you."
  ];
  const adjuster = sentimentAdjusters[Math.floor(Math.random() * sentimentAdjusters.length)];
  return { ...state, output: state.output + " " + adjuster };
});

workflow.addNode("addHumanTouch", (state) => {
  const humanTouches = [
    "By the way, hope your day's going well so far!",
    "Just a heads up, I'm an AI assistant still learning the ropes.",
    "Feel free to ask me to clarify if I say anything confusing.",
    "I appreciate your understanding as we work through this."
  ];
  const touch = humanTouches[Math.floor(Math.random() * humanTouches.length)];
  return { ...state, output: state.output + " " + touch };
});

workflow.setEntryPoint("analyzeInput");
workflow.addEdge("analyzeInput", "generateResponse");
workflow.addEdge("generateResponse", "interactiveFollowUp");
workflow.addEdge("interactiveFollowUp", "adjustSentiment");
workflow.addEdge("adjustSentiment", "addHumanTouch");
workflow.addEdge("addHumanTouch", END);

const graph = workflow.compile();
export { graph };

我看到它编写的这段代码,立即想到了以下陷阱:

突发的复杂性:

这是指简单组件交互产生的复杂性,在本例中是法学硕士的算法和它所训练的庞大数据集。 llm 可以生成的代码虽然功能强大,但表现出人类难以完全理解的复杂模式和依赖关系。

因此,如果我们可以稍微调整一下,并让它编写更干净、更简单的代码,我们可能就走在正确的轨道上。

无论如何,这只是一个实验,因为我想使用 langgraphs 新的命令功能。

请在评论中告诉我你的想法。

相关专题

更多
js正则表达式
js正则表达式

php中文网为大家提供各种js正则表达式语法大全以及各种js正则表达式使用的方法,还有更多js正则表达式的相关文章、相关下载、相关课程,供大家免费下载体验。

510

2023.06.20

js获取当前时间
js获取当前时间

JS全称JavaScript,是一种具有函数优先的轻量级,解释型或即时编译型的编程语言;它是一种属于网络的高级脚本语言,主要用于Web,常用来为网页添加各式各样的动态功能。js怎么获取当前时间呢?php中文网给大家带来了相关的教程以及文章,欢迎大家前来学习阅读。

244

2023.07.28

js 字符串转数组
js 字符串转数组

js字符串转数组的方法:1、使用“split()”方法;2、使用“Array.from()”方法;3、使用for循环遍历;4、使用“Array.split()”方法。本专题为大家提供js字符串转数组的相关的文章、下载、课程内容,供大家免费下载体验。

254

2023.08.03

js是什么意思
js是什么意思

JS是JavaScript的缩写,它是一种广泛应用于网页开发的脚本语言。JavaScript是一种解释性的、基于对象和事件驱动的编程语言,通常用于为网页增加交互性和动态性。它可以在网页上实现复杂的功能和效果,如表单验证、页面元素操作、动画效果、数据交互等。

5271

2023.08.17

js删除节点的方法
js删除节点的方法

js删除节点的方法有:1、removeChild()方法,用于从父节点中移除指定的子节点,它需要两个参数,第一个参数是要删除的子节点,第二个参数是父节点;2、parentNode.removeChild()方法,可以直接通过父节点调用来删除子节点;3、remove()方法,可以直接删除节点,而无需指定父节点;4、innerHTML属性,用于删除节点的内容。

477

2023.09.01

js截取字符串的方法
js截取字符串的方法

js截取字符串的方法有substring()方法、substr()方法、slice()方法、split()方法和slice()方法。本专题为大家提供字符串相关的文章、下载、课程内容,供大家免费下载体验。

206

2023.09.04

Js中concat和push的区别
Js中concat和push的区别

Js中concat和push的区别:1、concat用于将两个或多个数组合并成一个新数组,并返回这个新数组,而push用于向数组的末尾添加一个或多个元素,并返回修改后的数组的新长度;2、concat不会修改原始数组,是创建新的数组,而push会修改原数组,将新元素添加到原数组的末尾等等。本专题为大家提供concat和push相关的文章、下载、课程内容,供大家免费下载体验。

217

2023.09.14

js截取字符串的方法介绍
js截取字符串的方法介绍

JavaScript字符串截取方法,包括substring、slice、substr、charAt和split方法。这些方法可以根据具体需求,灵活地截取字符串的不同部分。在实际开发中,根据具体情况选择合适的方法进行字符串截取,能够提高代码的效率和可读性 。

218

2023.09.21

Golang gRPC 服务开发与Protobuf实战
Golang gRPC 服务开发与Protobuf实战

本专题系统讲解 Golang 在 gRPC 服务开发中的完整实践,涵盖 Protobuf 定义与代码生成、gRPC 服务端与客户端实现、流式 RPC(Unary/Server/Client/Bidirectional)、错误处理、拦截器、中间件以及与 HTTP/REST 的对接方案。通过实际案例,帮助学习者掌握 使用 Go 构建高性能、强类型、可扩展的 RPC 服务体系,适用于微服务与内部系统通信场景。

8

2026.01.15

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
相关推荐
/
热门推荐
/
最新课程
10分钟--Midjourney创作自己的漫画
10分钟--Midjourney创作自己的漫画

共1课时 | 0.1万人学习

Midjourney 关键词系列整合
Midjourney 关键词系列整合

共13课时 | 0.9万人学习

AI绘画教程
AI绘画教程

共2课时 | 0.2万人学习

关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号