Class SocialTRLLMServiceProvider
java.lang.Object
edu.tufts.hrilab.diarc.DiarcComponent
edu.tufts.hrilab.llm.LLMServiceProvider
edu.tufts.hrilab.llm.serviceproviders.tr.social.SocialTRLLMServiceProvider
- Direct Known Subclasses:
SocialAvaLLMServiceProvider,SocialSpotLLMServiceProvider
-
Field Summary
FieldsModifier and TypeFieldDescriptionprotected final Map<org.apache.commons.lang3.tuple.Pair<Symbol,Symbol>, List<ChatContext>> Extended History of chat contexts, stored for reference from ITK actions for the LLM to conditionally retrieve information about past interactions without cluttering current chat context.protected final Map<org.apache.commons.lang3.tuple.Pair<Symbol,Symbol>, ChatCollection> Maintained set of ChatCollections, split by user/AgentTeam pair Contains all relevant conversation contexts and their managed histories between each pairPrompt variables to be replaced in sent Completion requests.Fields inherited from class edu.tufts.hrilab.llm.LLMServiceProvider
agentHierarchy, conversationMappings, counter, currentConversations, language, learnedActions, trackDialogueHistory, trackLearnedActionsFields inherited from class edu.tufts.hrilab.diarc.DiarcComponent
executionLoopCycleTime, log, shouldRunExecutionLoop -
Constructor Summary
Constructors -
Method Summary
Modifier and TypeMethodDescriptionaddToolResponse(Symbol user, Symbol agentTeam, String toolResponse, String toolCallName) Method used by "social LLM" itk behaviors (llm to/from diarc itk) to add DIARC's response to an ITK request and then call the Completion endpoint with the updated Chat for a text response.addVisionResponse(Symbol user, Symbol agentTeam, String visionData, String toolCallName) protected CompletioncallChatCompletion(Chat chat, List<ToolDefinition> tools) callChatCompletionForTextResponse(Symbol user, Symbol agentTeam, long id) protected CompletioncallChatCompletionStreaming(Chat chat, List<ToolDefinition> tools, long uid) cancelLLMChatContext(Symbol user, Symbol agentTeam, long cid) convertSemanticsToTextLLMService(Utterance utterance) convertSemanticsToTextLLMService(Utterance utterance, boolean streamingSayText) Main NLG method used by LLMNLGComponentprotected abstract StringcorrectCommonNLUMistakes(Utterance utterance) voidendChatContext(Symbol user, Symbol agentTeam) Method to discard the current chat context.protected voidThis is where any code that needs to be called repeatedly in a dedicated thread should live.focusDialogueChat(Symbol user, Symbol agentTeam, String contextIdentifier, long cid) Transfer to a focused context chat.protected abstract Map<String,ChatTemplates> generateInstructTools(boolean xml) protected Stringprotected Stringprotected Stringprotected StringgetChatCollection(Symbol user, Symbol agentTeam) getChatHistory(Symbol user, Symbol agentTeam) getChatHistoryAsJSON(Symbol user, Symbol agentTeam) getChatHistoryAsString(Symbol user, Symbol agentTeam) getChatHistoryAsString(Chat chat) getChatHistoryAsString(List<Message> messages, int numMessages) getContextDependentTools(Symbol agentTeam) getContextTransferFillerPhrase(String contextId, long cid, Symbol user, Symbol agent) getContextTransferResponseUtterance(long cid) Utility to get second LLM response on transfer to a focused context (see comments above contextTransferResponseUtterance for an explanation)getCurrentGoals(Symbol agent) protected StringgetCurrentGoalsSummary(Symbol agent) protected StringgetCurrentQuestionsString(Symbol agent) getExtendedConversationHistories(Symbol user, Symbol agentTeam) getExtendedConversationHistoryString(Symbol user, Symbol agentTeam) protected Stringprotected Stringprotected Stringprotected StringgetFullGoalsSummary(Symbol agent) protected PromptbooleangetLastResponseStreamed(Symbol user, Symbol agentTeam) getLastResponseString(Symbol user, Symbol agentTeam) intgetLLMConversationLength(Symbol user, Symbol agentTeam) Method used in nlu.asl to understand on positive validation of a command whether the command was a first-time instruction or part of an extended, contextual dialogue.protected Promptprotected PromptgetPendingGoals(Symbol agent) protected PromptList of types handled by consultants in the system - when encountering symbols with these types during NLG preprocessing/NLU postprocessing, replaces references with descriptors/typed descriptors with variables.getScheduledGoals(Symbol agent) protected Promptprotected PromptvoidvoidhandleTextResponse(Completion llmResponse, Utterance inputUtterance, ChatContext chatContext, StringBuilder errorResponseBuilder, boolean streaming) Method for handling Completion responses containing Text responses.handleToolResponse(Completion llmResponse, Utterance inputUtterance, ChatCollection chatCollection, List<ToolDefinition> advertisedToolList, StringBuilder errorResponseBuilder, boolean useStreaming) Method for handling Completion responses containing Tool calls, 3 main cases: - Base: Return an Utterance populated with the Tool's underlying semantics.handleValidationResponse(Completion llmResponse, Utterance inputUtterance, ChatCollection chatCollection, List<ToolDefinition> advertisedToolList, StringBuilder errorResponseBuilder, boolean useStreaming) Method for handling Completion responses containing during validation.booleaninExtendedParseLoop(Symbol user, Symbol agentTeam) Method for HybridParser/NLG components to prevent use of other parser/NLG components once entering an extended interactionvoidinit()Perform any component initialization.protected voidbooleaninterruptWaitOnFocusedChat(Symbol user, Symbol agentTeam, long cid) Interruption method forwaitOnFocusedChat(Symbol, Symbol, long)Unlocks current chatContext for user/agentTeam pair if matching supplied Context IDparseUtteranceLLMService(Utterance utterance) parseUtteranceLLMService(Utterance utterance, boolean useStreaming) parseUtteranceLLMService(Utterance utterance, boolean useStreaming, boolean reattemptedParse) Main NLU method used by LLMParserComponentprotected SymbolprocessArbitraryToolArgument(String argumentName, Object argumentValue, ToolParameterV2 argumentDefinition, String parentArgumentName, Symbol actor, Utterance.Builder builder, Map<Symbol, Variable> varMap, StringBuilder errorMessage, boolean unpopulatedArgSafe, boolean emptyArgAllowed) protected SymbolprocessMapArgument(String name, Object arguments, ToolParameterV2 parameterDefinition, boolean includeActor, Symbol actor, Utterance.Builder builder, Map<Symbol, Variable> varMap, StringBuilder errorMessage, boolean unpopulatedArgSafe, boolean emptyArgAllowed) protected SymbolprocessSymbolArgument(String argName, String argString, List<String> possible_values, StringBuilder errorMessage, Map<Symbol, Variable> varMap, Utterance.Builder builder, boolean inner, boolean unpopulatedArgSafe, boolean emptyArgAllowed) voidquestionAskingCallback(Symbol agent, boolean active, Question question) Question asking notification callback - throw away the current chat context if the associated system validation question timed out without a response.booleanreattemptParse(Utterance utterance, boolean streamingTTS) Method called from nlu.asl after negative validation of an LLM parse.voidresumeLLMChatContext(Symbol user, Symbol agentTeam, long cid) voidstreamingChunkHandler(OpenaiChatCompletionResponse lastChunk, OpenaiChatCompletionResponse currentResponse, Chat currentChat) suspendLLMChatContext(Symbol user, Symbol agentTeam, long cid) protected StringtoolToDescString(Tool tool, boolean includePossibleValues) Convert a Tool definition to a description string for the LLM to use as reference - want to give the information of what may have been called by the system previously or what can be used as an inner argument to another tool without actually advertising these actions as valid Tools themselves (e.g.updateDomainPromptVars(Utterance utterance, boolean parsing) updateFocusedContextPromptVars(Symbol user, Symbol agent) voidupdateLLMConversationHistory(Utterance utterance, boolean newUtterance) Experimenting adding messages to ChatContexts from dialogue history updates (**currently NLG only) in case output from external parsers or generators is chosen over this one.protected voidupdatePromptVars(Utterance utterance, boolean parsing) Update prompt variables whose values need to be explicitly retrieved at call time TODO: a lot of these can be updated to be held internally and updated on eventsvoidusedLLMParse(Symbol user, Symbol agentTeam) voidwaitOnFocusedChat(Symbol user, Symbol agentTeam, long cid) Method to wait for termination of a focused ChatContext; currently only called from runContextSpecificChat in nlu.asl.Methods inherited from class edu.tufts.hrilab.llm.LLMServiceProvider
callChatEndpoint, clearConversationHistory, endLLMConversation, endLLMConversation, endLLMConversation, endLLMConversation, getConversationHistory, getConversationHistory, getDescendants, getUntypedSymbol, registerForNotifications, setLanguage, shutdownComponent, startLLMConversation, startLLMConversation, startLLMConversationMethods inherited from class edu.tufts.hrilab.diarc.DiarcComponent
additionalUsageInfo, attachShutdownHook, createInstance, createInstance, createInstance, getMyGroupConstraints, getMyGroups, getMyService, getMyServices, main, parseArgs, postRegistrationInit, shutdown
-
Field Details
-
currentChatCollections
protected final Map<org.apache.commons.lang3.tuple.Pair<Symbol,Symbol>, currentChatCollectionsChatCollection> Maintained set of ChatCollections, split by user/AgentTeam pair Contains all relevant conversation contexts and their managed histories between each pair -
chatContextHistories
protected final Map<org.apache.commons.lang3.tuple.Pair<Symbol,Symbol>, chatContextHistoriesList<ChatContext>> Extended History of chat contexts, stored for reference from ITK actions for the LLM to conditionally retrieve information about past interactions without cluttering current chat context. -
promptVars
Prompt variables to be replaced in sent Completion requests. Refer to the Prompt class and apply method if this notion is unfamiliar to you.
-
-
Constructor Details
-
SocialTRLLMServiceProvider
public SocialTRLLMServiceProvider()
-
-
Method Details
-
initDomainPromptVars
-
updateDomainPromptVars
-
getRefTypes
List of types handled by consultants in the system - when encountering symbols with these types during NLG preprocessing/NLU postprocessing, replaces references with descriptors/typed descriptors with variables. -
getNluSystemPrompt
-
getNlgSystemPrompt
-
getValidationNLUSystemPrompt
-
getValidationNLGSystemPrompt
-
getQuestionAnswerSystemPrompt
-
getGoalTranslationPrompt
-
generateInstructTools
-
generateITKTools
-
generateReplyTools
-
generateFocusedContextChatTemplates
-
correctCommonNLUMistakes
-
init
public void init()Description copied from class:DiarcComponentPerform any component initialization. This should not be used for setting local fields to default values as was the case in DIARC. This method is called after the constructor, and after parseArgs. Setting default values should be done in field declaration or in the constructor.- Overrides:
initin classLLMServiceProvider
-
executionLoop
protected void executionLoop()Description copied from class:DiarcComponentThis is where any code that needs to be called repeatedly in a dedicated thread should live. It is not called by default and you must set shouldRunExecutionLoop to true in your constructor.- Overrides:
executionLoopin classLLMServiceProvider
-
initPromptVars
-
updatePromptVars
Update prompt variables whose values need to be explicitly retrieved at call time TODO: a lot of these can be updated to be held internally and updated on events -
updateFocusedContextPromptVars
-
getContextDependentTools
-
parseUtteranceLLMService
- Specified by:
parseUtteranceLLMServicein classLLMServiceProvider
-
parseUtteranceLLMService
- Specified by:
parseUtteranceLLMServicein classLLMServiceProvider
-
parseUtteranceLLMService
public Utterance parseUtteranceLLMService(Utterance utterance, boolean useStreaming, boolean reattemptedParse) Main NLU method used by LLMParserComponent- Parameters:
utterance- Utterance with populated words to parse to semanticsreattemptedParse- Whether this is a followup call after negative user validation (so we do not update the Chat history with the same utterance more than once)- Returns:
- The utterance with populated semantics, or null if no valid parse is found
-
handleToolResponse
public Utterance handleToolResponse(Completion llmResponse, Utterance inputUtterance, ChatCollection chatCollection, List<ToolDefinition> advertisedToolList, StringBuilder errorResponseBuilder, boolean useStreaming) Method for handling Completion responses containing Tool calls, 3 main cases: - Base: Return an Utterance populated with the Tool's underlying semantics. In the case of an external cache hit, the context will be discarded and handleValidatedToolResponse will be called from the corresponding dialogue history update. - LLM ITK - will return semantics for goal without validation (Underlying semantics should match a SKIPPENDING priority goal which callsaddToolResponse(Symbol, Symbol, String, String)) - Invalid parse - Add a system error message to the Chat, call the completion again, and return a text response to the user with the result - *NEW* Stand-in tool(s) for text responses - Experimenting targeting a specific tool to give text responses rather than using handleTextResponse above with promising initial success. Allowing the LLM to target text responses or tool calls was giving it a hard time calling tools rather than just saying it performed the underlying functionality. -
handleTextResponse
public Utterance handleTextResponse(Completion llmResponse, Utterance inputUtterance, ChatContext chatContext, StringBuilder errorResponseBuilder, boolean streaming) Method for handling Completion responses containing Text responses. Add directly as assistant message to history and return generateResponseFromString semantics with needsValidation set to false -
handleValidationResponse
public Utterance handleValidationResponse(Completion llmResponse, Utterance inputUtterance, ChatCollection chatCollection, List<ToolDefinition> advertisedToolList, StringBuilder errorResponseBuilder, boolean useStreaming) Method for handling Completion responses containing during validation. -
inExtendedParseLoop
Method for HybridParser/NLG components to prevent use of other parser/NLG components once entering an extended interaction- Specified by:
inExtendedParseLoopin classLLMServiceProvider
-
usedLLMParse
-
getLLMConversationLength
Method used in nlu.asl to understand on positive validation of a command whether the command was a first-time instruction or part of an extended, contextual dialogue. Necessary to know what Utterance's are safe to cache.- Overrides:
getLLMConversationLengthin classLLMServiceProvider
-
reduceChatContextHistory
public void reduceChatContextHistory() -
reattemptParse
Method called from nlu.asl after negative validation of an LLM parse. Adds a system message informing the LLM of what occurred and calling the completion endpoint again with the user response. May result in an updated tool call or a text response for the user. -
convertSemanticsToTextLLMService
- Specified by:
convertSemanticsToTextLLMServicein classLLMServiceProvider
-
convertSemanticsToTextLLMService
Main NLG method used by LLMNLGComponent- Specified by:
convertSemanticsToTextLLMServicein classLLMServiceProvider- Parameters:
utterance- Utterance with populated semantics to transform to wordsstreamingSayText- - whether the response should be feed incrementally to TTS using a streaming Completion- Returns:
- The utterance with populated words, or null if no generation could be formed
-
focusDialogueChat
public Utterance focusDialogueChat(Symbol user, Symbol agentTeam, String contextIdentifier, long cid) Transfer to a focused context chat. Only called through runContextSpecificChat in nlu.asl - specific assumptions and logic made around this method, do not call this method from elsewhere without fully understanding what you are doing. -
interruptWaitOnFocusedChat
Interruption method forwaitOnFocusedChat(Symbol, Symbol, long)Unlocks current chatContext for user/agentTeam pair if matching supplied Context ID -
waitOnFocusedChat
Method to wait for termination of a focused ChatContext; currently only called from runContextSpecificChat in nlu.asl.- Parameters:
user- external interactor who is a part of this conversationagentTeam- DIARC AgentTeam which is a part of this conversationcid- unique identifier for this focused chat context ("context ID" as in DIARC Context class ID)
-
getContextTransferResponseUtterance
Utility to get second LLM response on transfer to a focused context (see comments above contextTransferResponseUtterance for an explanation) -
callChatCompletion
-
streamingChunkHandler
public void streamingChunkHandler(OpenaiChatCompletionResponse lastChunk, OpenaiChatCompletionResponse currentResponse, Chat currentChat) -
callChatCompletionStreaming
-
endChatContext
Method to discard the current chat context. Currently only used when validation questions expire (should be used for general nonactivity timeout as well) -
getChatCollection
-
callChatCompletionForTextResponse
-
addVisionResponse
-
addToolResponse
public Utterance addToolResponse(Symbol user, Symbol agentTeam, String toolResponse, String toolCallName) Method used by "social LLM" itk behaviors (llm to/from diarc itk) to add DIARC's response to an ITK request and then call the Completion endpoint with the updated Chat for a text response. -
suspendLLMChatContext
-
resumeLLMChatContext
-
cancelLLMChatContext
-
getCurrentGoals
-
getPendingGoals
-
getScheduledGoals
-
getCurrentGoalsSummary
-
getFullGoalsSummary
-
getExtendedConversationHistories
-
getExtendedConversationHistoryString
-
getCurrentQuestionsString
-
getLearnedActionPredicates
-
initLearnedActions
protected void initLearnedActions()- Overrides:
initLearnedActionsin classLLMServiceProvider
-
handleDatabaseAddition
public void handleDatabaseAddition(ActionDBEntry entry) throws ai.thinkingrobots.trade.TRADEException - Overrides:
handleDatabaseAdditionin classLLMServiceProvider- Throws:
ai.thinkingrobots.trade.TRADEException
-
handleDatabaseRemoval
public void handleDatabaseRemoval(ActionDBEntry entry) throws ai.thinkingrobots.trade.TRADEException - Overrides:
handleDatabaseRemovalin classLLMServiceProvider- Throws:
ai.thinkingrobots.trade.TRADEException
-
getInstructableActions
-
updateLLMConversationHistory
Experimenting adding messages to ChatContexts from dialogue history updates (**currently NLG only) in case output from external parsers or generators is chosen over this one. (If intending to do the same for NLU, need to first stop adding messages directly in parseUtterance)- Overrides:
updateLLMConversationHistoryin classLLMServiceProvider
-
questionAskingCallback
Question asking notification callback - throw away the current chat context if the associated system validation question timed out without a response. -
processArbitraryToolArgument
protected Symbol processArbitraryToolArgument(String argumentName, Object argumentValue, ToolParameterV2 argumentDefinition, String parentArgumentName, Symbol actor, Utterance.Builder builder, Map<Symbol, Variable> varMap, StringBuilder errorMessage, boolean unpopulatedArgSafe, boolean emptyArgAllowed) -
processMapArgument
protected Symbol processMapArgument(String name, Object arguments, ToolParameterV2 parameterDefinition, boolean includeActor, Symbol actor, Utterance.Builder builder, Map<Symbol, Variable> varMap, StringBuilder errorMessage, boolean unpopulatedArgSafe, boolean emptyArgAllowed) -
processSymbolArgument
protected Symbol processSymbolArgument(String argName, String argString, List<String> possible_values, StringBuilder errorMessage, Map<Symbol, Variable> varMap, Utterance.Builder builder, boolean inner, boolean unpopulatedArgSafe, boolean emptyArgAllowed) -
getChatHistory
-
getChatHistoryAsJSON
-
getChatHistoryAsString
-
getChatHistoryAsString
-
getChatHistoryAsString
-
getLastResponseString
-
getLastResponseStreamed
-
toolToDescString
Convert a Tool definition to a description string for the LLM to use as reference - want to give the information of what may have been called by the system previously or what can be used as an inner argument to another tool without actually advertising these actions as valid Tools themselves (e.g. NLG, goal scheduling, action ITK) (TODO: keep an eye on this, this information can not be formatted in a way familiar to the LLM as a tool call, or else it will try to call it) -
getContextTransferFillerPhrase
-
getBaseRoleDescription
-
getBaseContextualInformation
-
getBaseResponseConstraints
-
getBaseResponseStyle
-
getFocusedResponseConstraints
-
getFocusedResponseStyle
-
getFocusedResponsePolicy
-
getFocusedFinalInstruction
-