Compare commits

...

6 Commits

Author SHA1 Message Date
Kevin Dang
9247463480 hardcoded and mentions
* added options to queries

* removed hard coded vals, added message options

* updated importing

* added check for message mentions

* fix missing botID

* updated token to uid

* added contributer

---------

Co-authored-by: JT2M0L3Y <jtsmoley@icloud.com>
2024-01-29 12:50:59 -08:00
Kevin Dang
97acae3d08 added embed msg and stream parser 2024-01-28 12:59:45 -08:00
Kevin Dang
aaf734b06c added ollamajs esm 2024-01-25 18:24:37 -08:00
Kevin Dang
78921ee571 added persistence in chat endpoint 2024-01-23 22:24:26 -08:00
Kevin Dang
f8956b0b50 bot can edit message response 2024-01-23 21:26:39 -08:00
Kevin Dang
70103c1f5a readme ollama setup 2024-01-22 23:24:32 -08:00
13 changed files with 265 additions and 70 deletions

18
.gitignore vendored
View File

@@ -1,10 +1,13 @@
# Credentials
.env
.dev.env
# Created by https://www.toptal.com/developers/gitignore/api/node
# Edit at https://www.toptal.com/developers/gitignore?templates=node
# dotenv environment variable files
.env
.env.dev.local
.env.test.local
.env.production.local
.env.local
### Node ###
# Logs
logs
@@ -80,13 +83,6 @@ web_modules/
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

View File

@@ -1,9 +1,23 @@
# Discord Ollama Integration [![License: CC BY-NC 4.0](https://img.shields.io/badge/License-CC_BY--NC_4.0-darkgreen.svg)](https://creativecommons.org/licenses/by-nc/4.0/) [![Release Badge](https://img.shields.io/github/v/release/kevinthedang/discord-ollama?logo=github)](https://github.com/kevinthedang/discord-ollama/releases/latest)
Ollama is an AI model management tool that allows users to install and use custom large language models locally. The goal is to create a discord bot that will utilize Ollama and chat with it on a Discord!
## Ollama Setup
* Go to Ollama's [Linux download page](https://ollama.ai/download/linux) and run the simple curl command they provide. The command should be `curl https://ollama.ai/install.sh | sh`.
* Now the the following commands in separate terminals to test out how it works!
* In terminal 1 -> `ollama serve` to setup ollama
* In terminal 2 -> `ollama run [model name]`, for example `ollama run llama2`
* The models can vary as you can create your own model. You can also view ollama's [library](https://ollama.ai/library) of models.
* This can also be done in [wsl](https://learn.microsoft.com/en-us/windows/wsl/install) for Windows machines.
* You can now interact with the model you just ran (it might take a second to startup).
* Response time varies with processing power!
## To Run
* Clone this repo using `git clone https://github.com/kevinthedang/discord-ollama.git` or just use [GitHub Desktop](https://desktop.github.com/) to clone the repo.
* You can run the bot by running `npm run start` which will build and run the decompiled typescript.
* Run `npm install` to install the npm packages.
* You will need a `.env` file in the root of the project directory with the bot's token.
* For example, `CLIENT_TOKEN = [Bot Token]`
* Now, you can run the bot by running `npm run start` which will build and run the decompiled typescript and run the setup for ollama.
* **IMPORTANT**: This must be ran in the wsl/Linux instance to work properly! Using Command Prompt/Powershell/Git Bash/etc. will not work on Windows (at least in my experience).
* Refer to the [resources](#resources) on what node version to use.
## Resources
@@ -13,10 +27,11 @@ Ollama is an AI model management tool that allows users to install and use custo
* To run dev with `tsx`, you can use `v20.10.0` or earlier.
* This project supports any NodeJS version above `16.x.x` to only allow ESModules.
* [Ollama](https://ollama.ai/)
* [Docker Documentation](https://docs.docker.com/?_gl=1*nof6f8*_ga*MTQxNTc1MTYxOS4xNzAxNzI1ODAx*_ga_XJWPQMJYHQ*MTcwMjQxODUzOS4yLjEuMTcwMjQxOTgyMC41OS4wLjA.)
* [Discord Developer Portal](https://discord.com/developers/docs/intro)
* [Discord.js Docs](https://discord.js.org/docs/packages/discord.js/main)
## Acknowledgement
* [Kevin Dang](https://github.com/kevinthedang)
* [Jonathan Smoley](https://github.com/JT2M0L3Y)
[discord-ollama](https://github.com/kevinthedang/discord-ollama) © 2023 by [Kevin Dang](https://github.com/kevinthedang) is licensed under [CC BY-NC 4.0](https://creativecommons.org/licenses/by-nc/4.0/?ref=chooser-v1)

20
package-lock.json generated
View File

@@ -1,18 +1,19 @@
{
"name": "discord-ollama",
"version": "0.0.1",
"version": "0.1.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "discord-ollama",
"version": "0.0.1",
"version": "0.1.1",
"license": "ISC",
"dependencies": {
"axios": "^1.6.2",
"concurrently": "^8.2.2",
"discord.js": "^14.14.1",
"dotenv": "^16.3.1"
"dotenv": "^16.3.1",
"ollama": "^0.4.3"
},
"devDependencies": {
"@types/node": "^20.10.5",
@@ -1312,6 +1313,14 @@
"node": ">=0.10.0"
}
},
"node_modules/ollama": {
"version": "0.4.3",
"resolved": "https://registry.npmjs.org/ollama/-/ollama-0.4.3.tgz",
"integrity": "sha512-l8RtRp5uKhvqbAmA9n5PS4ZW1RPbA2CPSlNinJ+jVQYD36UjxPQphEPxp0etH/wqY26nHyM6HQEHatIfrW0+Tw==",
"dependencies": {
"whatwg-fetch": "^3.6.20"
}
},
"node_modules/picomatch": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
@@ -1598,6 +1607,11 @@
"integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==",
"dev": true
},
"node_modules/whatwg-fetch": {
"version": "3.6.20",
"resolved": "https://registry.npmjs.org/whatwg-fetch/-/whatwg-fetch-3.6.20.tgz",
"integrity": "sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg=="
},
"node_modules/wrap-ansi": {
"version": "7.0.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",

View File

@@ -1,6 +1,6 @@
{
"name": "discord-ollama",
"version": "0.0.1",
"version": "0.1.2",
"description": "Ollama Integration into discord",
"main": "dist/index.js",
"exports": "./dist/index.js",
@@ -19,7 +19,8 @@
"axios": "^1.6.2",
"concurrently": "^8.2.2",
"discord.js": "^14.14.1",
"dotenv": "^16.3.1"
"dotenv": "^16.3.1",
"ollama": "^0.4.3"
},
"devDependencies": {
"@types/node": "^20.10.5",

View File

@@ -5,6 +5,7 @@ import Events from "./events/index.js";
// Import keys/tokens
import Keys from "./keys.js";
// initialize the client with the following permissions when logging in
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
@@ -14,7 +15,21 @@ const client = new Client({
]
});
registerEvents(client, Events)
const messageHistory = [
{
role: 'system',
content: 'Your name is Ollama GU'
}
]
/**
* register events for bot to listen to in discord
* @param messageHistory message history for the llm
* @param Events events to register
* @param client the bot reference
* @param Keys tokens from .env files
*/
registerEvents(client, Events, messageHistory, Keys)
// Try to log in the client
client.login(Keys.clientToken)

View File

@@ -1,42 +1,39 @@
import { event, Events } from '../utils/index.js'
import Axios from 'axios'
import { embedMessage, event, Events } from '../utils/index.js'
/*
/**
* Max Message length for free users is 2000 characters (bot or not).
* @param message the message received from the channel
*/
export default event(Events.MessageCreate, ({ log }, message) => {
export default event(Events.MessageCreate, async ({ log, msgHist, tokens }, message) => {
log(`Message created \"${message.content}\" from ${message.author.tag}.`)
// Hard-coded channel to test output there only, in our case "ollama-endpoint"
if (message.channelId != '1188262786497785896') {
log(`Unauthorized Channel input, Aborting...`)
return
}
log(`Channel id OK!`)
if (message.channelId != tokens.channel) return
// Do not respond if bot talks in the chat
if (message.author.tag === message.client.user.tag) {
log(`Found Bot message reply, Aborting...`)
return
}
log(`Sender Checked!`)
if (message.author.tag === message.client.user.tag) return
// Request made to API
const request = async () => {
try {
const response = await Axios.post('http://127.0.0.1:11434/api/generate', {
model: 'llama2',
prompt: message.content,
stream: false
})
log(response.data)
//
message.reply(response.data['response'])
} catch (error) {
log(error)
}
}
// Attempt to call ollama's endpoint
request()
// Only respond if message mentions the bot
if (!message.mentions.has(tokens.botUid)) return
// push user response
msgHist.push({
role: 'user',
content: message.content
})
// Try to query and send embed
const response = await embedMessage(message, tokens, msgHist)
// Try to query and send message
// log(normalMessage(message, tokens, msgHist))
// If something bad happened, remove user query and stop
if (response == undefined) { msgHist.pop(); return }
// successful query, save it as history
msgHist.push({
role: 'assistant',
content: response.message.content
})
})

View File

@@ -1,7 +1,10 @@
import { getEnvVar } from "./utils/env.js"
export const Keys = {
clientToken: getEnvVar('CLIENT_TOKEN')
clientToken: getEnvVar('CLIENT_TOKEN'),
channel: getEnvVar('CHANNEL_ID'),
model: getEnvVar('MODEL'),
botUid: getEnvVar('BOT_UID')
} as const // readonly keys
export default Keys

View File

@@ -2,7 +2,7 @@ import { resolve } from "path"
import { config } from "dotenv"
// Find config - ONLY WORKS WITH NODEMON
const envFile = process.env.NODE_ENV === "development" ? ".dev.env" : ".env"
const envFile = process.env.NODE_ENV === "development" ? ".env.dev.local" : ".env"
// resolve config file
const envFilePath = resolve(process.cwd(), envFile)

View File

@@ -1,43 +1,58 @@
import type { ClientEvents, Awaitable, Client } from 'discord.js';
import type { ClientEvents, Awaitable, Client } from 'discord.js'
// Export events through here to reduce amount of imports
export { Events } from 'discord.js';
export { Events } from 'discord.js'
export type LogMethod = (...args: unknown[]) => void;
export type EventKeys = keyof ClientEvents; // only wants keys of ClientEvents object
export type LogMethod = (...args: unknown[]) => void
export type EventKeys = keyof ClientEvents // only wants keys of ClientEvents object
// Event properties
export interface EventProps {
client: Client;
log: LogMethod;
client: Client
log: LogMethod
msgHist: { role: string, content: string }[]
tokens: {
channel: string,
model: string,
botUid: string
}
}
export type EventCallback<T extends EventKeys> = (
props: EventProps,
...args: ClientEvents[T]
) => Awaitable<unknown>; // Method can be synchronous or async, unknown so we can return anything
) => Awaitable<unknown> // Method can be synchronous or async, unknown so we can return anything
// Event interface
export interface Event<T extends EventKeys = EventKeys> {
key: T;
callback: EventCallback<T>;
key: T
callback: EventCallback<T>
}
export function event<T extends EventKeys>(key: T, callback: EventCallback<T>): Event<T> {
return { key, callback };
return { key, callback }
}
export function registerEvents(client: Client, events: Event[]): void {
export function registerEvents(
client: Client,
events: Event[],
msgHist: { role: string, content: string }[],
tokens: {
channel: string,
model: string,
botUid: string
}
): void {
for (const { key, callback } of events) {
client.on(key, (...args) => {
// Create a new log method for this event
const log = console.log.bind(console, `[Event: ${key}]`);
const log = console.log.bind(console, `[Event: ${key}]`)
// Handle Errors, call callback, log errors as needed
try {
callback({ client, log }, ...args);
callback({ client, log, msgHist, tokens }, ...args)
} catch (error) {
log('[Uncaught Error]', error);
log('[Uncaught Error]', error)
}
});
})
}
}

View File

@@ -1,3 +1,5 @@
// Centralized import index
export * from './env.js';
export * from './events.js';
export * from './env.js'
export * from './events.js'
export * from './messageEmbed.js'
export * from './messageNormal.js'

66
src/utils/messageEmbed.ts Normal file
View File

@@ -0,0 +1,66 @@
import { EmbedBuilder, Message } from "discord.js";
import ollama, { ChatResponse } from "ollama";
/**
* Method to send replies as normal text on discord like any other user
* @param message message sent by the user
* @param tokens tokens to run query
* @param msgHist message history between user and model
*/
export async function embedMessage(
message: Message,
tokens: {
channel: string,
model: string
},
msgHist: {
role: string,
content: string
}[]
) {
// bot response
let response: ChatResponse
// initial message to client
const botMessage = new EmbedBuilder()
.setTitle(`Responding to ${message.author.tag}`)
.setDescription('Generating Response . . .')
.setColor('#00FF00')
// send the message
const sentMessage = await message.channel.send({ embeds: [botMessage] })
try {
// Attempt to query model for message
response = await ollama.chat({
model: tokens.model,
messages: msgHist,
options: {
num_thread: 8, // remove if optimization needed further
mirostat: 1,
mirostat_tau: 2.0,
top_k: 70
},
stream: false
})
const newEmbed = new EmbedBuilder()
.setTitle(`Responding to ${message.author.tag}`)
.setDescription(response.message.content)
.setColor('#00FF00')
// edit the message
sentMessage.edit({ embeds: [newEmbed] })
} catch(error: any) {
const errorEmbed = new EmbedBuilder()
.setTitle(`Responding to ${message.author.tag}`)
.setDescription(error.error)
.setColor('#00FF00')
// send back error
sentMessage.edit({ embeds: [errorEmbed] })
}
// Hope there is a response! undefined otherwie
return response!!
}

View File

@@ -0,0 +1,48 @@
import { Message } from "discord.js";
import ollama, { ChatResponse } from "ollama";
/**
* Method to send replies as normal text on discord like any other user
* @param message message sent by the user
* @param tokens tokens to run query
* @param msgHist message history between user and model
*/
export function normalMessage(
message: Message,
tokens: {
channel: string,
model: string
},
msgHist: {
role: string,
content: string
}[]
) {
// bot's respnse
let response: ChatResponse
message.reply('Generating Response . . .').then(async sentMessage => {
try {
// Attempt to query model for message
response = await ollama.chat({
model: tokens.model,
messages: msgHist,
options: {
num_thread: 8, // remove if optimization needed further
mirostat: 1,
mirostat_tau: 2.0,
top_k: 70
},
stream: false
})
// edit the 'generic' response to new message
sentMessage.edit(response.message.content)
} catch(error: any) {
sentMessage.edit(error.error)
}
})
// Hope there is a response, force client to believe
return response!!
}

23
src/utils/streamParse.ts Normal file
View File

@@ -0,0 +1,23 @@
import { AxiosResponse } from "axios";
/**
* When running a /api/chat stream, the output needs to be parsed into an array of objects
* @param stream Axios response to from Ollama
*/
export function parseStream(stream: AxiosResponse<any, any>) {
// split string by newline
const keywordObjects: string[] = stream.data.trim().split('\n')
// parse string and load them into objects
const keywordsArray: {
model: string,
created_at: string,
message: {
role: string,
content: string
},
done: boolean
}[] = keywordObjects.map((keywordString) => JSON.parse(keywordString))
return keywordsArray
}