React Integration - janardhanhere/langgraph-deployment-kit GitHub Wiki

React Integration

This guide explains how to integrate LangGraph Deployment Kit with React using the agent-react-hook package.

Installing the Hook

npm install agent-react-hook

Basic Usage

Here's a simple example of using the hook in a React component:

import React, { useState } from 'react';
import useAgent from 'agent-react-hook';

function ChatComponent() {
  const [inputValue, setInputValue] = useState('');
  
  const {
    messages,
    currentTokens,
    isLoading,
    error,
    submit
  } = useAgent({
    baseUrl: 'http://localhost:8000',
    apiKey: 'your-api-key' // Optional
  });

  const handleSubmit = (e) => {
    e.preventDefault();
    if (inputValue.trim() && !isLoading) {
      submit(inputValue);
      setInputValue('');
    }
  };

  return (
    <div>
      <div>
        {messages.map((msg, idx) => (
          <div key={idx}>
            <strong>{msg.type}:</strong> {msg.content}
          </div>
        ))}
        
        {isLoading && currentTokens && (
          <div>
            <strong>AI (typing):</strong> {currentTokens}
          </div>
        )}
      </div>
      
      {error && <div style={{color: 'red'}}>{error}</div>}
      
      <form onSubmit={handleSubmit}>
        <input
          value={inputValue}
          onChange={(e) => setInputValue(e.target.value)}
          placeholder="Type a message..."
          disabled={isLoading}
        />
        <button type="submit" disabled={!inputValue.trim() || isLoading}>
          Send
        </button>
      </form>
    </div>
  );
}

Advanced Configuration

The useAgent hook accepts many configuration options:

const {
  messages,
  currentTokens,
  nodeUpdates,
  isLoading,
  threadId,
  error,
  submit,
  stop,
  reset
} = useAgent({
  baseUrl: 'http://localhost:8000',
  agentId: 'my-agent',            // Which agent to use (matches the name in agents.py)
  threadId: 'existing-thread-id', // For continuing conversations
  userId: 'user123',              // User identifier
  sessionId: 'session456',        // Session identifier
  model: 'gpt-4',                 // Model override
  apiKey: 'your-api-key',         // Authentication
  streamTokens: true,             // Enable token streaming
  streamNodeUpdates: true,        // Enable node updates
  agentConfig: {                  // Additional agent config
    temperature: 0.7,
    max_tokens: 2000
  },
  // Callbacks
  onToken: (token) => console.log('Token:', token),
  onMessage: (msg) => console.log('Message:', msg), 
  onNodeUpdate: (update) => console.log('Update:', update),
  onError: (err) => console.error('Error:', err),
  onFinish: () => console.log('Done'),
  onThreadId: (id) => console.log('Thread ID:', id)
});

Displaying "Thinking" Process

One powerful feature is the ability to display the agent's internal thinking process using node updates:

{showThinking && Object.keys(nodeUpdates).length > 0 && (
  <div className="thinking-panel">
    <h3>Agent Thinking Process</h3>
    <div>
      {Object.entries(nodeUpdates).map(([node, data]) => (
        <div key={node}>
          <h4>{node}</h4>
          <pre>{JSON.stringify(data, null, 2)}</pre>
        </div>
      ))}
    </div>
  </div>
)}

Example Project

Check out the example project in the examples/useagenthookexample directory for a complete implementation.

⚠️ **GitHub.com Fallback** ⚠️