Create a Simple Chatbot Using ChatGPT API in React Native

preview_player
Показать описание
0:00 - Tutorial
6:00 - Bonus: Using Markdown
6:58 - Bonus: Typing indicator

----------------------------------------------------------------

npm install react-native-gifted-chat --save
npm install react-native-uuid
npm install openai --save
npm install react-native-dotenv --save

Optional:

npm install react-native-markdown-display

add:

plugins: ['module:react-native-dotenv'],

like so:

return {
presets: ['babel-preset-expo'],
plugins: ['module:react-native-dotenv'],
};
};

To get your API Key:

The code will be in the comments.
Рекомендации по теме
Комментарии
Автор

Code:


import React, { useState, useCallback, useEffect } from 'react'
import { GiftedChat } from 'react-native-gifted-chat';
import uuid from 'react-native-uuid';
import OpenAI from "openai";
import Markdown from

const openai = new OpenAI({ apiKey: OPENAI_API_KEY });

const error = console.error;
console.error = (...args) => { if return; error(...args); }; // Ignore warning of Gifted Chat


export function ChatScreen() {
const [messages, setMessages] = useState([])
const [isTyping, setIsTyping] = useState(false);

const test = async (userMessage) => {
try {
setIsTyping(true);
const completion = await
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: userMessage }
],
model: "gpt-4o-mini",
});

const aiMessage =
const newMessage = {
_id: uuid.v4(), // Random ID
text: aiMessage,
createdAt: new Date(),
user: {
_id: 2,
name: 'AI Assistant',
},
};

setMessages(previousMessages => GiftedChat.append(previousMessages, [newMessage]));
} catch (error) {
console.error(error);
} finally {
setIsTyping(false);
}
}

const onSend = useCallback((messages = []) => {
setMessages(previousMessages => GiftedChat.append(previousMessages, messages));
const userMessage = messages[0].text;
test(userMessage);
}, [])


const CustomMessageText = (props) => {
const { currentMessage } = props;
const textColor = currentMessage.user._id === 1 ? "white" : "black";

return (
<Markdown style={{
body: {
marginHorizontal: 10,
fontSize: 16,
color: textColor,
},
lineHeight: 20,
marginTop: 5,
marginBottom: 5,
marginLeft: 10,
marginRight: 10,
}}>
{currentMessage.text}
</Markdown>
);
}


return (
<GiftedChat
messages={messages}
onSend={messages => onSend(messages)}
user={{
_id: 1,
}}

isTyping={isTyping}
/>
)
}

export default ChatScreen;

Devving_Horizon
Автор

i face below error

error [Error: 404 Invalid URL (POST /v1/chat/completions/)]

QuranMajeed