• bitcoinBitcoin(BTC)$84,548.000.63%
  • ethereumEthereum(ETH)$2,686.330.37%
  • tetherTether(USDT)$1.00-0.01%
  • binancecoinBNB(BNB)$777.421.00%
  • rippleXRP(XRP)$1.520.62%
  • usd-coinUSDC(USDC)$1.00-0.01%
  • solanaSolana(SOL)$122.701.83%
  • tronTRON(TRX)$0.333655-0.41%
  • zcashZcash(ZEC)$1,604.531.57%
  • Figure HelocFigure Heloc(FIGR_HELOC)$1.062.90%
  • HyperliquidHyperliquid(HYPE)$91.630.08%
  • dogecoinDogecoin(DOGE)$0.0969510.99%
  • chainlinkChainlink(LINK)$14.020.19%
  • moneroMonero(XMR)$547.17-0.89%
  • whitebitWhiteBIT Coin(WBT)$84.310.62%
  • USDSUSDS(USDS)$1.00-0.01%
  • cardanoCardano(ADA)$0.2548281.59%
  • RainRain(RAIN)$0.012554-2.19%
  • leo-tokenLEO Token(LEO)$9.050.98%
  • stellarStellar(XLM)$0.2159770.26%
  • nearNEAR Protocol(NEAR)$5.4714.20%
  • bitcoin-cashBitcoin Cash(BCH)$333.840.02%
  • uniswapUniswap(UNI)$9.692.00%
  • litecoinLitecoin(LTC)$71.24-0.34%
  • CantonCanton(CC)$0.1379893.58%
  • suiSui(SUI)$1.2610.51%
  • Ethena USDeEthena USDe(USDE)$1.000.02%
  • avalanche-2Avalanche(AVAX)$10.962.75%
  • the-open-networkGram (prev. Toncoin)(GRAM)$1.643.75%
  • daiDai(DAI)$1.00-0.01%
  • USD1USD1(USD1)$1.00-0.02%
  • hedera-hashgraphHedera(HBAR)$0.0945822.07%
  • BittensorBittensor(TAO)$325.013.18%
  • shiba-inuShiba Inu(SHIB)$0.0000060.62%
  • crypto-com-chainCronos(CRO)$0.0673782.95%
  • BitwayBitway(BTW)$1.2117.61%
  • Global DollarGlobal Dollar(USDG)$1.00-0.01%
  • quant-networkQuant(QNT)$198.3764.95%
  • EthenaEthena(ENA)$0.2815904.79%
  • paypal-usdPayPal USD(PYUSD)$1.000.00%
  • MemeCoreMemeCore(M)$1.19-1.88%
  • OndoOndo(ONDO)$0.553.12%
  • tether-goldTether Gold(XAUT)$4,278.21-0.04%
  • okbOKB(OKB)$121.450.87%
  • Ripple USDRipple USD(RLUSD)$1.00-0.01%
  • Circle USYCCircle USYC(USYC)$1.140.00%
  • aaveAave(AAVE)$154.350.17%
  • Pump.funPump.fun(PUMP)$0.00500715.44%
  • BlackRock USD Institutional Digital Liquidity FundBlackRock USD Institutional Digital Liquidity Fund(BUIDL)$1.000.00%
  • Ondo US Dollar YieldOndo US Dollar Yield(USDY)$1.15-0.11%
TradePoint.io
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop
No Result
View All Result
TradePoint.io
No Result
View All Result

Building a Legal AI Chatbot: A Step-by-Step Guide Using bigscience/T0pp LLM, Open-Source NLP Models, Streamlit, PyTorch, and Hugging Face Transformers

February 24, 2025
in AI & Technology
Reading Time: 5 mins read
A A
Building a Legal AI Chatbot: A Step-by-Step Guide Using bigscience/T0pp LLM, Open-Source NLP Models, Streamlit, PyTorch, and Hugging Face Transformers
ShareShareShareShareShare

In this tutorial, we will build an efficient Legal AI CHatbot using open-source tools. It provides a step-by-step guide to creating a chatbot using bigscience/T0pp LLM, Hugging Face Transformers, and PyTorch. We will walk you through setting up the model, optimizing performance using PyTorch, and ensuring an efficient and accessible AI-powered legal assistant.

from transformers import AutoModelForSeq2SeqLM, AutoTokenizer


model_name = "bigscience/T0pp"  # Open-source and available
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSeq2SeqLM.from_pretrained(model_name)

First, we load bigscience/T0pp, an open-source LLM, using Hugging Face Transformers. It initializes a tokenizer for text preprocessing and loads the AutoModelForSeq2SeqLM, enabling the model to perform text generation tasks such as answering legal queries.

YOU MAY ALSO LIKE

Bill Gates Says It’s ‘Completely Irresponsible’ For AI To Not Have Safeguards

Why The iPhone Duo Could Be Beneficial For Samsung’s Galaxy Z Fold 8

import spacy
import re


nlp = spacy.load("en_core_web_sm")


def preprocess_legal_text(text):
    text = text.lower()
    text = re.sub(r'\s+', ' ', text)  # Remove extra spaces
    text = re.sub(r'[^a-zA-Z0-9\s]', '', text)  # Remove special characters
    doc = nlp(text)
    tokens = [token.lemma_ for token in doc if not token.is_stop]  # Lemmatization
    return " ".join(tokens)


sample_text = "The contract is valid for 5 years, terminating on December 31, 2025."
print(preprocess_legal_text(sample_text))

Then, we preprocess legal text using spaCy and regular expressions to ensure cleaner and more structured input for NLP tasks. It first converts text to lowercase, removes extra spaces and special characters using regex, and then tokenizes and lemmatizes the text using spaCy’s NLP pipeline. Additionally, it filters out stop words to retain only meaningful terms, making it ideal for legal text processing in AI applications. The cleaned text is more efficient for machine learning and language models like bigscience/T0pp, improving accuracy in legal chatbot responses.

def extract_legal_entities(text):
    doc = nlp(text)
    entities = [(ent.text, ent.label_) for ent in doc.ents]
    return entities


sample_text = "Apple Inc. signed a contract with Microsoft on June 15, 2023."
print(extract_legal_entities(sample_text))

Here, we extract legal entities from text using spaCy’s Named Entity Recognition (NER) capabilities. The function processes the input text with spaCy’s NLP model, identifying and extracting key entities such as organizations, dates, and legal terms. It returns a list of tuples, each containing the recognized entity and its category (e.g., organization, date, or law-related term).

import faiss
import numpy as np
import torch
from transformers import AutoModel, AutoTokenizer


embedding_model = AutoModel.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")
embedding_tokenizer = AutoTokenizer.from_pretrained("sentence-transformers/all-MiniLM-L6-v2")


def embed_text(text):
    inputs = embedding_tokenizer(text, return_tensors="pt", padding=True, truncation=True)
    with torch.no_grad():
        output = embedding_model(**inputs)
    embedding = output.last_hidden_state.mean(dim=1).squeeze().cpu().numpy()  # Ensure 1D vector
    return embedding


legal_docs = [
    "A contract is legally binding if signed by both parties.",
    "An NDA prevents disclosure of confidential information.",
    "A non-compete agreement prohibits working for a competitor."
]


doc_embeddings = np.array([embed_text(doc) for doc in legal_docs])


print("Embeddings Shape:", doc_embeddings.shape)  # Should be (num_samples, embedding_dim)


index = faiss.IndexFlatL2(doc_embeddings.shape[1])  # Dimension should match embedding size
index.add(doc_embeddings)


query = "What happens if I break an NDA?"
query_embedding = embed_text(query).reshape(1, -1)  # Reshape for FAISS
_, retrieved_indices = index.search(query_embedding, 1)


print(f"Best matching legal text: {legal_docs[retrieved_indices[0][0]]}")

With the above code, we build a legal document retrieval system using FAISS for efficient semantic search. It first loads the MiniLM embedding model from Hugging Face to generate numerical representations of text. The embed_text function processes legal documents and queries by computing contextual embeddings using MiniLM. These embeddings are stored in a FAISS vector index, allowing fast similarity searches.

def legal_chatbot(query):
    inputs = tokenizer(query, return_tensors="pt", padding=True, truncation=True)
    output = model.generate(**inputs, max_length=100)
    return tokenizer.decode(output[0], skip_special_tokens=True)


query = "What happens if I break an NDA?"
print(legal_chatbot(query))

Finally, we define a Legal AI Chatbot as generating responses to legal queries using a pre-trained language model. The legal_chatbot function takes a user query, processes it using the tokenizer, and generates a response with the model. The response is then decoded into readable text, removing any special tokens. When a query like “What happens if I break an NDA?” is input, the chatbot provides a relevant AI-generated legal response.

In conclusion, by integrating bigscience/T0pp LLM, Hugging Face Transformers, and PyTorch, we have demonstrated how to build a powerful and scalable Legal AI Chatbot using open-source resources. This project is a solid foundation for creating reliable AI-powered legal tools, making legal assistance more accessible and automated.


Here is the Colab Notebook for the above project. Also, don’t forget to follow us on Twitter and join our Telegram Channel and LinkedIn Group. Don’t Forget to join our 80k+ ML SubReddit.

🚨 Recommended Read- LG AI Research Releases NEXUS: An Advanced System Integrating Agent AI System and Data Compliance Standards to Address Legal Concerns in AI Datasets


Asif Razzaq is the CEO of Marktechpost Media Inc.. As a visionary entrepreneur and engineer, Asif is committed to harnessing the potential of Artificial Intelligence for social good. His most recent endeavor is the launch of an Artificial Intelligence Media Platform, Marktechpost, which stands out for its in-depth coverage of machine learning and deep learning news that is both technically sound and easily understandable by a wide audience. The platform boasts of over 2 million monthly views, illustrating its popularity among audiences.

🚨 Recommended Open-Source AI Platform: ‘IntellAgent is a An Open-Source Multi-Agent Framework to Evaluate Complex Conversational AI System’ (Promoted)

Credit: Source link

ShareTweetSendSharePin

Related Posts

Bill Gates Says It’s ‘Completely Irresponsible’ For AI To Not Have Safeguards
AI & Technology

Bill Gates Says It’s ‘Completely Irresponsible’ For AI To Not Have Safeguards

September 27, 2026
Why The iPhone Duo Could Be Beneficial For Samsung’s Galaxy Z Fold 8
AI & Technology

Why The iPhone Duo Could Be Beneficial For Samsung’s Galaxy Z Fold 8

September 27, 2026
How To Improve Your Router’s Security In 10 Minutes
AI & Technology

How To Improve Your Router’s Security In 10 Minutes

September 27, 2026
Humanoid Robots Are Getting Even Creepier (This One Can Cry On Command)
AI & Technology

Humanoid Robots Are Getting Even Creepier (This One Can Cry On Command)

September 27, 2026
Next Post
Alleged ringleader in 0M Covid fraud case goes to trial

Alleged ringleader in $250M Covid fraud case goes to trial

Leave a Reply Cancel reply

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

Search

No Result
View All Result
Stay Tuned NOW Streaming Behind The Scenes! – Aug 25

Stay Tuned NOW Streaming Behind The Scenes! – Aug 25

September 23, 2026
Lots of unsold units remain at One Wall Street — and pied-à-terre tax unlikely to help

Lots of unsold units remain at One Wall Street — and pied-à-terre tax unlikely to help

September 21, 2026
Putin says new Ukrainian strikes opened ‘Pandora’s box’

Putin says new Ukrainian strikes opened ‘Pandora’s box’

September 25, 2026

About

Learn more

Our Services

Legal

Privacy Policy

Terms of Use

Bloggers

Learn more

Article Links

Contact

Advertise

Ask us anything

©2020- TradePoint.io - All rights reserved!

Tradepoint.io, being just a publishing and technology platform, is not a registered broker-dealer or investment adviser. So we do not provide investment advice. Rather, brokerage services are provided to clients of Tradepoint.io by independent SEC-registered broker-dealers and members of FINRA/SIPC. Every form of investing carries some risk and past performance is not a guarantee of future results. “Tradepoint.io“, “Instant Investing” and “My Trading Tools” are registered trademarks of Apperbuild, LLC.

This website is operated by Apperbuild, LLC. We have no link to any brokerage firm and we do not provide investment advice. Every information and resource we provide is solely for the education of our readers. © 2020 Apperbuild, LLC. All rights reserved.

No Result
View All Result
  • Main
  • AI & Technology
  • Stock Charts
  • Market & News
  • Business
  • Finance Tips
  • Trade Tube
  • Blog
  • Shop

© 2023 - TradePoint.io - All Rights Reserved!