You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular对接LangChain Agent Executor添加聊天历史报错排查

Angular对接LangChain Agent Executor问题解决与示例

BaseMessage的type属性有效值

LangChain的BaseMessage类型中,type属性仅支持以下固定枚举值,传入其他值会触发类型错误:

  • human:用户发送的消息
  • ai:AI返回的消息
  • system:系统提示类消息
  • function:函数调用相关消息
  • tool:工具返回的消息

你遇到的TypeError大概率是因为前端传入的ChatMessage的type值不在上述范围内,或是大小写不匹配(比如用user代替human)。

Angular对接LangChain Agent Executor示例代码

1. 定义TypeScript接口(匹配LangChain的Pydantic Schema)

// 匹配LangChain BaseMessage的标准接口
interface BaseMessage {
  type: 'human' | 'ai' | 'system' | 'function' | 'tool';
  content: string;
  name?: string; // 函数/工具消息场景下必填
  additional_kwargs?: Record<string, any>; // 扩展字段,可选
}

// Agent接口的输入参数结构
interface AgentInput {
  input: string;
  chat_history?: BaseMessage[];
}

2. 前端ChatMessage类(带格式转换方法)

export class ChatMessage {
  constructor(public content: string, public isUser: boolean) {}

  // 转换为LangChain要求的BaseMessage格式
  toBaseMessage(): BaseMessage {
    return {
      type: this.isUser ? 'human' : 'ai',
      content: this.content
    };
  }
}

3. Agent服务层实现(发送请求到后端)

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { AgentInput, BaseMessage } from './interfaces';
import { ChatMessage } from './chat-message';

@Injectable({ providedIn: 'root' })
export class AgentService {
  private apiUrl = '/api/langchain-agent'; // 替换为你的后端接口地址

  constructor(private http: HttpClient) {}

  sendMessage(input: string, chatHistory: ChatMessage[]): Observable<any> {
    // 将前端聊天历史转换为LangChain可识别的格式
    const formattedHistory: BaseMessage[] = chatHistory.map(msg => msg.toBaseMessage());
    
    const agentRequest: AgentInput = {
      input,
      chat_history: formattedHistory
    };

    return this.http.post(this.apiUrl, agentRequest);
  }
}

4. 聊天组件调用示例

import { Component } from '@angular/core';
import { ChatMessage } from './chat-message';
import { AgentService } from './agent.service';

@Component({
  selector: 'app-chat',
  template: `
    <div class="chat-box">
      <div *ngFor="let msg of messages" 
           [class.user-bubble]="msg.isUser" 
           [class.ai-bubble]="!msg.isUser">
        {{ msg.content }}
      </div>
      <input [(ngModel)]="userInput" 
             placeholder="输入消息..." 
             (keyup.enter)="sendMessage()">
      <button (click)="sendMessage()">发送</button>
    </div>
  `,
  styles: [`
    .user-bubble { text-align: right; margin: 8px; padding: 10px; background: #e3f2fd; border-radius: 12px; }
    .ai-bubble { text-align: left; margin: 8px; padding: 10px; background: #f5f5f5; border-radius: 12px; }
  `]
})
export class ChatComponent {
  userInput = '';
  messages: ChatMessage[] = [];

  constructor(private agentService: AgentService) {}

  sendMessage() {
    if (!this.userInput.trim()) return;
    
    // 添加用户消息到界面
    const userMsg = new ChatMessage(this.userInput, true);
    this.messages.push(userMsg);
    
    // 调用Agent接口
    this.agentService.sendMessage(this.userInput, this.messages)
      .subscribe({
        next: (res) => {
          // 添加AI回复到界面
          const aiMsg = new ChatMessage(res.output, false);
          this.messages.push(aiMsg);
        },
        error: (err) => {
          console.error('请求失败:', err);
          this.messages.push(new ChatMessage('请求出错,请稍后重试', false));
        }
      });
    
    this.userInput = '';
  }
}

关键注意事项

  • 若涉及函数/工具调用,需补充name和additional_kwargs字段,示例如下:
    {
      type: 'function',
      content: '',
      name: 'get_user_info',
      additional_kwargs: {
        arguments: JSON.stringify({ userId: 1001 })
      }
    }
    
  • 后端需确保用LangChain原生的BaseMessage类解析传入的聊天历史,避免类型不兼容。

内容的提问来源于stack exchange,提问作者Michael Rosario

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 03:57:46