casper's Profile Image

Full Stack Web/Mobile Developer

Nov, 25, 2024

React Native Ai Chatbot Tutorial With Grok Api

If you want to make an ai chatbot like chatgpt this post will help you.

React Native Ai Chatbot Tutorial With Grok Api Image

You can also watch the YouTube video:

React Native AI Chatbot Tutorial with Grok Api

We'll use Grok Api to make AI Chatbot in our React Native app. I'll use ShadCN UI with React Native Reusables but you don't have to use it.

You can use React Native CLI, Expo, whatever you want.

If you'll use ShadCN UI like me then we need to clone react native reusables repository:

git clone https://github.com/mrzachnugent/react-native-reusables.git

Then copy the starter base and rename it:

cp -R react-native-reusables/packages/templates/starter-base/ ./rn-ai-chatbot

install the dependencies, and fix packages if needed.

cd rn-ai-chatbot && yarn install && npx expo install --fix

Enable new arch support in app.json to avoid future warnings.

{
    "expo": {
        "newArchEnabled": true,
        ...
    }
}

Run the project

yarn android

Our React Native app ready to build. Now we need to sign in/sign up x.ai to get our api key.

You don't need to sign up if you have X (aka Twitter) account. You can sign in with your X account.

X AI gives us $25 USD free credit to explore the Grok Api.

You can find and create api keys from console.x.ai

Now we can build a ai chatbot with our api key.

We'll need a few dependencies we can install them before we start:

yarn add react-native-keyboard-aware-scroll-view

And

npx @react-native-reusables/cli@latest add skeleton input

Now we can edit our app/index.tsx to achieve final result:

import * as React from "react";
import { ScrollView, View } from "react-native";
import { KeyboardAwareScrollView } from "react-native-keyboard-aware-scroll-view";
import { Button } from "~/components/ui/button";
import {
  Card,
  CardContent,
  CardFooter,
  CardHeader,
  CardTitle,
} from "~/components/ui/card";
import { Input } from "~/components/ui/input";
import { Skeleton } from "~/components/ui/skeleton";
import { Text } from "~/components/ui/text";

interface IMessage {
  role: string;
  content: string;
  id: number;
}

export default function Screen() {
  const [message, setMessage] = React.useState("");
  const [messages, setMessages] = React.useState<IMessage[]>([]);
  const [loading, setLoading] = React.useState(false);

  const onChangeText = (text: string) => {
    setMessage(text);
  };

  const sendMessage = async () => {
    try {
      setLoading(true);

      setMessages((prevMessages) => [
        ...prevMessages,
        {
          role: "user",
          content: message,
          id: Math.floor(100000000 + Math.random() * 900000000),
        },
      ]);

      const response = await fetch("https://api.x.ai/v1/chat/completions", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          Authorization: `Bearer YOUR_API_KEY_HERE`,
        },
        body: JSON.stringify({
          messages: [
            {
              role: "system",
              content:
                "You are Grok, a chatbot inspired by the Hitchhikers Guide to the Galaxy.",
            },
            {
              role: "user",
              content: message,
            },
          ],
          model: "grok-beta",
          stream: false,
          temperature: 0,
        }),
      });

      const data = await response.json();

      setMessages((prevMessages) => [
        ...prevMessages,
        {
          role: data.choices[0].message.role,
          content: data.choices[0].message.content,
          id: Math.floor(100000000 + Math.random() * 900000000),
        },
      ]);

      setLoading(false);

      setMessage("");
    } catch (error) {
      console.error("Error:", error);
    }
  };

  return (
    <View className="flex-1 justify-center items-center gap-5 p-6 bg-secondary/30">
      <Card className="w-full h-full max-w-sm p-6 rounded-2xl">
        <CardHeader className="items-center">
          <View className="p-3" />
          <CardTitle className="pb-2 text-center">
            AI Chatbot with Grok API
          </CardTitle>
        </CardHeader>
        <KeyboardAwareScrollView>
          <CardContent>
            <ScrollView className="min-h-[480px] max-h-[480px]">
              {loading ? <Skeleton className="h-48 w-72" /> : null}
              {[...messages].reverse()?.map((message) => (
                <Card key={message.id} className="mt-8">
                  <CardHeader>
                    <CardTitle>
                      {message.role === "assistant" ? "Grok 🤖" : "Me 🧑"}
                    </CardTitle>
                  </CardHeader>

                  <CardContent>
                    <Text className="text-black dark:text-white">{message.content}</Text>
                  </CardContent>
                </Card>
              ))}
            </ScrollView>
          </CardContent>

          <CardFooter className="mt-8">
            <Input
              placeholder="Write some stuff..."
              value={message}
              onChangeText={onChangeText}
              aria-labelledby="inputLabel"
              aria-errormessage="inputError"
            />

            <Button
              disabled={loading}
              variant="outline"
              className="shadow shadow-foreground/5"
              onPress={sendMessage}
            >
              <Text className="text-black dark:text-white">{loading ? "Loading" : "Send"}</Text>
            </Button>
          </CardFooter>
        </KeyboardAwareScrollView>
      </Card>
    </View>
  );
}

Now we can use our ai chatbot to get answers for our questions.

I hope you found this post useful, thnx for reading.

0
0

Comments (0)