Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

I want to make an chatbot app like chatgpt using chatgpt api key so generate app.js file…

  1. User

    I want to make an chatbot app like chatgpt using chatgpt api key so generate app.js file code because i make app in react native expo, make it beautiful and minimal give me correct code which 100% works

  2. Assistant

    Certainly! Below is a minimal and beautiful App.js file for your React Native Expo app that creates a chatbot using the ChatGPT API. This code is designed to work seamlessly and should serve as a solid foundation for your chatbot application.


    App.js

    import React, { useState } from 'react';
    import {
      SafeAreaView,
      StyleSheet,
      TextInput,
      TouchableOpacity,
      Text,
      View,
      FlatList,
      KeyboardAvoidingView,
      Platform,
    } from 'react-native';
    
    const OPENAI_API_KEY = 'YOUR_OPENAI_API_KEY';
    
    export default function App() {
      const [messages, setMessages] = useState([
        { id: '1', text: 'Hello! How can I assist you today?', sender: 'bot' },
      ]);
      const [inputText, setInputText] = useState('');
    
      const sendMessage = async () => {
        if (inputText.trim() === '') return;
    
        const userMessage = {
          id: Date.now().toString(),
          text: inputText,
          sender: 'user',
        };
    
        setMessages([...messages, userMessage]);
        setInputText('');
    
        try {
          const response = await fetch('https://api.openai.com/v1/chat/completions', {
            method: 'POST',
            headers: {
              'Authorization': `Bearer ${OPENAI_API_KEY}`,
              'Content-Type': 'application/json',
            },
            body: JSON.stringify({
              model: 'gpt-3.5-turbo',
              messages: [{ role: 'user', content: inputText }],
            }),
          });
    
          const data = await response.json();
          const botMessage = {
            id: Date.now().toString() + 'bot',
            text: data.choices[0].message.content.trim(),
            sender: 'bot',
          };
    
          setMessages((prevMessages) => [...prevMessages, botMessage]);
        } catch (error) {
          console.error('Error:', error);
        }
      };
    
      const renderItem = ({ item }) => (
        <View style={[styles.messageContainer, item.sender === 'user' ? styles.userMessage : styles.botMessage]}>
          <Text style={styles.messageText}>{item.text}</Text>
        </View>
      );
    
      return (
        <SafeAreaView style={styles.container}>
          <FlatList
            data={messages}
            renderItem={renderItem}
            keyExtractor={(item) => item.id}
            contentContainerStyle={styles.chatContainer}
          />
          <KeyboardAvoidingView behavior={Platform.OS === 'ios' ? 'padding' : undefined}>
            <View style={styles.inputContainer}>
              <TextInput
                style={styles.input}
                placeholder="Type your message..."
                value={inputText}
                onChangeText={setInputText}
                multiline
              />
              <TouchableOpacity style={styles.sendButton} onPress={sendMessage}>
                <Text style={styles.buttonText}>Send</Text>
              </TouchableOpacity>
            </View>
          </KeyboardAvoidingView>
        </SafeAreaView>
      );
    }
    
    const styles = StyleSheet.create({
      container: {
        flex: 1,
      },
      chatContainer: {
        padding: 10,
        paddingBottom: 70,
      },
      messageContainer: {
        marginVertical: 5,
        maxWidth: '80%',
        alignSelf: 'flex-start',
        padding: 10,
        borderRadius: 10,
      },
      userMessage: {
        backgroundColor: '#DCF8C6',
        alignSelf: 'flex-end',
      },
      botMessage: {
        backgroundColor: '#ECECEC',
      },
      messageText: {
        fontSize: 16,
        color: '#333',
      },
      inputContainer: {
        position: 'absolute',
        bottom: 0,
        flexDirection: 'row',
        padding: 10,
        backgroundColor: '#FFFFFF',
        alignItems: 'flex-end',
      },
      input: {
        flex: 1,
        maxHeight: 100,
        borderRadius: 20,
        paddingHorizontal: 15,
        paddingVertical: 10,
        backgroundColor: '#F0F0F0',
        fontSize: 16,
      },
      sendButton: {
        marginLeft: 10,
        backgroundColor: '#007AFF',
        borderRadius: 20,
        paddingVertical: 10,
        paddingHorizontal: 20,
      },
      buttonText: {
        color: '#FFFFFF',
        fontSize: 16,
      },
    });
    

    Instructions:

    1. Replace the API Key:

      • Replace 'YOUR_OPENAI_API_KEY' with your actual OpenAI API key.
      • For security, consider using environment variables or a secure storage solution to store your API key instead of hardcoding it.
    2. Install Dependencies:

      • Ensure you have Expo CLI installed:
        npm install -g expo-cli
        
      • Initialize a new Expo project (if you haven't already):
        expo init my-chatbot-app
        
      • Navigate to your project directory:
        cd my-chatbot-app
        
      • Install any additional dependencies if necessary.
    3. Run the App:

      • Start your app:
        expo start
        
      • Use an emulator or the Expo Go app on your device to run the application.

    Explanation:

    • State Management:

      • messages: An array of message objects containing id, text, and sender.
      • inputText: The current text in the input field.
    • sendMessage Function:

      • Checks if the input is not empty.
      • Adds the user's message to the messages array.
      • Sends a POST request to the OpenAI ChatGPT API with the user's message.
      • Receives and processes the response, then updates the messages array with the bot's reply.
    • Rendering Messages:

      • Uses FlatList to render messages efficiently.
      • renderItem function styles messages based on the sender.
    • UI Components:

      • SafeAreaView: Ensures content is rendered within the safe area boundaries of a device.
      • FlatList: Displays the chat messages.
      • TextInput: For user to type messages.
      • TouchableOpacity: Send button to trigger sendMessage.
      • KeyboardAvoidingView: Adjusts the view to avoid the keyboard overlapping the input field.
    • Styling:

      • Clean and minimal styles are applied via StyleSheet.
      • Different background colors are used to distinguish between user and bot messages.
      • The layout is responsive and adjusts to different screen sizes.

    Notes:

    • Error Handling:

      • Basic error handling is included with try-catch.
      • In a production app, you might want to display an error message to the user if the fetch fails.
    • Asynchronous Behavior:

      • The sendMessage function is async to handle the asynchronous API call.
    • Security Considerations:

      • API Key Protection: Never commit your API keys to a public repository. Use environment variables or a secure key management system for production apps.
      • Data Privacy: Be mindful of the data sent to the API. Avoid sending sensitive information.

    Example Output:

    When you run the app, you'll see the initial bot message:

    Hello! How can I assist you today?
    

    You can type into the input field, and upon pressing "Send," your message will appear, followed by the bot's response.

    Customization:

    • UI Enhancements:

      • You can further enhance the UI by adding avatars, timestamps, or customizing fonts.
      • Consider adding loading indicators while waiting for the bot's response.
    • Functionality:

      • Maintain a conversation history by sending the entire message array to the API if desired.
      • Implement additional features like typing indicators or message status.

    Feel free to ask if you need further assistance or customization. Happy coding!