Commit ·
f914bbe
0
Parent(s):
Duplicate from freddyaboulton/llama2-70b-discord-bot
Browse filesCo-authored-by: Freddy Boulton <freddyaboulton@users.noreply.huggingface.co>
Files changed (4)
- .gitattributesAdded+35
- README.mdAdded+15
- app.pyAdded+206
- requirements.txtAdded+1
1234567891011121314151617181920212223242526272829303132333435*.7z filter=lfs diff=lfs merge=lfs -text*.arrow filter=lfs diff=lfs merge=lfs -text*.bin filter=lfs diff=lfs merge=lfs -text*.bz2 filter=lfs diff=lfs merge=lfs -text*.ckpt filter=lfs diff=lfs merge=lfs -text*.ftz filter=lfs diff=lfs merge=lfs -text*.gz filter=lfs diff=lfs merge=lfs -text*.h5 filter=lfs diff=lfs merge=lfs -text*.joblib filter=lfs diff=lfs merge=lfs -text*.lfs.* filter=lfs diff=lfs merge=lfs -text*.mlmodel filter=lfs diff=lfs merge=lfs -text*.model filter=lfs diff=lfs merge=lfs -text*.msgpack filter=lfs diff=lfs merge=lfs -text*.npy filter=lfs diff=lfs merge=lfs -text*.npz filter=lfs diff=lfs merge=lfs -text*.onnx filter=lfs diff=lfs merge=lfs -text*.ot filter=lfs diff=lfs merge=lfs -text*.parquet filter=lfs diff=lfs merge=lfs -text*.pb filter=lfs diff=lfs merge=lfs -text*.pickle filter=lfs diff=lfs merge=lfs -text*.pkl filter=lfs diff=lfs merge=lfs -text*.pt filter=lfs diff=lfs merge=lfs -text*.pth filter=lfs diff=lfs merge=lfs -text*.rar filter=lfs diff=lfs merge=lfs -text*.safetensors filter=lfs diff=lfs merge=lfs -textsaved_model/**/* filter=lfs diff=lfs merge=lfs -text*.tar.* filter=lfs diff=lfs merge=lfs -text*.tar filter=lfs diff=lfs merge=lfs -text*.tflite filter=lfs diff=lfs merge=lfs -text*.tgz filter=lfs diff=lfs merge=lfs -text*.wasm filter=lfs diff=lfs merge=lfs -text*.xz filter=lfs diff=lfs merge=lfs -text*.zip filter=lfs diff=lfs merge=lfs -text*.zst filter=lfs diff=lfs merge=lfs -text*tfevents* filter=lfs diff=lfs merge=lfs -text123456789101112131415---title: Llama2 70b Discord Botemoji: 🏆colorFrom: greencolorTo: greensdk: gradiosdk_version: 3.38.0app_file: app.pypinned: falsetags:- gradio-discord-botduplicated_from: freddyaboulton/llama2-70b-discord-bot---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206import asyncioimport osimport threadingfrom threading import Eventfrom typing import Optional
import discordimport gradio as grfrom discord import Permissionsfrom discord.ext import commandsfrom discord.utils import oauth_url
import gradio_client as grcfrom gradio_client.utils import QueueError
event = Event()
DISCORD_TOKEN = os.getenv("DISCORD_TOKEN")
async def wait(job): while not job.done(): await asyncio.sleep(0.2)
def get_client(session: Optional[str] = None) -> grc.Client: client = grc.Client("https://ysharma-explore-llamav2-with-tgi.hf.space", hf_token=os.getenv("HF_TOKEN")) if session: client.session_hash = session return client
def truncate_response(response: str) -> str: ending = "...\nTruncating response to 2000 characters due to discord api limits." if len(response) > 2000: return response[: 2000 - len(ending)] + ending else: return response
intents = discord.Intents.default()intents.message_content = Truebot = commands.Bot(command_prefix="!", intents=intents)
@bot.eventasync def on_ready(): print(f"Logged in as {bot.user} (ID: {bot.user.id})") event.set() print("------")
thread_to_client = {}thread_to_user = {}
@bot.command()@commands.is_owner()async def sync(ctx) -> None: synced = await bot.tree.sync() await ctx.send(f"Synced commands: {', '.join([s.name for s in synced])}.")
@bot.hybrid_command( name="llama70b", description="Enter some text to chat with the bot! Like this: /llama70b Hello, how are you?",)async def chat(ctx, prompt: str): if ctx.author.id == bot.user.id: return try: message = await ctx.send("Creating thread...")
# User triggered bot via !llama70b if ctx.message.content: prompt = ctx.message.content.replace( f"{bot.command_prefix}llama70b", "" ).strip()
thread = await message.create_thread(name=prompt) loop = asyncio.get_running_loop() client = await loop.run_in_executor(None, get_client, None) job = client.submit(prompt, api_name="/chat") await wait(job)
try: job.result() response = job.outputs()[-1] print(response) await thread.send(truncate_response(response)) thread_to_client[thread.id] = client thread_to_user[thread.id] = ctx.author.id except QueueError: await thread.send( "The gradio space powering this bot is really busy! Please try again later!" )
except Exception as e: print(f"{e}")
async def continue_chat(message): """Continues a given conversation based on chathistory""" try: client = thread_to_client[message.channel.id] prompt = message.content job = client.submit(prompt, api_name="/chat") await wait(job) try: job.result() response = job.outputs()[-1] await message.reply(truncate_response(response)) except QueueError: await message.reply( "The gradio space powering this bot is really busy! Please try again later!" )
except Exception as e: print(f"Error: {e}")
@bot.eventasync def on_message(message): """Continue the chat""" try: if not message.author.bot: if message.channel.id in thread_to_user: if thread_to_user[message.channel.id] == message.author.id: await continue_chat(message) else: await bot.process_commands(message)
except Exception as e: print(f"Error: {e}")
# running in threaddef run_bot(): if not DISCORD_TOKEN: print("DISCORD_TOKEN NOT SET") event.set() else: bot.run(DISCORD_TOKEN)
threading.Thread(target=run_bot).start()
event.wait()
if not DISCORD_TOKEN: welcome_message = """
## You have not specified a DISCORD_TOKEN, which means you have not created a bot account. Please follow these steps:
### 1. Go to https://discord.com/developers/applications and click 'New Application' ### 2. Give your bot a name 🤖
 ## 3. In Settings > Bot, click the 'Reset Token' button to get a new token. Write it down and keep it safe 🔐  ## 4. Optionally make the bot public if you want anyone to be able to add it to their servers ## 5. Scroll down and enable 'Message Content Intent' under 'Priviledged Gateway Intents' 
## 6. Save your changes!
## 7. The token from step 3 is the DISCORD_TOKEN. Rerun the deploy_discord command, e.g client.deploy_discord(discord_bot_token=DISCORD_TOKEN, ...), or add the token as a space secret manually."""else: permissions = Permissions(326417525824) url = oauth_url(bot.user.id, permissions=permissions) welcome_message = f""" ## Add this bot to your server by clicking this link: {url}
## How to use it?
The bot can be triggered via `!llama70b` followed by your text prompt.
## Enabling slash commands
If you are the owner of this bot, call the `!sync` command from your discord server. This will allow anyone in your server to call the bot via `/llama70b`. This is known as a slash command and is a nicer experience than calling the bot via `!llama70b`. After calling `!sync`, it may take a few minutes for `/llama70b` to be recognized as a valid command in your server. """
with gr.Blocks() as demo: gr.Markdown( f""" # Discord bot of https://ysharma-explore-llamav2-with-tgi.hf.space {welcome_message} """ )
demo.launch()1discord.py==2.3.1.gitattributesAdded+35
README.mdAdded+15
app.pyAdded+206
requirements.txtAdded+1