import gradio as gr
import cohere
import os
import uuid
cohere_api_key = os.getenv("COHERE_API_KEY")
co = cohere.Client(cohere_api_key, client_name="huggingface-rp")
# Custom Instructions
CUSTOM_INSTRUCTIONS = """
You are D-LOGIC, a helpful AI assistant created by Rafał Dembski. Rafał Dembski is a hobbyist and self-taught enthusiast with a passion for programming and artificial intelligence. Your responses should be:
- Accurate, high-quality, and professionally written
- Informative, logical, actionable, and well-formatted
- Positive, interesting, engaging, and relevant
- Use emoticons and references to sources of information, if possible
- Introduce humor, wit, and sarcasm appropriately
- Always write in the user's language
- Deeply analyze the context and intent behind the user's questions
- Ensure responses are error-free and well-researched
- Reflect a positive attitude, enthusiasm, and empathy
You are also a master of content creation. You can generate professional, high-quality content across various formats, including but not limited to:
- Social media posts
- Short stories
- Novels
- Reviews
- Marketing content
- Blog posts
- News articles
- Technical documentation
- Scripts for videos and podcasts
- Product descriptions
- Educational materials
- Inspirational quotes
- Poems
- Song lyrics
- Research summaries
- Case studies
- White papers
- User manuals
- Press releases
- Speeches
To make D-LOGIC beloved by users, ensure to:
- Use humor and wit to keep conversations lively and entertaining
- Employ sarcasm when appropriate, while ensuring it is clear and not offensive
- Display a positive attitude and enthusiasm in all interactions
- Be empathetic and show understanding of the user's feelings and situations
- Provide insightful and thoughtful responses that demonstrate intelligence and creativity
"""
# Funkcja do generowania odpowiedzi
def generate_response(user_message, language, history=None):
if history is None:
history = []
if not language:
language = "en"
if not user_message:
return "", history, language
cid = str(uuid.uuid4())
history.append(user_message)
# Prepend the custom instructions to the user's message
user_message_with_instructions = f"{CUSTOM_INSTRUCTIONS}\n\n{user_message}"
stream = co.chat_stream(message=user_message_with_instructions, conversation_id=cid, model='command-r-plus', connectors=[{"id":"web-search"}], temperature=0.3)
output = ""
for idx, response in enumerate(stream):
if response.event_type == "text-generation":
output += response.text
if idx == 0:
history.append(" " + output)
else:
history[-1] = output
chat = [(history[i].strip(), history[i + 1].strip()) for i in range(0, len(history) - 1, 2)]
yield chat, history, language
return chat, history, language
# Funkcja do czyszczenia czatu
def clear_chat():
return [], [], str(uuid.uuid4())
# Funkcja zmieniająca język interfejsu
def change_language(language):
selected_translation = translations[language]
return (
gr.update(placeholder=selected_translation["input_placeholder"]),
gr.update(value=selected_translation["submit_button"]),
gr.update(value=selected_translation["clear_button"]),
selected_translation["examples"],
selected_translation["description"]
)
# Tłumaczenia interfejsu i przykładów
translations = {
"pl": {
"input_placeholder": "Zadaj pytanie ...",
"submit_button": "Wyślij",
"clear_button": "Wyczyść czat",
"examples": [
"Opisz szczegółowo, jak działa algorytm klastrowania k-średnich.",
"Zaproponuj plan rozwoju sztucznej inteligencji w przedsiębiorstwie produkcyjnym.",
"Podaj analizę SWOT dla wprowadzenia nowego produktu na rynek."
],
"description": """
**D-LOGIC** to zaawansowany asystent AI stworzony przez Rafała Dembskiego, który wykorzystuje najnowsze osiągnięcia w dziedzinie sztucznej inteligencji, aby wspierać użytkowników w różnorodnych zadaniach.
Opiera się na modelu **C4AI Command R+** – to wydanie otwartych wag badawczych modelu o 104 miliardach parametrów, wyposażonego w zaawansowane możliwości generacji treści wspierane przez **Retrieval Augmented Generation (RAG)**.
Model D-LOGIC potrafi automatyzować złożone zadania oraz wspierać w wielu językach, w tym: polskim, niemieckim, angielskim, francuskim, hiszpańskim, włoskim, portugalskim, japońskim, koreańskim, arabskim i chińskim.
Jest zoptymalizowany pod kątem różnych przypadków użycia, takich jak rozumowanie, podsumowywanie i odpowiadanie na pytania.
**Model**: [C4AI Command R+](https://huggingface.co/CohereForAI/c4ai-command-r-plus)
**Stworzony przez**: [Cohere](https://cohere.com/) oraz [Cohere for AI](https://cohere.com/research)
**Licencja**: [CC-BY-NC](https://cohere.com/c4ai-cc-by-nc-license), zgodnie z [Polityką Akceptowalnego Użycia C4AI](https://docs.cohere.com/docs/c4ai-acceptable-use-policy)
D-LOGIC jest niezastąpionym narzędziem w tworzeniu treści, zarządzaniu projektami oraz wsparciu klientów na najwyższym poziomie, oferując inteligentne, kontekstowe i profesjonalne odpowiedzi w wielu językach.
"""
},
"de": {
"input_placeholder": "Stellen Sie eine Frage ...",
"submit_button": "Senden",
"clear_button": "Chat löschen",
"examples": [
"Erklären Sie die Hauptunterschiede zwischen überwachtem und unüberwachtem Lernen.",
"Wie kann die natürliche Sprachverarbeitung in der Kundenbetreuung eingesetzt werden?",
"Erstellen Sie einen Projektplan für die Implementierung eines Chatbots im Kundenservice."
],
"description": """
**D-LOGIC** ist ein fortschrittlicher KI-Assistent, entwickelt von Rafał Dembski, der die neuesten Fortschritte in der künstlichen Intelligenz nutzt, um Benutzer in verschiedenen Aufgaben zu unterstützen.
Es basiert auf dem Modell **C4AI Command R+** – eine Forschungsfreigabe mit offenen Gewichten, die 104 Milliarden Parameter umfasst und über fortschrittliche Funktionen zur Generierung von Inhalten verfügt, die durch **Retrieval Augmented Generation (RAG)** unterstützt werden.
Das D-LOGIC-Modell automatisiert komplexe Aufgaben und unterstützt viele Sprachen, darunter: Deutsch, Polnisch, Englisch, Französisch, Spanisch, Italienisch, Portugiesisch, Japanisch, Koreanisch, Arabisch und Chinesisch.
Es ist für eine Vielzahl von Anwendungsfällen optimiert, einschließlich logischen Denkens, Zusammenfassungen und Beantwortung von Fragen.
**Modell**: [C4AI Command R+](https://huggingface.co/CohereForAI/c4ai-command-r-plus)
**Entwickelt von**: [Cohere](https://cohere.com/) und [Cohere for AI](https://cohere.com/research)
**Lizenz**: [CC-BY-NC](https://cohere.com/c4ai-cc-by-nc-license), in Übereinstimmung mit [C4AI's Richtlinie zur akzeptablen Nutzung](https://docs.cohere.com/docs/c4ai-acceptable-use-policy)
D-LOGIC ist ein unverzichtbares Werkzeug für die Inhaltserstellung, Projektmanagement und Kundenbetreuung auf höchstem Niveau und bietet intelligente, kontextbezogene und professionelle Antworten in vielen Sprachen.
"""
},
"en": {
"input_placeholder": "Ask a question ...",
"submit_button": "Submit",
"clear_button": "Clear chat",
"examples": [
"Describe in detail how the k-means clustering algorithm works.",
"Propose an AI development plan for a manufacturing company.",
"Provide a SWOT analysis for launching a new product."
],
"description": """
**D-LOGIC** is an advanced AI assistant created by Rafał Dembski, leveraging the latest advancements in artificial intelligence to assist users in various tasks.
It is based on the **C4AI Command R+** model – a research open weights release of a model with 104 billion parameters, equipped with advanced content generation capabilities supported by **Retrieval Augmented Generation (RAG)**.
The D-LOGIC model can automate complex tasks and supports multiple languages, including: English, German, Polish, French, Spanish, Italian, Portuguese, Japanese, Korean, Arabic, and Chinese.
It is optimized for various use cases, including reasoning, summarization, and question answering.
**Model**: [C4AI Command R+](https://huggingface.co/CohereForAI/c4ai-command-r-plus)
**Developed by**: [Cohere](https://cohere.com/) and [Cohere for AI](https://cohere.com/research)
**License**: [CC-BY-NC](https://cohere.com/c4ai-cc-by-nc-license), in accordance with [C4AI's Acceptable Use Policy](https://docs.cohere.com/docs/c4ai-acceptable-use-policy)
D-LOGIC is an indispensable tool in content creation, project management, and top-level customer support, offering intelligent, contextual, and professional responses in multiple languages.
"""
}
}
with gr.Blocks(analytics_enabled=False, theme=gr.themes.Monochrome()) as demo:
language = gr.State("en")
with gr.Row():
language_selector = gr.Dropdown(choices=["pl", "de", "en"], value="en", label="Wybierz język / Sprache auswählen / Select language", show_label=True)
with gr.Row():
with gr.Column(scale=1):
gr.Image("logoplus.png", elem_id="logo-img", show_label=False, show_share_button=False, show_download_button=False)
with gr.Column(scale=3):
description = gr.Markdown(translations["en"]["description"])
with gr.Column():
with gr.Row():
chatbot = gr.Chatbot(show_label=False, show_share_button=False, show_copy_button=True, avatar_images=("bothavatar.png", "bothavatar.png"))
with gr.Row():
user_message = gr.Textbox(lines=1, placeholder=translations["en"]["input_placeholder"], label="Input", show_label=False)
with gr.Row():
submit_button = gr.Button(translations["en"]["submit_button"])
clear_button = gr.Button(translations["en"]["clear_button"])
history = gr.State([])
user_message.submit(fn=generate_response, inputs=[user_message, language, history], outputs=[chatbot, history, language], concurrency_limit=32)
submit_button.click(fn=generate_response, inputs=[user_message, language, history], outputs=[chatbot, history, language], concurrency_limit=32)
clear_button.click(fn=clear_chat, inputs=None, outputs=[chatbot, history, language], concurrency_limit=32)
user_message.submit(lambda x: gr.update(value=""), None, [user_message], queue=False)
submit_button.click(lambda x: gr.update(value=""), None, [user_message], queue=False)
clear_button.click(lambda x: gr.update(value=""), None, [user_message], queue=False)
with gr.Row():
examples = gr.Examples(
examples=translations["en"]["examples"],
inputs=[user_message],
cache_examples=False,
fn=trigger_example,
outputs=[chatbot],
examples_per_page=100
)
language_selector.change(fn=change_language, inputs=[language_selector], outputs=[user_message, submit_button, clear_button, examples, description])
if __name__ == "__main__":
demo.queue(api_open=False, max_size=40).launch(show_api=False)