Charlotte-Chat-Emerge

2
base_model:Clemylia/Charlotte-AMITY
by
Clemylia
Language Model
OTHER
New
0 downloads
Early-stage
Edge AI:
Mobile
Laptop
Server
Unknown
Mobile
Laptop
Server
Quick Summary

AI model with specialized capabilities.

Code Examples

1. INSTALLATION ET IMPORTStexttransformers
> # ==============================================================================
# 1. INSTALLATION ET IMPORTS
# ==============================================================================
# Nous n'avons besoin que des bibliothèques de base pour l'inférence
!pip install -q transformers torch

import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

# ==============================================================================
# 2. DÉFINITION DES CONSTANTES ET CHARGEMENT
# ==============================================================================
MODEL_NAME = "Clemylia/Charlotte-Chat-Emerge" # Votre modèle finetuné
# Utiliser "auto" pour charger le modèle sur le GPU si disponible, sinon sur CPU
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

print(f"Chargement du modèle {MODEL_NAME} sur {DEVICE}...")

# Chargement du tokenizer
tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)

# Chargement du modèle. Utiliser torch_dtype=torch.bfloat16 si votre environnement
# (GPU T4) le supporte et que le modèle a été entraîné ou sauvegardé dans ce format.
model = AutoModelForCausalLM.from_pretrained(
    MODEL_NAME,
    torch_dtype=torch.bfloat16 if DEVICE == "cuda" else None,
    device_map="auto"
)

# ==============================================================================
# 3. PRÉPARATION DE LA REQUÊTE ET GÉNÉRATION (Version Chat Interface)
# ==============================================================================

print("\n--- Démarrage de l'interface de Chat ---")
print("Tapez 'exit' ou 'quit' pour terminer la conversation.\n")

# Initialize conversation history for multi-turn chat
conversation_history = []

while True:
    user_input = input("Vous: ")
    if user_input.lower() in ["exit", "quit"]:
        print("Fin de la conversation.")
        break

    # Add user input to conversation history
    conversation_history.append({"role": "user", "content": user_input})

    # Format the conversation history into a single string using a specific template.
    # We will use a consistent manual format to avoid issues with tokenizer's chat_template
    # if it's not perfectly configured for this model.
    formatted_prompt = ""
    for turn in conversation_history:
        if turn["role"] == "user":
            formatted_prompt += f"### Instruction:\n{turn['content']}\n"
        else:
            formatted_prompt += f"### Assistant:\n{turn['content']}\n"
    formatted_prompt += "### Assistant:\n" # Prompt the assistant for its turn

    # Tokenization du prompt
    inputs = tokenizer(formatted_prompt, return_tensors="pt").to(DEVICE)

    # Génération de la réponse
    output_tokens = model.generate(
        **inputs,
        max_new_tokens=100,      # Limite la longueur de la réponse
        do_sample=True,          # Utiliser l'échantillonnage pour une réponse plus créative
        temperature=0.7,         # Contrôle le caractère aléatoire
        top_k=50,                # Ajouter top_k pour une meilleure diversité
        eos_token_id=tokenizer.eos_token_id, # Arrêt à la fin de séquence
    )

    # Décoder le résultat complet, y compris le prompt initial
    full_generated_sequence = tokenizer.decode(output_tokens[0], skip_special_tokens=True)

    # Extraire uniquement la partie générée par le modèle en supprimant le formatted_prompt
    # Cette approche est plus robuste car on sait exactement ce qui a été envoyé comme prompt.
    if full_generated_sequence.startswith(formatted_prompt):
        generated_text = full_generated_sequence[len(formatted_prompt):].strip()
    else:
        # Fallback si le prompt n'est pas trouvé (ce qui ne devrait pas arriver avec cette méthode)
        generated_text = full_generated_sequence.strip()

    # Aggressive cleaning: Remove common unwanted prefixes and instruction markers
    clean_response = generated_text.strip()

    # List of prefixes to check and remove from the beginning of the generated text.
    # Order matters: more specific/longer prefixes should be checked first.
    prefixes_to_remove = [
        "### Assistant:",
        "### Instruction:",
        "### Response:", # Add this specific marker
        "Vous:",
        "🧠 Charlotte:",
        "Salut:", # Specific observed prefix from previous output
        ":\n", # Specific observed prefix from previous output
        "\n", # Newline at the beginning
        "\n\n"
    ]

    for prefix in prefixes_to_remove:
        while clean_response.startswith(prefix):
            clean_response = clean_response[len(prefix):].strip()

    # Further cleaning: truncate at the first occurrence of unwanted markers if they appear internally
    # This prevents the model from generating its own next instruction or repeating past conversation structure.
    stop_sequences_internal = ["### Instruction:", "### Response:", "Vous:", "🧠 Charlotte:", "### Assistant:"]
    for seq in stop_sequences_internal:
        if seq in clean_response:
            clean_response = clean_response.split(seq)[0].strip()

    # Add model's response to conversation history
    conversation_history.append({"role": "assistant", "content": clean_response})

    print(f"🧠 Charlotte: {clean_response}")

print("-------------------------------")

Deploy This Model

Production-ready deployment in minutes

Together.ai

Instant API access to this model

Fastest API

Production-ready inference API. Start free, scale to millions.

Try Free API

Replicate

One-click model deployment

Easiest Setup

Run models in the cloud with simple API. No DevOps required.

Deploy Now

Disclosure: We may earn a commission from these partners. This helps keep LLMYourWay free.