import tiktoken
from typing import List
from langchain_core.messages import BaseMessage
from langchain_core.messages import SystemMessage
from langchain_core.messages import HumanMessage
from langchain_core.messages import ToolMessage
from langchain_core.messages import AIMessage
from langchain_core.messages import trim_messages
sourceMessageList = [
SystemMessage("you're a good assistant, you always respond with a joke."),
HumanMessage("i wonder why it's called langchain"),
AIMessage('Well, I guess they thought "WordRope" and "SentenceString" just didn\'t have the same ring to it!'),
HumanMessage("and who is harrison chasing anyways"),
AIMessage("Hmmm let me think.\n\nWhy, he's probably chasing after the last cup of coffee in the office!"),
HumanMessage("what do you call a speechless parrot")
]
def getTokenCounterFromString(text : str) -> int:
encoding = tiktoken.get_encoding("o200k_base")
return len(encoding.encode(text))
def getTokenCounterFromMessageList(messageList : List[BaseMessage]) -> int:
tokenCount = 3 # 모든 응답은 <|start|>assistant<|message|>로 시작된다.
tokenCountPerMessage = 3
tokenCountPerName = 1
for message in messageList:
if isinstance(message, SystemMessage):
role = "system"
elif isinstance(message, HumanMessage):
role = "user"
elif isinstance(message, ToolMessage):
role = "tool"
elif isinstance(message, AIMessage):
role = "assistant"
else:
raise ValueError(f"Unsupported messages type {message.__class__}")
tokenCount += (tokenCountPerMessage + getTokenCounterFromString(role) + getTokenCounterFromString(message.content))
if message.name:
tokenCount += tokenCountPerName + getTokenCounterFromString(message.name)
return tokenCount
targetMessageList = trim_messages(
sourceMessageList,
max_tokens = 45,
strategy = "last",
token_counter = getTokenCounterFromMessageList,
)
print(targetMessageList)
"""
[
AIMessage(content = "Hmmm let me think.\n\nWhy, he's probably chasing after the last cup of coffee in the office!"),
HumanMessage(content = 'what do you call a speechless parrot')
]
"""----------------------------------------------------------------------------------------------------
▶ requirements.txt