0

I'm using LangChain4j to define prompts using @UserMessage annotations, like this:

@UserMessage( "The alert is described as follows: {{description}}\n\n" + "HTTP response evidence:\n---\n{{evidence}}\n---\n" + "Additional context:\n---\n{{otherinfo}}") Confidence review(@V("description") String description, @V("evidence") String evidence, @V("otherinfo") String otherinfo); 

The problem: if otherinfo is null, the placeholder {{otherinfo}} is still rendered as the string "null" in the final prompt, which confuses the LLM. I want the otherinfo section to be excluded entirely if it's null or empty.

Is there a built-in way in LangChain4j to make prompt sections conditional based on variable values (e.g., skip {{otherinfo}} if it's null)? Or do I need to construct the prompt manually outside the annotation system?

Any advice or best practices appreciated.

1 Answer 1

0

You're right to look for a cleaner approach here. As of now, @UserMessage in LangChain4j doesn’t support conditional inclusion of prompt sections based on null or empty values. If a variable like otherinfo is null, it will be rendered as the string "null", which can confuse the LLM and degrade prompt quality.

Recommended approach is -

StringBuilder prompt = new StringBuilder(); prompt.append("The alert is described as follows: ").append(description).append("\n\n") .append("HTTP response evidence:\n---\n").append(evidence).append("\n---\n"); if (otherinfo != null && !otherinfo.isBlank()) { prompt.append("Additional context:\n---\n").append(otherinfo); } String finalPrompt = prompt.toString(); 

This way the other info is included only if it contains the content.

If you're building more complex prompts, a templating engine like Mustache or Thymeleaf can handle conditionals cleanly.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.