如何在一定时间内的不活动后清除地图条目

huangapple go评论91阅读模式
英文:

How to clear Map entry after certain time of inactivity

问题

我正在开发一个由OpenAI提供支持的聊天机器人。我正在使用新的gpt-3.5-turbo模型进行ChatCompletion请求。我已经想出了一种方法,让机器人记住每个用户的对话,使用HashMap来实现,一切都正常工作。机器人能够记住所有先前的回应,并使用历史作为上下文生成新的回应。然而,查询中的回应越多,它将使用的代币越多,增加成本。我希望如果有一定数量的不活动时间(比如与机器人不交谈的2分钟),它会清除历史记录并开始一个全新的对话,以节省代币。如何实现这一点的最佳方法是什么?

这是我的代码:

private static OpenAiService service;
	
private static Map<String, List<ChatMessage>> conversations = new HashMap<String, List<ChatMessage>>();
			
public static void initializeOpenAi() {
	service = new OpenAiService(Settings.OPENAI_ACCESS_KEY);
}

public static String generateChatResponse(User user, String prompt) {
	List<ChatMessage> conversation;
		
	if (conversations.containsKey(user.getId())) {
		conversation = conversations.get(user.getId());
	} else {
		conversation = new ArrayList<ChatMessage>();
	}
		
	if (conversation.size() < 1) {
		ChatMessage system = new ChatMessage();
		system.setRole("system");
		system.setContent("Omnis is a chatbot with sarcasm");
		conversation.add(system);
	}
		
	ChatMessage userPrompt = new ChatMessage();
	userPrompt.setRole("user");
	userPrompt.setContent(prompt);
	conversation.add(userPrompt);
		
	ChatCompletionRequest chatRequest = ChatCompletionRequest.builder()
			.model("gpt-3.5-turbo")
			.maxTokens(1000)
			.temperature(0.9)
			.topP(0.3)
			.frequencyPenalty(0.9)
			.presencePenalty(0.0)
			.messages(conversation)
			.build();
		
	ChatCompletionResult chatResult = null;
		
	try {
		chatResult = service.createChatCompletion(chatRequest);
	} catch (Exception e) {
		System.out.println("An OpenAI request failed!");
			
		if (e.getMessage().contains("timeout")) {
			return "Your request timed out. Please try again after a brief wait or try a different request.";
		}
			
		if (e.getMessage().contains("Rate limit")) {
			return "Rate limit for chat requests has been reached!";
		}
			
		return "Something went wrong with your request. Cause of error is " + e.getMessage();
	}
		
	if (chatResult != null) {
		System.out.println("Created chat completion request that used " + chatResult.getUsage().getTotalTokens() + " tokens with " + chatResult.getModel());
	}
		
	String response = chatResult.getChoices().get(0).getMessage().getContent();
		
	ChatMessage assistantPrompt = new ChatMessage();
	assistantPrompt.setRole("assistant");
	assistantPrompt.setContent(response);
	conversation.add(assistantPrompt);
		
	conversations.put(user.getId(), conversation);
		
	return response;
}

每当用户发送消息时,都会调用“generateChatResponse”方法。它获取用户的ID,并从HashMap中提取对话(如果存在的话),如果不存在,则创建一个新对话。

我不知道要尝试什么。

我不想清除整个HashMap,只想清除与不活动用户关联的条目。

英文:

I'm working on a chatbot powered by OpenAI. I'm using the new gpt-3.5-turbo model with ChatCompletion requests. I've already come up with a way for the bot to remember conversations for each individual user using a HashMap and it all works. The bot is able to remember all the previous responses and generate a new response using the history as context. However, the more responses in the query, the more tokens that it'll use, increasing costs. I want make it where if there is a certain amount of inactivity (like 2 minutes of not talking to the bot), it'll clear the history and start a fresh new conversation to save on tokens. What would be the best way to accomplish this?

Here is my code:

private static OpenAiService service;
private static Map&lt;String, List&lt;ChatMessage&gt;&gt; conversations = new HashMap&lt;String, List&lt;ChatMessage&gt;&gt;();
public static void initializeOpenAi() {
service = new OpenAiService(Settings.OPENAI_ACCESS_KEY);
}
public static String generateChatResponse(User user, String prompt) {
List&lt;ChatMessage&gt; conversation;
if (conversations.containsKey(user.getId())) {
conversation = conversations.get(user.getId());
} else {
conversation = new ArrayList&lt;ChatMessage&gt;();
}
if (conversation.size() &lt; 1) {
ChatMessage system = new ChatMessage();
system.setRole(&quot;system&quot;);
system.setContent(&quot;Omnis is a chatbot with sarcasm&quot;);
conversation.add(system);
}
ChatMessage userPrompt = new ChatMessage();
userPrompt.setRole(&quot;user&quot;);
userPrompt.setContent(prompt);
conversation.add(userPrompt);
ChatCompletionRequest chatRequest = ChatCompletionRequest.builder()
.model(&quot;gpt-3.5-turbo&quot;)
.maxTokens(1000)
.temperature(0.9)
.topP(0.3)
.frequencyPenalty(0.9)
.presencePenalty(0.0)
.messages(conversation)
.build();
ChatCompletionResult chatResult = null;
try {
chatResult = service.createChatCompletion(chatRequest);
} catch (Exception e) {
System.out.println(&quot;An OpenAI request failed!&quot;);
if (e.getMessage().contains(&quot;timeout&quot;)) {
return &quot;Your request timed out. Please try again after a breif wait for try a different request.&quot;;
}
if (e.getMessage().contains(&quot;Rate limit&quot;)) {
return &quot;Rate limit for chat requests has been reached!&quot;;
}
return &quot;Something went wrong with your request. Cause of error is &quot; + e.getMessage();
}
if (chatResult != null) {
System.out.println(&quot;Created chat completion request that used &quot; + chatResult.getUsage().getTotalTokens() + &quot; tokens with &quot; + chatResult.getModel());
}
String response = chatResult.getChoices().get(0).getMessage().getContent();
ChatMessage assistantPrompt = new ChatMessage();
assistantPrompt.setRole(&quot;assistant&quot;);
assistantPrompt.setContent(response);
conversation.add(assistantPrompt);
conversations.put(user.getId(), conversation);
return response;
}

The "generateChatResonse" method gets called each time a message is sent by a user. It get's the user's ID and pulls the conversation from the HashMap if it exists, if not it creates a new conversation.

I don't know what to try.

I don't want to clear the entire HashMap, just the entry associated with the inactive user.

答案1

得分: 1

I've added Guava to my project and replaced the Map with a LoadingCache object. It takes the same type of parameters and allows me to easily set the time before expiration.

private static LoadingCache<String, List<ChatMessage>> conversations;

public static void initializeOpenAi() {
	service = new OpenAiService(Settings.OPENAI_ACCESS_KEY);
		
	conversations = CacheBuilder.newBuilder()
			.maximumSize(10000)
			.expireAfterWrite(2, TimeUnit.MINUTES)
			.build(
			    new CacheLoader<String, List<ChatMessage>>() {
					@Override
					public List<ChatMessage> load(String key) throws Exception {
						return conversations.get(key);
					}
			    });
}

public static String generateChatResponse(User user, String prompt) {
	List<ChatMessage> conversation = conversations.getIfPresent(user.getId());
		
	if (conversation == null) {
		conversation = new ArrayList<ChatMessage>();
			
		ChatMessage system = new ChatMessage();
		system.setRole("system");
		system.setContent("Omnis is a chatbot with sarcasm");
			
		conversation.add(system);
	}

	// Remaining code is unchanged
}
英文:

I've added Guava to my project and replaced the Map with a LoadingCache object. It takes the same type of parameters and allows me to easily set the time before expiration.

private static LoadingCache&lt;String, List&lt;ChatMessage&gt;&gt; conversations;
public static void initializeOpenAi() {
service = new OpenAiService(Settings.OPENAI_ACCESS_KEY);
conversations = CacheBuilder.newBuilder()
.maximumSize(10000)
.expireAfterWrite(2, TimeUnit.MINUTES)
.build(
new CacheLoader&lt;String, List&lt;ChatMessage&gt;&gt;() {
@Override
public List&lt;ChatMessage&gt; load(String key) throws Exception {
return conversations.get(key);
}
});
}
public static String generateChatResponse(User user, String prompt) {
List&lt;ChatMessage&gt; conversation = conversations.getIfPresent(user.getId());
if (conversation == null) {
conversation = new ArrayList&lt;ChatMessage&gt;();
ChatMessage system = new ChatMessage();
system.setRole(&quot;system&quot;);
system.setContent(&quot;Omnis is a chatbot with sarcasm&quot;);
conversation.add(system);
}
// Remaining code is unchanged
}

答案2

得分: -1

检查是否有更改,如果没有,经过一段时间将其清除?

英文:

How about a thread ? Check if there are changes , and if not for an amount of time to clear it ?

huangapple
  • 本文由 发表于 2023年3月4日 02:32:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/75630689.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定