찾다
웹 프론트엔드JS 튜토리얼자가 작성 언어 그래프 상태

Self Writing Lang Graph State

첫 번째 AI 응답:

출력: 문의해 주셔서 감사합니다. 나는 당신을 도와주고 싶지만, 당신의 필요를 완벽하게 이해하고 있는지 확인하고 싶습니다. 찾고 있는 항목에 대해 좀 더 자세히 설명해 주시겠습니까? 더 많은 정보를 공유할수록 더 나은 도움을 드릴 수 있습니다! 나는 내가 할 수 있는 어떤 방법으로든 당신을 돕고 싶습니다. 더 자세히 탐구하고 싶은 특정 영역이 있나요? 귀하의 의견은 귀하의 정확한 필요에 맞게 지원을 맞춤화하는 데 도움이 됩니다. 저는 이 경험을 최대한 원활하고 즐겁게 만들기 위해 최선을 다하고 있습니다.

AI 응답, 자체 그래프 작성 후:

출력: 안녕하세요! 무슨 일이야? 오늘은 무엇을 도와드릴까요? 더 많이 말씀해 주시면 더 잘 도와드릴 수 있습니다. 무슨 생각을 하고 있나요? 저는 귀하에게 적합한 솔루션을 찾는 데 도움을 드리고자 왔습니다. 미리 말씀드리지만 저는 아직 요령을 배우고 있는 AI 비서입니다.

정말 놀랍죠?

거의 인간처럼 들립니다. 주말 동안 van wilder guy와 함께 영화 Free Guy를 보고 깨달았습니다. @langchain/langgraph의 The GraphState를 사용하면 자체적으로 반복을 수행하고 자체 코드를 작성할 수 있는 AI를 만들 수 있을 것이라는 사실을 깨달았습니다.

지금까지 깨닫지 못했다면 Claude Sonnet은 0샷 코딩에 매우 능숙하고, 멀티샷에는 더욱 뛰어납니다.

라이브러리 사용 npm:sentiment :

README.md에서

Sentiment는 AFINN-165 단어 목록과 Emoji Sentiment Ranking을 사용하여 임의의 입력 텍스트 블록에 대한 감정 분석을 수행하는 Node.js 모듈입니다.

출력에 대한 감정 분석을 실행하고 더 높은 점수를 얻기 위해 코드를 새 버전으로 발전시키는 간단한 명령을 그래프 상태에 추가했습니다.

// 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
    });

작업할 수 있는 초기 그래프 상태로 langgraph를 시드합니다(원하는 경우 기본 코드).

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 };
`;

모서리 하나가 붙어 있는 정말 기본적인 응답 노드임을 알 수 있습니다.

현재 코드는 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...

이 분석 클래스를 사용하여 코드에서 더 높은 점수를 얻습니다.

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  {
  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의 알고리즘과 학습된 방대한 데이터 세트)의 상호 작용으로 인해 발생하는 복잡성을 나타냅니다. LLM은 기능적이지만 사람이 완전히 이해하기 어려운 복잡한 패턴과 종속성을 나타내는 코드를 생성할 수 있습니다.

따라서 이 문제를 조금 뒤로 돌려 더 깔끔하고 더 간단한 코드를 작성할 수 있다면 올바른 방향으로 가고 있는 것일 수도 있습니다.

어쨌든 이것은 단지 실험일 뿐입니다. 왜냐하면 저는 Langgraphs의 새로운 명령 기능을 사용하고 싶었기 때문입니다.

댓글로 여러분의 생각을 알려주세요.

위 내용은 자가 작성 언어 그래프 상태의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Node.js는 TypeScript가있는 스트림입니다Node.js는 TypeScript가있는 스트림입니다Apr 30, 2025 am 08:22 AM

Node.js는 크림 덕분에 효율적인 I/O에서 탁월합니다. 스트림은 메모리 오버로드를 피하고 큰 파일, 네트워크 작업 및 실시간 애플리케이션을위한 메모리 과부하를 피하기 위해 데이터를 점차적으로 처리합니다. 스트림을 TypeScript의 유형 안전과 결합하면 Powe가 생성됩니다

Python vs. JavaScript : 성능 및 효율성 고려 사항Python vs. JavaScript : 성능 및 효율성 고려 사항Apr 30, 2025 am 12:08 AM

파이썬과 자바 스크립트 간의 성능과 효율성의 차이는 주로 다음과 같이 반영됩니다. 1) 해석 된 언어로서, 파이썬은 느리게 실행되지만 개발 효율이 높고 빠른 프로토 타입 개발에 적합합니다. 2) JavaScript는 브라우저의 단일 스레드로 제한되지만 멀티 스레딩 및 비동기 I/O는 Node.js의 성능을 향상시키는 데 사용될 수 있으며 실제 프로젝트에서는 이점이 있습니다.

JavaScript의 기원 : 구현 언어 탐색JavaScript의 기원 : 구현 언어 탐색Apr 29, 2025 am 12:51 AM

JavaScript는 1995 년에 시작하여 Brandon Ike에 의해 만들어졌으며 언어를 C로 실현했습니다. 1.C Language는 JavaScript의 고성능 및 시스템 수준 프로그래밍 기능을 제공합니다. 2. JavaScript의 메모리 관리 및 성능 최적화는 C 언어에 의존합니다. 3. C 언어의 크로스 플랫폼 기능은 자바 스크립트가 다른 운영 체제에서 효율적으로 실행하는 데 도움이됩니다.

무대 뒤에서 : 어떤 언어의 힘이 자바 스크립트입니까?무대 뒤에서 : 어떤 언어의 힘이 자바 스크립트입니까?Apr 28, 2025 am 12:01 AM

JavaScript는 브라우저 및 Node.js 환경에서 실행되며 JavaScript 엔진을 사용하여 코드를 구문 분석하고 실행합니다. 1) 구문 분석 단계에서 초록 구문 트리 (AST)를 생성합니다. 2) 컴파일 단계에서 AST를 바이트 코드 또는 기계 코드로 변환합니다. 3) 실행 단계에서 컴파일 된 코드를 실행하십시오.

파이썬과 자바 스크립트의 미래 : 트렌드와 예측파이썬과 자바 스크립트의 미래 : 트렌드와 예측Apr 27, 2025 am 12:21 AM

Python 및 JavaScript의 미래 추세에는 다음이 포함됩니다. 1. Python은 과학 컴퓨팅 분야에서의 위치를 ​​통합하고 AI, 2. JavaScript는 웹 기술의 개발을 촉진하고, 3. 교차 플랫폼 개발이 핫한 주제가되고 4. 성능 최적화가 중점을 둘 것입니다. 둘 다 해당 분야에서 응용 프로그램 시나리오를 계속 확장하고 성능이 더 많은 혁신을 일으킬 것입니다.

Python vs. JavaScript : 개발 환경 및 도구Python vs. JavaScript : 개발 환경 및 도구Apr 26, 2025 am 12:09 AM

개발 환경에서 Python과 JavaScript의 선택이 모두 중요합니다. 1) Python의 개발 환경에는 Pycharm, Jupyternotebook 및 Anaconda가 포함되어 있으며 데이터 과학 및 빠른 프로토 타이핑에 적합합니다. 2) JavaScript의 개발 환경에는 Node.js, VScode 및 Webpack이 포함되어 있으며 프론트 엔드 및 백엔드 개발에 적합합니다. 프로젝트 요구에 따라 올바른 도구를 선택하면 개발 효율성과 프로젝트 성공률이 향상 될 수 있습니다.

JavaScript가 C로 작성 되었습니까? 증거를 검토합니다JavaScript가 C로 작성 되었습니까? 증거를 검토합니다Apr 25, 2025 am 12:15 AM

예, JavaScript의 엔진 코어는 C로 작성되었습니다. 1) C 언어는 효율적인 성능과 기본 제어를 제공하며, 이는 JavaScript 엔진 개발에 적합합니다. 2) V8 엔진을 예를 들어, 핵심은 C로 작성되며 C의 효율성 및 객체 지향적 특성을 결합하여 C로 작성됩니다.

JavaScript의 역할 : 웹 대화식 및 역동적 인 웹JavaScript의 역할 : 웹 대화식 및 역동적 인 웹Apr 24, 2025 am 12:12 AM

JavaScript는 웹 페이지의 상호 작용과 역학을 향상시키기 때문에 현대 웹 사이트의 핵심입니다. 1) 페이지를 새로 고치지 않고 콘텐츠를 변경할 수 있습니다. 2) Domapi를 통해 웹 페이지 조작, 3) 애니메이션 및 드래그 앤 드롭과 같은 복잡한 대화식 효과를 지원합니다. 4) 성능 및 모범 사례를 최적화하여 사용자 경험을 향상시킵니다.

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

VSCode Windows 64비트 다운로드

VSCode Windows 64비트 다운로드

Microsoft에서 출시한 강력한 무료 IDE 편집기

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

Dreamweaver Mac版

Dreamweaver Mac版

시각적 웹 개발 도구

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구