Skip to content

Commit

Permalink
Merge pull request #10 from langx:xuelink/issue6
Browse files Browse the repository at this point in the history
Add Appwrite Functionality for LangX Copilot with POST Request Support
  • Loading branch information
xuelink authored May 28, 2024
2 parents 1351ab0 + 3dfdab3 commit 9d0bbbc
Show file tree
Hide file tree
Showing 8 changed files with 167 additions and 26 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,4 @@ dist
.pnp.*

# instructions file
/utils/instructions.js
instructions.js
41 changes: 17 additions & 24 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,10 @@ You can try out LangX Copilot in the [#copilot channel](https://discord.langx.io

## What can it do?

- :construction: **Grammar Correction**: The bot can correct grammar mistakes in your messages.
- :hourglass_flowing_sand: **Suggest Next Message**: The bot can suggest what to say next based on the context of the conversation.
- :hourglass_flowing_sand: **Better Way to Say**: The bot can suggest a better way to express your thoughts.
- :hourglass_flowing_sand: **Suggest New Topic**: The bot can suggest a new topic of conversation when the current topic has been exhausted.
- :construction: **Grammar Correction**: The bot can correct grammar mistakes in your messages.
- :hourglass_flowing_sand: **And more**: The bot has many more features to explore!

You can try it out in the [#copilot channel](https://discord.langx.io) on Discord.
Expand All @@ -36,55 +36,48 @@ You can try it out in the [#copilot channel](https://discord.langx.io) on Discor

### Installation

#### Application

1. **Clone the repository**:

```sh
git clone https://github.com/langx/copilot.git
git clone
cd copilot
```

2. **Install dependencies**:

```sh
npm install
```

3. **Copy `.env` file** with the following environment variables:
2. **Copy `.env` file** with the following environment variables:

```sh
cp .env.sample .env
```

4. **Fill in the environment variables** in the `.env` file:
3. **Fill in the environment variables** in the `.env` file:

```sh
DISCORD_BOT_TOKEN=your_discord_token
DISCORD_CLIENT_ID=your_discord_client_id
GEMINI_API_KEY=your_gemini_api_key
```

5. **Set up the system instructions:**
4. Copy instructions.js.sample to instructions.js and fill in your instructions:

```sh
cd utils
cp instructions.js.sample instructions.js
```

Open the `instructions.js` file in your preferred text editor and edit the `systemInstruction` and `chatHistory` constant to include your own instructions.

6. **Run the application**:
5. Prepare the environment by running the prebuild script:

```sh
npm start discord
npm run prebuild
```

7. **Deploy the Bot (Optional)**:
6. **Deploy Appwrite Functions**:

```sh
npm i pm2 -g
node discord/registerCommands.js
pm2 start discord/bot.js --name copilot
```
Deploy the Appwrite functions, ensuring that the environment variables are correctly set during the deployment process. We utilize Git integration for deployment. For more information on deploying Appwrite functions, refer to the [Appwrite Functions Documentation](https://appwrite.io/docs/advanced/self-hosting/functions).

#### Setting Up the Discord Bot

Detailed instructions for installing and configuring the Discord bot are provided in a separate document. This includes steps for setting up your environment, configuring the bot, and deploying it to a server.

Please refer to the [Discord Bot Documentation](discord/README.md) for more information.

## Contributing

Expand Down
8 changes: 7 additions & 1 deletion copilot/aiHandler.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import dotenv from "dotenv";

import { genAI, safetySettings } from "../utils/common.js";
import { systemInstruction, chatHistory } from "../utils/instructions.js";

dotenv.config();

const systemInstruction = process.env.SYSTEM_INSTRUCTION;
const chatHistory = process.env.CHAT_HISTORY;

const model = genAI.getGenerativeModel({
model: "gemini-1.5-pro-latest",
Expand Down
88 changes: 88 additions & 0 deletions discord/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# :robot: LangX Copilot

## Discord Bot Documentation

LangX Copilot is an innovative AI-powered tool designed to enhance your language learning journey. This feature-rich platform offers personalized feedback to improve your language skills in real-time. LangX Copilot ensures your privacy while providing corrections and explanations directly to you.

## Demo

You can try out LangX Copilot in the [#copilot channel](https://discord.langx.io) on Discord.

![Example](../assets/example.png)

## Features

- **Personalized Feedback**: Get real-time corrections and explanations to enhance your language learning.
- **Grammar Correction**: Automatically corrects grammar mistakes and provides detailed explanations.
- **Privacy Focused**: Feedback is provided confidentially, ensuring your privacy is maintained.
- **Supports Multiple Languages**: Not limited to English, LangX Copilot supports various languages for grammar correction.

## Getting Started

### Prerequisites

- Node.js (version 18 or later)
- npm (Node Package Manager)
- Cloudflare account with Workers enabled
- Discord account and bot set up in the Discord Developer Portal

### Installation

1. **Clone the repository**:

```sh
git clone https://github.com/langx/copilot.git
cd copilot
```

2. **Install dependencies**:

```sh
npm install
```

3. **Copy `.env` file** with the following environment variables:

```sh
cp .env.sample .env
```

4. **Fill in the environment variables** in the `.env` file:

```sh
DISCORD_BOT_TOKEN=your_discord_token
DISCORD_CLIENT_ID=your_discord_client_id
GEMINI_API_KEY=your_gemini_api_key
```

5. **Set up the system instructions:**

```sh
cp instructions.js.sample instructions.js
```

Open the `instructions.js` file in your preferred text editor and edit the `systemInstruction` and `chatHistory` constant to include your own instructions.

6. **Run the application**:

```sh
npm start discord
```

7. **Deploy the Bot (Optional)**:

```sh
npm i pm2 -g
node discord/registerCommands.js
pm2 start discord/bot.js --name copilot
```

## Contributing

Feel free to contribute to this project and help us improve LangX Copilot. You can contribute by opening a PR or creating an issue easily.

We welcome all contributions, including bug fixes, new features, and improvements to the documentation.

## License

This project is licensed under BSD 3-Clause License. See the [LICENSE](LICENSE) file for more details.
7 changes: 7 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { handleInteraction } from "./copilot/aiHandler.js";

export default async function ({ req, res, log, error }) {
try {
// Log a message
Expand All @@ -12,6 +14,11 @@ export default async function ({ req, res, log, error }) {
if (req.method === "GET") {
// Send a JSON response
return res.json({ message: "Hello, World!" });
} else if (req.method === "POST") {
// Handle POST request
const userMessage = req.body.message;
const aiResponse = await handleInteraction(userMessage);
return res.json({ response: aiResponse });
} else {
// Handle other HTTP methods if necessary
return res.send("Unsupported request method", 405);
Expand Down
File renamed without changes.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"type": "module",
"description": "An introduction to LangX Copilot, an AI-powered tool designed to enhance your language learning experience with personalized feedback and privacy-focused features.",
"scripts": {
"prebuild": "node setup_env.js",
"discord": "node discord/registerCommands.js && node discord/bot.js"
},
"repository": {
Expand Down
46 changes: 46 additions & 0 deletions setup_env.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import fs from "fs";
import { systemInstruction, chatHistory } from "./instructions.js";

const envFilePath = new URL(".env", import.meta.url);
let envContent = "";

try {
// Read the existing .env file content
envContent = fs.readFileSync(envFilePath, "utf8");
} catch (error) {
if (error.code !== "ENOENT") {
throw error;
}
}

// Convert the instructions to an environment variable format
const systemInstructionValue = systemInstruction
.replace(/'/g, "\\'")
.replace(/\n/g, "\\n");
const chatHistoryValue = JSON.stringify(chatHistory)
.replace(/'/g, "\\'")
.replace(/\n/g, "\\n");

const systemInstructionEnv = `SYSTEM_INSTRUCTION='${systemInstructionValue}'`;
const chatHistoryEnv = `CHAT_HISTORY='${chatHistoryValue}'`;

// Function to update or add environment variable in .env content
const updateEnvVariable = (content, variable, value) => {
const regex = new RegExp(`^${variable}=.*$`, "m");
if (regex.test(content)) {
return content.replace(regex, value);
} else {
return content + "\n" + value;
}
};

// Update or append the variables
envContent = updateEnvVariable(
envContent,
"SYSTEM_INSTRUCTION",
systemInstructionEnv
);
envContent = updateEnvVariable(envContent, "CHAT_HISTORY", chatHistoryEnv);

// Write the updated .env file
fs.writeFileSync(envFilePath, envContent, { flag: "w" });

0 comments on commit 9d0bbbc

Please sign in to comment.