DEV Community

Apollo
Apollo

Posted on

How to integrate DeepSeek R1 into your React app

Integrating DeepSeek R1 into Your React App: A Comprehensive Guide

DeepSeek R1 is a powerful AI-driven API that enables developers to integrate advanced natural language processing (NLP) capabilities into their applications. In this tutorial, we'll walk you through the process of integrating DeepSeek R1 into a React application. By the end of this guide, you'll have a fully functional React app that leverages DeepSeek R1's capabilities for text analysis, sentiment detection, and more.

Prerequisites

Before we begin, ensure you have the following:

  1. Node.js and npm installed on your machine.
  2. A DeepSeek R1 API key. You can obtain this by signing up on the DeepSeek platform.
  3. Basic knowledge of React and JavaScript.

Setting Up Your React App

First, let's create a new React app using create-react-app.

npx create-react-app deepseek-react-integration
cd deepseek-react-integration
Enter fullscreen mode Exit fullscreen mode

Next, install the necessary dependencies:

npm install axios react-bootstrap bootstrap
Enter fullscreen mode Exit fullscreen mode

Here, we're installing axios for making HTTP requests and react-bootstrap along with bootstrap for styling our app.

Configuring the DeepSeek R1 API

Create a new file named .env in the root of your project:

REACT_APP_DEEPSEEK_API_KEY=your_api_key_here
Enter fullscreen mode Exit fullscreen mode

Replace your_api_key_here with your actual DeepSeek R1 API key. This environment variable will be used to authenticate requests to the DeepSeek API.

Creating the DeepSeek Service

Now, let's create a service to handle interactions with the DeepSeek R1 API. Create a new file src/services/deepseek.js:

import axios from 'axios';

const DEEPSEEK_API_URL = 'https://api.deepseek.com/v1/r1';
const API_KEY = process.env.REACT_APP_DEEPSEEK_API_KEY;

const deepseekClient = axios.create({
  baseURL: DEEPSEEK_API_URL,
  headers: {
    'Authorization': `Bearer ${API_KEY}`,
    'Content-Type': 'application/json',
  },
});

export const analyzeText = async (text) => {
  try {
    const response = await deepseekClient.post('/analyze', { text });
    return response.data;
  } catch (error) {
    console.error('Error analyzing text:', error);
    throw error;
  }
};
Enter fullscreen mode Exit fullscreen mode

Here, we've set up an axios instance with the base URL for the DeepSeek API and the necessary headers, including the authorization token. The analyzeText function sends a POST request to the /analyze endpoint with the provided text.

Building the UI Component

Let's create a simple UI component that allows users to input text and see the analysis results. Create a new file src/components/DeepSeekAnalyzer.js:

import React, { useState } from 'react';
import { Button, Form, Card } from 'react-bootstrap';
import { analyzeText } from '../services/deepseek';

const DeepSeekAnalyzer = () => {
  const [text, setText] = useState('');
  const [analysisResult, setAnalysisResult] = useState(null);
  const [isLoading, setIsLoading] = useState(false);

  const handleSubmit = async (e) => {
    e.preventDefault();
    setIsLoading(true);
    try {
      const result = await analyzeText(text);
      setAnalysisResult(result);
    } catch (error) {
      console.error('Error:', error);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <Card>
      <Card.Body>
        <Form onSubmit={handleSubmit}>
          <Form.Group className="mb-3">
            <Form.Label>Enter Text to Analyze</Form.Label>
            <Form.Control
              as="textarea"
              rows={3}
              value={text}
              onChange={(e) => setText(e.target.value)}
              placeholder="Type your text here..."
            />
          </Form.Group>
          <Button type="submit" disabled={isLoading}>
            {isLoading ? 'Analyzing...' : 'Analyze'}
          </Button>
        </Form>
        {analysisResult && (
          <div className="mt-3">
            <h5>Analysis Result</h5>
            <pre>{JSON.stringify(analysisResult, null, 2)}</pre>
          </div>
        )}
      </Card.Body>
    </Card>
  );
};

export default DeepSeekAnalyzer;
Enter fullscreen mode Exit fullscreen mode

In this component, we use React hooks (useState) to manage the text input, analysis result, and loading state. When the form is submitted, the analyzeText function from our service is called, and the result is displayed in a formatted JSON block.

Integrating the Component into the App

Finally, integrate the DeepSeekAnalyzer component into your main app. Open src/App.js and replace its content with the following:

import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import DeepSeekAnalyzer from './components/DeepSeekAnalyzer';

function App() {
  return (
    <div className="container mt-5">
      <h1 className="text-center mb-4">DeepSeek R1 Integration with React</h1>
      <DeepSeekAnalyzer />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Here, we're importing our DeepSeekAnalyzer component and Bootstrap's CSS for styling. The component is centered in the page with a title.

Running the Application

You can now run your React app to see the integration in action:

npm start
Enter fullscreen mode Exit fullscreen mode

Open your browser and navigate to http://localhost:3000. You should see the text input form. Enter some text, click "Analyze," and you'll receive detailed analysis from the DeepSeek R1 API.

Conclusion

Congratulations! You've successfully integrated DeepSeek R1 into your React application. This powerful API can now be used for various NLP tasks within your app, enhancing its capabilities and providing users with advanced text analysis features.

Feel free to expand upon this foundation by integrating additional DeepSeek endpoints, improving the UI, or adding more sophisticated error handling. Happy coding!


🚀 Stop Writing Boilerplate Prompts

If you want to skip the setup and code 10x faster with complete AI architecture patterns, grab my Senior React Developer AI Cookbook ($19). It includes Server Action prompt libraries, UI component generation loops, and hydration debugging strategies.

Browse all 10+ developer products at the Apollo AI Store | Or snipe Solana tokens free via @ApolloSniper_Bot.

Top comments (0)