Market Cap: $2.6906T 0.59%
Volume(24h): $84.6845B 15.37%
  • Market Cap: $2.6906T 0.59%
  • Volume(24h): $84.6845B 15.37%
  • Fear & Greed Index:
  • Market Cap: $2.6906T 0.59%
Cryptos
Topics
Cryptospedia
News
CryptosTopics
Videos
Top News
Cryptos
Topics
Cryptospedia
News
CryptosTopics
Videos
bitcoin
bitcoin

$79248.069182 USD

1.09%

ethereum
ethereum

$2511.064695 USD

1.53%

tether
tether

$0.999850 USD

0.01%

bnb
bnb

$756.247700 USD

0.89%

xrp
xrp

$1.438158 USD

3.79%

usd-coin
usd-coin

$0.999958 USD

0.01%

solana
solana

$104.884928 USD

2.06%

tron
tron

$0.339008 USD

0.51%

hyperliquid
hyperliquid

$86.722420 USD

3.32%

zcash
zcash

$1235.386194 USD

9.84%

dogecoin
dogecoin

$0.090749 USD

1.59%

monero
monero

$503.916600 USD

-2.09%

chainlink
chainlink

$12.600233 USD

-0.32%

unus-sed-leo
unus-sed-leo

$9.181565 USD

-0.39%

cardano
cardano

$0.221251 USD

2.14%

Cryptocurrency News Articles

Managing Context Effectively with the Model Context Protocol

Apr 28, 2025 at 02:32 pm

In this tutorial, we guide you through a practical implementation of the Model Context Protocol (MCP) by building a ModelContextManager

Managing Context Effectively with the Model Context Protocol

```python

import torch

import numpy as np

import typing

from dataclasses import dataclass

import time

import gc

from tqdm.notebook import tqdm

from sentence_transformers import SentenceTransformer

from transformers import GPT2Tokenizer, FLAN_T5ForConditionalGeneration, AutoTokenizer, AutoModelForSeq2SeqLM

import math

MAX_TOKENS = 8000

DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'

NUM_CHUNKS = 50

CHUNK_SIZE = 100

RELEVANCE_THRESHOLD = 0.1

IMPORTANCE_FACTOR = 1.0

RECENCY_FACTOR = 0.5

VISUALIZE_CONTEXT = True

BATCH_SIZE = 32

class ContextChunk(typing.NamedTuple):

content: str

embedding: np.array

importance: float = 1.0

timestamp: float = time.time()

metadata: dict = None

def __post_init__(self):

if self.metadata is None:

self.metadata = {}

class ModelContextManager:

def __init__(self, context_chunks:typing.List[ContextChunk]=None, max_tokens:int=MAX_TOKENS, token_limit:int=0, gpt2_tokenizer:GPT2Tokenizer=None):

self.max_tokens = max_tokens

self.token_limit = token_limit

self.context_chunks = context_chunks or []

self.used_tokens = 0

self.last_chunk_index = 0

self.total_chunks = 0

if gpt2_tokenizer is None:

self.gpt2_tokenizer = GPT2Tokenizer.from_pretrained("gpt2")

else:

self.gpt2_tokenizer = gpt2_tokenizer

self.sentence_transformer = SentenceTransformer('all-mpnet-base-v2')

def add_chunk(self, chunk_text:str, importance:float=1.0):

encoded_input = self.gpt2_tokenizer(chunk_text, return_tensors='pt')

self.used_tokens += int(encoded_input[0].shape[1])

chunk_embedding = self.sentence_transformer.encode(chunk_text, batch_size=BATCH_SIZE)

new_chunk = ContextChunk(content=chunk_text, embedding=chunk_embedding, importance=importance)

self.context_chunks.append(new_chunk)

self.last_chunk_index += 1

self.total_chunks += 1

print(f"Added chunk with {int(encoded_input[0].shape[1])} tokens and importance {importance}. Total used tokens: {self.used_tokens}, total chunks: {self.total_chunks}")

def optimize_context_window(self, query:str, min_chunks:int=3):

if len(self.context_chunks) <= min_chunks:

return []

query_embedding = self.sentence_transformer.encode(query, batch_size=BATCH_SIZE)

chunks_to_keep = []

remaining_tokens = self.max_tokens - self.used_tokens

if remaining_tokens < 0:

print("Warning: token limit exceeded by %s tokens" % -remaining_tokens)

for i in range(min_chunks, len(self.context_chunks) - 1, -1):

chunk = self.context_chunks[i]

if i == len(self.context_chunks) - 1:

chunks_to_keep.append(i)

continue

chunk_importance = chunk.importance * IMPORTANCE_FACTOR

chunk_recency = (time.time() - chunk.timestamp) * RECENCY_FACTOR

relevant_scores = np.array([cosine_similarity(chunk.embedding, x) for x in query_embedding])

max_relevant_score = np.max(relevant_scores)

total_score = chunk_importance + chunk_recency + max_relevant_score

if total_score >= RELEVANCE_THRESHOLD:

encoded_input = self.gpt2_tokenizer(chunk.content, return_tensors='pt')

chunk_token_count = int(encoded_input[0].shape[1])

if remaining_tokens >= chunk_token_count:

chunks_to_keep.append(i)

remaining_

Original source:marktechpost

Disclaimer:info@kdj.com

The information provided is not trading advice. kdj.com does not assume any responsibility for any investments made based on the information provided in this article. Cryptocurrencies are highly volatile and it is highly recommended that you invest with caution after thorough research!

If you believe that the content used on this website infringes your copyright, please contact us immediately (info@kdj.com) and we will delete it promptly.

Other articles published on Sep 09, 2026