A simple AI-powered chat console built using React, TypeScript, and the GPT-4 API. This app allows users to interact with an AI model by typing messages and receiving responses, all in a conversational interface.
- Real-time communication with the AI model.
- Allows users to type messages and hit "Enter" to trigger a response.
- Displays loading state while waiting for the AI response.
- Displays error messages if something goes wrong.
- User messages and AI responses are shown in a chat-like interface.
- React: A JavaScript library for building user interfaces.
- TypeScript: A statically typed superset of JavaScript.
- Axios: A promise-based HTTP client for making requests to the AI model API.
- CSS-in-JS: For styling the components using plain JavaScript objects.
git clone https://github.com/suhasmanjunath/react-ts-useaimodel.git
cd react-ts-useaimodel
Make sure you have Node.js and npm (or Yarn) installed. Then run the following command:
npm install
or if you're using Yarn:
yarn install
The app uses the GPT-4 API via RapidAPI. You’ll need to sign up for a RapidAPI key to access the service.
- Go to RapidAPI GPT-4 API.
- Get your API key.
- Replace the
x-rapidapi-key
in the code with your own API key:- Open
useAIModel.tsx
and find the line:
'x-rapidapi-key': 'your-api-key-here',
- Open
Run the app in development mode:
npm start
This will open the app in your browser at http://localhost:3000
.
- Enter your query in the input box at the bottom of the screen.
- Press Enter or click Send to send your query.
- The AI model will respond with an answer which will appear in the chat window.
/src
/components
App.tsx # Main component containing the chat interface
App.styles.tsx # Styling objects for the components
/hooks
useAIModel.tsx # Custom hook to interact with the AI model API
index.tsx # Entry point for the React app
The custom hook useAIModel
handles the communication with the AI model API:
- Takes
apiUrl
(API endpoint) andquery
(user input) as arguments. - Returns:
messages
: Array of messages, including the user's input and AI's response.loading
: A boolean to indicate if the response is being fetched.error
: Error message if an issue occurs.
const { messages, loading, error } = useAIModel({
apiUrl: "https://gpt-4o.p.rapidapi.com/chat/completions",
query: "Hello, AI!",
});
- Fork the repository.
- Create a new branch (
git checkout -b feature-branch
). - Make your changes and commit them (
git commit -am 'Add new feature'
). - Push to the branch (
git push origin feature-branch
). - Create a pull request.
This project is open-source and available under the MIT License.