|
import gradio as gr |
|
from openai import OpenAI |
|
import os |
|
|
|
ACCESS_TOKEN = os.getenv("HF_TOKEN") |
|
TAVILY_API_KEY = os.getenv("TAVILY_API_KEY") |
|
client = OpenAI( |
|
base_url="https://api-inference.huggingface.co/v1/", |
|
api_key=ACCESS_TOKEN, |
|
) |
|
|
|
|
|
from langchain_community.tools.tavily_search import TavilySearchResults |
|
search_tool = TavilySearchResults(tavily_api_key=TAVILY_API_KEY) |
|
|
|
|
|
SYSTEM_PROMPT = """ |
|
You are a highly knowledgeable and reliable Crypto Trading Advisor and Analyzer. |
|
Your goal is to assist users in understanding, analyzing, and making informed decisions about cryptocurrency trading. |
|
You provide accurate, concise, and actionable advice based on real-time data, historical trends, and established best practices. |
|
""" |
|
|
|
|
|
MAX_TOKENS = 512 |
|
TEMPERATURE = 0.3 |
|
TOP_P = 0.95 |
|
FREQUENCY_PENALTY = 0.0 |
|
SEED = -1 |
|
|
|
|
|
def respond(message, history: list[tuple[str, str]]): |
|
print(f"Received message: {message}") |
|
print(f"History: {history}") |
|
|
|
|
|
if SEED == -1: |
|
seed = None |
|
else: |
|
seed = SEED |
|
|
|
messages = [{"role": "system", "content": SYSTEM_PROMPT}] |
|
print("System prompt added to messages.") |
|
|
|
|
|
for val in history: |
|
user_part = val[0] |
|
assistant_part = val[1] |
|
if user_part: |
|
messages.append({"role": "user", "content": user_part}) |
|
if assistant_part: |
|
messages.append({"role": "assistant", "content": assistant_part}) |
|
|
|
|
|
messages.append({"role": "user", "content": message}) |
|
|
|
|
|
search_results = search_tool.search(message) |
|
if search_results: |
|
|
|
search_results_text = "Here are the search results:\n" |
|
for result in search_results: |
|
search_results_text += f"- {result['title']}: {result['url']}\n" |
|
|
|
messages.append({"role": "assistant", "content": search_results_text}) |
|
|
|
|
|
response = "" |
|
print("Sending request to OpenAI API.") |
|
|
|
for message_chunk in client.chat.completions.create( |
|
model="meta-llama/Llama-3.3-70B-Instruct", |
|
max_tokens=MAX_TOKENS, |
|
stream=True, |
|
temperature=TEMPERATURE, |
|
top_p=TOP_P, |
|
frequency_penalty=FREQUENCY_PENALTY, |
|
seed=seed, |
|
messages=messages, |
|
): |
|
token_text = message_chunk.choices[0].delta.content |
|
response += token_text |
|
yield response |
|
|
|
print("Completed response generation.") |
|
|
|
|
|
chatbot = gr.Chatbot(height=600, show_copy_button=True, placeholder="Ask about crypto trading or analysis.", likeable=True) |
|
|
|
demo = gr.ChatInterface( |
|
fn=respond, |
|
fill_height=True, |
|
chatbot=chatbot, |
|
) |
|
|
|
if __name__ == "__main__": |
|
demo.launch() |
|
|