• Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy
Thursday, June 12, 2025
newsaiworld
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us
No Result
View All Result
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us
No Result
View All Result
Morning News
No Result
View All Result
Home Artificial Intelligence

Tutorial: Semantic Clustering of Person Messages with LLM Prompts

Admin by Admin
February 18, 2025
in Artificial Intelligence
0
Unnamed.png
0
SHARES
0
VIEWS
Share on FacebookShare on Twitter

READ ALSO

Mannequin Context Protocol (MCP) Tutorial: Construct Your First MCP Server in 6 Steps

Audio Spectrogram Transformers Past the Lab


As a Developer Advocate, it’s difficult to maintain up with consumer discussion board messages and perceive the massive image of what customers are saying. There’s loads of beneficial content material — however how are you going to shortly spot the important thing conversations? On this tutorial, I’ll present you an AI hack to carry out semantic clustering just by prompting LLMs!

TL;DR 🔄 this weblog publish is about methods to go from (information science + code) → (AI prompts + LLMs) for a similar outcomes — simply sooner and with much less effort! 🤖⚡. It’s organized as follows:

  • Inspiration and Knowledge Sources
  • Exploring the Knowledge with Dashboards
  • LLM Prompting to provide KNN Clusters
  • Experimenting with Customized Embeddings
  • Clustering Throughout A number of Discord Servers

Inspiration and Knowledge Sources

First, I’ll give props to the December 2024 paper Clio (Claude insights and observations), a privacy-preserving platform that makes use of AI assistants to research and floor aggregated utilization patterns throughout thousands and thousands of conversations. Studying this paper impressed me to do this.

Knowledge. I used solely publicly out there Discord messages, particularly “discussion board threads”, the place customers ask for tech assist. As well as, I aggregated and anonymized content material for this weblog.  Per thread, I formatted the info into dialog flip format, with consumer roles recognized as both “consumer”, asking the query or “assistant”, anybody answering the consumer’s preliminary query. I additionally added a easy, hard-coded binary sentiment rating (0 for “not blissful” and 1 for “blissful”) based mostly on whether or not the consumer stated thanks anytime of their thread. For vectorDB distributors I used Zilliz/Milvus, Chroma, and Qdrant.

Step one was to transform the info right into a pandas information body. Under is an excerpt. You may see for thread_id=2, a consumer solely requested 1 query. However for thread_id=3, a consumer requested 4 completely different questions in the identical thread (different 2 questions at farther down timestamps, not proven beneath).

Step one was to transform the anonymized information right into a pandas information body with columns: rating, consumer, function, message, timestamp, thread, user_turns.

I added a naive sentiment 0|1 scoring perform.

def calc_score(df):
   # Outline the goal phrases
   target_words = ["thanks", "thank you", "thx", "🙂", "😉", "👍"]


   # Helper perform to verify if any goal phrase is within the concatenated message content material
   def contains_target_words(messages):
       concatenated_content = " ".be part of(messages).decrease()
       return any(phrase in concatenated_content for phrase in target_words)


   # Group by 'thread_id' and calculate rating for every group
   thread_scores = (
       df[df['role_name'] == 'consumer']
       .groupby('thread_id')['message_content']
       .apply(lambda messages: int(contains_target_words(messages)))
   )
   # Map the calculated scores again to the unique DataFrame
   df['score'] = df['thread_id'].map(thread_scores)
   return df


...


if __name__ == "__main__":
  
   # Load parameters from YAML file
   config_path = "config.yaml"
   params = load_params(config_path)
   input_data_folder = params['input_data_folder']
   processed_data_dir = params['processed_data_dir']
   threads_data_file = os.path.be part of(processed_data_dir, "thread_summary.csv")
  
   # Learn information from Discord Discussion board JSON recordsdata right into a pandas df.
   clean_data_df = process_json_files(
       input_data_folder,
       processed_data_dir)
  
   # Calculate rating based mostly on particular phrases in message content material
   clean_data_df = calc_score(clean_data_df)


   # Generate reviews and plots
   plot_all_metrics(processed_data_dir)


   # Concat thread messages & save as CSV for prompting.
   thread_summary_df, avg_message_len, avg_message_len_user = 
   concat_thread_messages_df(clean_data_df, threads_data_file)
   assert thread_summary_df.form[0] == clean_data_df.thread_id.nunique()

Exploring the Knowledge with Dashboards

From the processed information above, I constructed conventional dashboards:

  • Message Volumes: One-off peaks in distributors like Qdrant and Milvus (presumably as a consequence of advertising and marketing occasions).
  • Person Engagement: High customers bar charts and scatterplots of response time vs. variety of consumer turns present that, usually, extra consumer turns imply larger satisfaction. However, satisfaction does NOT look correlated with response time. Scatterplot darkish dots appear random with regard to y-axis (response time). Possibly customers usually are not in manufacturing, their questions usually are not very pressing? Outliers exist, comparable to Qdrant and Chroma, which can have bot-driven anomalies.
  • Satisfaction Developments: Round 70% of customers seem blissful to have any interplay. Knowledge be aware: be certain to verify emojis per vendor, generally customers reply utilizing emojis as an alternative of phrases! Instance Qdrant and Chroma.
Picture by creator of aggregated, anonymized information. High lefts: Charts show Chroma’s highest message quantity, adopted by Qdrant, after which Milvus. High rights: High messaging customers, Qdrant + Chroma doable bots (see high bar in high messaging customers chart). Center rights: Scatterplots of Response time vs Variety of consumer turns reveals no correlation with respect to darkish dots and y-axis (response time). Often larger satisfaction w.r.t. x-axis (consumer turns), besides Chroma. Backside lefts: Bar charts of satisfaction ranges, be sure you catch doable emoji-based suggestions, see Qdrant and Chroma.

LLM Prompting to provide KNN Clusters

For prompting, the subsequent step was to mixture information by thread_id. For LLMs, you want the texts concatenated collectively. I separate out consumer messages from total thread messages, to see if one or the opposite would produce higher clusters. I ended up utilizing simply consumer messages.

Instance anonymized information for prompting. All message texts concatenated collectively.

With a CSV file for prompting, you’re able to get began utilizing a LLM to do information science!

!pip set up -q google.generativeai
import os
import google.generativeai as genai


# Get API key from native system
api_key=os.environ.get("GOOGLE_API_KEY")


# Configure API key
genai.configure(api_key=api_key)


# Record all of the mannequin names
for m in genai.list_models():
   if 'generateContent' in m.supported_generation_methods:
       print(m.identify)


# Attempt completely different fashions and prompts
GEMINI_MODEL_FOR_SUMMARIES = "gemini-2.0-pro-exp-02-05"
mannequin = genai.GenerativeModel(GEMINI_MODEL_FOR_SUMMARIES)
# Mix the immediate and CSV information.
full_input = immediate + "nnCSV Knowledge:n" + csv_data
# Inference name to Gemini LLM
response = mannequin.generate_content(full_input)


# Save response.textual content as .json file...


# Examine token counts and examine to mannequin restrict: 2 million tokens
print(response.usage_metadata)
Picture by creator. High: Instance LLM mannequin names. Backside: Instance inference name to Gemini LLM token counts: prompt_token_count = enter tokens; candidates_token_count = output tokens; total_token_count = sum complete tokens used.

Sadly Gemini API saved chopping brief the response.textual content. I had higher luck utilizing AI Studio straight.

Picture by creator: Screenshot of instance outputs from Google AI Studio.

My 5 prompts to Gemini Flash & Professional (temperature set to 0) are beneath.

Immediate#1: Get thread Summaries:

Given this .csv file, per row, add 3 columns:
– thread_summary = 205 characters or much less abstract of the row’s column ‘message_content’
– user_thread_summary = 126 characters or much less abstract of the row’s column ‘message_content_user’
– thread_topic = 3–5 phrase tremendous high-level class
Be certain that the summaries seize the primary content material with out dropping an excessive amount of element. Make consumer thread summaries straight to the purpose, seize the primary content material with out dropping an excessive amount of element, skip the intro textual content. If a shorter abstract is nice sufficient desire the shorter abstract. Be certain that the subject is normal sufficient that there are fewer than 20 high-level matters for all the info. Choose fewer matters. Output JSON columns: thread_id, thread_summary, user_thread_summary, thread_topic.

Immediate#2: Get cluster stats:

Given this CSV file of messages, use column=’user_thread_summary’ to carry out semantic clustering of all of the rows. Use method = Silhouette, with linkage methodology = ward, and distance_metric = Cosine Similarity. Simply give me the stats for the strategy Silhouette evaluation for now.

Immediate#3: Carry out preliminary clustering:

Given this CSV file of messages, use column=’user_thread_summary’ to carry out semantic clustering of all of the rows into N=6 clusters utilizing the Silhouette methodology. Use column=”thread_topic” to summarize every cluster subject in 1–3 phrases. Output JSON with columns: thread_id, level0_cluster_id, level0_cluster_topic.

Silhouette Rating measures how related an object is to its personal cluster (cohesion) versus different clusters (separation). Scores vary from -1 to 1. A better common silhouette rating typically signifies better-defined clusters with good separation. For extra particulars, try the scikit-learn silhouette rating documentation.

Making use of it to Chroma Knowledge. Under, I present outcomes from Immediate#2, as a plot of silhouette scores. I selected N=6 clusters as a compromise between excessive rating and fewer clusters. Most LLMs lately for information evaluation take enter as CSV and output JSON.

Picture by creator of aggregated, anonymized information. Left: I selected N=6 clusters as compromise between larger rating and fewer clusters. Proper: The precise clusters utilizing N=6. Highest sentiment (highest scores) are for matters about Question. Lowest sentiment (lowest scores) are for matters about “Shopper Issues”.

From the plot above, you may see we’re lastly stepping into the meat of what customers are saying!

Immediate#4: Get hierarchical cluster stats:

Given this CSV file of messages, use the column=’thread_summary_user’ to carry out semantic clustering of all of the rows into Hierarchical Clustering (Agglomerative) with 2 ranges. Use Silhouette rating. What’s the optimum variety of subsequent Level0 and Level1 clusters? What number of threads per Level1 cluster? Simply give me the stats for now, we’ll do the precise clustering later.

Immediate#5: Carry out hierarchical clustering:

Settle for this clustering with 2-levels. Add cluster matters that summarize textual content column “thread_topic”. Cluster matters ought to be as brief as doable with out dropping an excessive amount of element within the cluster that means.
– Level0 cluster matters ~1–3 phrases.
– Level1 cluster matters ~2–5 phrases.
Output JSON with columns: thread_id, level0_cluster_id, level0_cluster_topic, level1_cluster_id, level1_cluster_topic.

I additionally prompted to generate Streamlit code to visualise the clusters (since I’m not a JS knowledgeable 😄). Outcomes for a similar Chroma information are proven beneath.

Picture by creator of aggregated, anonymized information. Left picture: Every scatterplot dot is a thread with hover-info. Proper picture: Hierarchical clustering with uncooked information drill-down capabilities. Api and Bundle Errors appears like Chroma’s most pressing subject to repair, as a result of sentiment is low and quantity of messages is excessive.

I discovered this very insightful. For Chroma, clustering revealed that whereas customers have been proud of matters like Question, Distance, and Efficiency, they have been sad about areas comparable to Knowledge, Shopper, and Deployment.

Experimenting with Customized Embeddings

I repeated the above clustering prompts, utilizing simply the numerical embedding (“user_embedding”) within the CSV as an alternative of the uncooked textual content summaries (“user_text”).I’ve defined embeddings intimately in earlier blogs earlier than, and the dangers of overfit fashions on leaderboards. OpenAI has dependable embeddings that are extraordinarily reasonably priced by API name. Under is an instance code snippet methods to create embeddings.

from openai import OpenAI


EMBEDDING_MODEL = "text-embedding-3-small"
EMBEDDING_DIM = 512 # 512 or 1536 doable


# Initialize shopper with API key
openai_client = OpenAI(
   api_key=os.environ.get("OPENAI_API_KEY"),
)


# Operate to create embeddings
def get_embedding(textual content, embedding_model=EMBEDDING_MODEL,
                 embedding_dim=EMBEDDING_DIM):
   response = openai_client.embeddings.create(
       enter=textual content,
       mannequin=embedding_model,
       dimensions=embedding_dim
   )
   return response.information[0].embedding


# Operate to name per pandas df row in .apply()
def generate_row_embeddings(row):
   return {
       'user_embedding': get_embedding(row['user_thread_summary']),
   }


# Generate embeddings utilizing pandas apply
embeddings_data = df.apply(generate_row_embeddings, axis=1)
# Add embeddings again into df as separate columns
df['user_embedding'] = embeddings_data.apply(lambda x: x['user_embedding'])
show(df.head())


# Save as CSV ...
Instance information for prompting. Column “user_embedding” is an array size=512 of floating level numbers.

Curiously, each Perplexity Professional and Gemini 2.0 Professional generally hallucinated cluster matters (e.g., misclassifying a query about gradual queries as “Private Matter”).

Conclusion: When performing NLP with prompts, let the LLM generate its personal embeddings — externally generated embeddings appear to confuse the mannequin.

Picture by creator of aggregated, anonymized information. Each Perplexity Professional and Google’s Gemini 1.5 Professional hallucinated Cluster Subjects when given an externally-generated embedding column. Conclusion — when performing NLP with prompts, simply maintain the uncooked textual content and let the LLM create its personal embeddings behind the scenes. Feeding in externally-generated embeddings appears to confuse the LLM!

Clustering Throughout A number of Discord Servers

Lastly, I broadened the evaluation to incorporate Discord messages from three completely different VectorDB distributors. The ensuing visualization highlighted frequent points — like each Milvus and Chroma dealing with authentication issues.

Picture by creator of aggregated, anonymized information: A multi-vendor VectorDB dashboard shows high points throughout many corporations. One factor that stands out is each Milvus and Chroma are having bother with Authentication.

Abstract

Right here’s a abstract of the steps I adopted to carry out semantic clustering utilizing LLM prompts:

  1. Extract Discord threads.
  2. Format information into dialog turns with roles (“consumer”, “assistant”).
  3. Rating sentiment and save as CSV.
  4. Immediate Google Gemini 2.0 flash for thread summaries.
  5. Immediate Perplexity Professional or Gemini 2.0 Professional for clustering based mostly on thread summaries utilizing the identical CSV.
  6. Immediate Perplexity Professional or Gemini 2.0 Professional to jot down Streamlit code to visualise clusters (as a result of I’m not a JS knowledgeable 😆).

By following these steps, you may shortly remodel uncooked discussion board information into actionable insights — what used to take days of coding can now be achieved in only one afternoon!

References

  1. Clio: Privateness-Preserving Insights into Actual-World AI Use, https://arxiv.org/abs/2412.13678
  2. Anthropic weblog about Clio, https://www.anthropic.com/analysis/clio
  3. Milvus Discord Server, final accessed Feb 7, 2025
    Chroma Discord Server, final accessed Feb 7, 2025
    Qdrant Discord Server, final accessed Feb 7, 2025
  4. Gemini fashions, https://ai.google.dev/gemini-api/docs/fashions/gemini
  5. Weblog about Gemini 2.0 fashions, https://weblog.google/expertise/google-deepmind/gemini-model-updates-february-2025/
  6. Scikit-learn Silhouette Rating
  7. OpenAI Matryoshka embeddings
  8. Streamlit

Tags: clusteringLLMMessagesPromptsSemanticTutorialUser

Related Posts

Screenshot 2025 06 09 at 10.42.31 pm.png
Artificial Intelligence

Mannequin Context Protocol (MCP) Tutorial: Construct Your First MCP Server in 6 Steps

June 12, 2025
Audiomoth.webp.webp
Artificial Intelligence

Audio Spectrogram Transformers Past the Lab

June 11, 2025
1749574001 default image.jpg
Artificial Intelligence

Functions of Density Estimation to Authorized Principle

June 10, 2025
0 brlbtvg9haryy7 h.jpg
Artificial Intelligence

The best way to Transition From Knowledge Analyst to Knowledge Scientist

June 10, 2025
Tree.png
Artificial Intelligence

Choice Bushes Natively Deal with Categorical Information

June 9, 2025
The new york public library lxos0bkpcjm unsplash scaled 1.jpg
Artificial Intelligence

5 Essential Tweaks That Will Make Your Charts Accessible to Individuals with Visible Impairments

June 8, 2025
Next Post
Chip Fab Shutterstock 2 1 2145346979.jpg

Information Bytes Podcast 20250217: Arm Promoting Its Personal Chips to Meta?, Massive xAI, Massive Energy, Massive… Air pollution?, TSMC in Intel Fab Takeover?, Europe's Massive AI Funding

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

POPULAR NEWS

0 3.png

College endowments be a part of crypto rush, boosting meme cash like Meme Index

February 10, 2025
Gemini 2.0 Fash Vs Gpt 4o.webp.webp

Gemini 2.0 Flash vs GPT 4o: Which is Higher?

January 19, 2025
1da3lz S3h Cujupuolbtvw.png

Scaling Statistics: Incremental Customary Deviation in SQL with dbt | by Yuval Gorchover | Jan, 2025

January 2, 2025
0khns0 Djocjfzxyr.jpeg

Constructing Data Graphs with LLM Graph Transformer | by Tomaz Bratanic | Nov, 2024

November 5, 2024
How To Maintain Data Quality In The Supply Chain Feature.jpg

Find out how to Preserve Knowledge High quality within the Provide Chain

September 8, 2024

EDITOR'S PICK

1fr9s Av6brjtau8wr Qm4g.png

Calibrating Classification Chances the Proper Approach | by Jonte Dancker | Sep, 2024

September 18, 2024
Kubernetes.jpg

Kubernetes — Understanding and Using Probes Successfully

March 6, 2025
Depositphotos 87186216 Xl Scaled.jpg

Extra Organizations Use AI to Handle Paperwork

September 30, 2024
Talkgraph1 process.width 800.gif

Encoding graphs for big language fashions

August 1, 2024

About Us

Welcome to News AI World, your go-to source for the latest in artificial intelligence news and developments. Our mission is to deliver comprehensive and insightful coverage of the rapidly evolving AI landscape, keeping you informed about breakthroughs, trends, and the transformative impact of AI technologies across industries.

Categories

  • Artificial Intelligence
  • ChatGPT
  • Crypto Coins
  • Data Science
  • Machine Learning

Recent Posts

  • Monitoring Knowledge With out Turning into Massive Brother
  • OpenAI’s Sam Altman muses about superintelligence • The Register
  • Mannequin Context Protocol (MCP) Tutorial: Construct Your First MCP Server in 6 Steps
  • Home
  • About Us
  • Contact Us
  • Disclaimer
  • Privacy Policy

© 2024 Newsaiworld.com. All rights reserved.

No Result
View All Result
  • Home
  • Artificial Intelligence
  • ChatGPT
  • Data Science
  • Machine Learning
  • Crypto Coins
  • Contact Us

© 2024 Newsaiworld.com. All rights reserved.

Are you sure want to unlock this post?
Unlock left : 0
Are you sure want to cancel subscription?