Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
9 views5 pages

AI Chatbot App Code

The document provides code for an AI chatbot application using Android and Retrofit for API communication. It includes dependencies, layout XML for the chat interface, Java classes for chat messages and adapter, and the main activity that handles user input and API requests. The chatbot utilizes OpenAI's API to send and receive messages, displaying them in a RecyclerView.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views5 pages

AI Chatbot App Code

The document provides code for an AI chatbot application using Android and Retrofit for API communication. It includes dependencies, layout XML for the chat interface, Java classes for chat messages and adapter, and the main activity that handles user input and API requests. The chatbot utilizes OpenAI's API to send and receive messages, displaying them in a RecyclerView.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 5

AI Chatbot App Code

Open AI

dependencies {
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
implementation 'androidx.recyclerview:recyclerview:1.3.1'
implementation 'androidx.appcompat:appcompat:1.6.1'
}

activity_chatbot.xml

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">

<!-- RecyclerView to display chat messages -->


<androidx.recyclerview.widget.RecyclerView
android:id="@+id/recyclerViewChat"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="@android:color/white"
android:padding="8dp" />

<!-- Input layout for user message -->


<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:paddingTop="8dp">

<EditText
android:id="@+id/editTextMessage"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Type your message..."
android:inputType="text" />

<Button
android:id="@+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Send" />
</LinearLayout>
</LinearLayout>

ChatMessage.Java

public class ChatMessage {


private String sender;
private String message;

public ChatMessage(String sender, String message) {


this.sender = sender;
this.message = message;
}

public String getSender() {


return sender;
}

public String getMessage() {


return message;
}
}

ChatAdapter.Java

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.List;

public class ChatAdapter extends RecyclerView.Adapter<ChatAdapter.ViewHolder> {


private List<ChatMessage> chatMessages;

public ChatAdapter(List<ChatMessage> chatMessages) {


this.chatMessages = chatMessages;
}

@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view =
LayoutInflater.from(parent.getContext()).inflate(android.R.layout.simple_list_item_
2, parent, false);
return new ViewHolder(view);
}

@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
ChatMessage message = chatMessages.get(position);
holder.textSender.setText(message.getSender());
holder.textMessage.setText(message.getMessage());
}

@Override
public int getItemCount() {
return chatMessages.size();
}

public static class ViewHolder extends RecyclerView.ViewHolder {


TextView textSender;
TextView textMessage;

public ViewHolder(@NonNull View itemView) {


super(itemView);
textSender = itemView.findViewById(android.R.id.text1);
textMessage = itemView.findViewById(android.R.id.text2);
}
}
}

ChatbotActivity Activity

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.POST;

public class ChatbotActivity extends AppCompatActivity {


private RecyclerView recyclerViewChat;
private EditText editTextMessage;
private Button buttonSend;
private ChatAdapter chatAdapter;
private List<ChatMessage> chatMessages = new ArrayList<>();

private static final String API_KEY = "your_openai_api_key";


private static final String BASE_URL = "https://api.openai.com/v1/";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chatbot);
recyclerViewChat = findViewById(R.id.recyclerViewChat);
editTextMessage = findViewById(R.id.editTextMessage);
buttonSend = findViewById(R.id.buttonSend);

// Set up RecyclerView
chatAdapter = new ChatAdapter(chatMessages);
recyclerViewChat.setLayoutManager(new LinearLayoutManager(this));
recyclerViewChat.setAdapter(chatAdapter);

// Send button click listener


buttonSend.setOnClickListener(v -> {
String userMessage = editTextMessage.getText().toString().trim();
if (!userMessage.isEmpty()) {
// Add user message to the chat
chatMessages.add(new ChatMessage("You", userMessage));
chatAdapter.notifyDataSetChanged();
recyclerViewChat.smoothScrollToPosition(chatMessages.size() - 1);

// Clear input field


editTextMessage.setText("");

// Send message to the chatbot API


sendMessageToChatbot(userMessage);
}
});
}

private void sendMessageToChatbot(String userMessage) {


Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build();

OpenAIApiService service = retrofit.create(OpenAIApiService.class);

OpenAIApiService.ChatRequest.Message[] messages = {
new OpenAIApiService.ChatRequest.Message("user", userMessage)
};
OpenAIApiService.ChatRequest request = new
OpenAIApiService.ChatRequest(messages);

Call<OpenAIApiService.ChatResponse> call = service.sendMessage("Bearer " +


API_KEY, request);
call.enqueue(new Callback<OpenAIApiService.ChatResponse>() {
@Override
public void onResponse(Call<OpenAIApiService.ChatResponse> call,
Response<OpenAIApiService.ChatResponse> response) {
if (response.isSuccessful() && response.body() != null) {
String botReply = response.body().choices[0].message.content;

// Add bot reply to the chat


chatMessages.add(new ChatMessage("Bot", botReply));
chatAdapter.notifyDataSetChanged();
recyclerViewChat.smoothScrollToPosition(chatMessages.size() -
1);
}
}

@Override
public void onFailure(Call<OpenAIApiService.ChatResponse> call,
Throwable t) {
t.printStackTrace();
}
});
}

interface OpenAIApiService {
@POST("chat/completions")
Call<ChatResponse> sendMessage(@Header("Authorization") String auth, @Body
ChatRequest request);

class ChatRequest {
String model = "gpt-3.5-turbo";
Message[] messages;

ChatRequest(Message[] messages) {
this.messages = messages;
}
}

class Message {
String role;
String content;

Message(String role, String content) {


this.role = role;
this.content = content;
}
}

class ChatResponse {
String id;
String object;
Message[] choices;
}
}
}

You might also like