Skip to content

Commit eb6877b

Browse files
committed
Reformat and cleanup some code
1 parent efafc1b commit eb6877b

File tree

14 files changed

+171
-154
lines changed

14 files changed

+171
-154
lines changed

content-retrievers/langchain4j-community-neo4j-retriever/src/main/java/dev/langchain4j/community/rag/content/retriever/neo4j/Neo4jGraph.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
import org.neo4j.driver.summary.ResultSummary;
1616

1717
public class Neo4jGraph implements AutoCloseable {
18+
1819
public record StructuredSchema(
1920
List<String> nodesProperties, List<String> relationshipsProperties, List<String> patterns) {}
2021

@@ -24,7 +25,7 @@ public record StructuredSchema(
2425

2526
private StructuredSchema structuredSchema;
2627

27-
public Neo4jGraph(final Driver driver, Long sample, Long maxRels) {
28+
public Neo4jGraph(Driver driver, Long sample, Long maxRels) {
2829

2930
this.sample = getOrDefault(sample, 1000L);
3031
this.maxRels = getOrDefault(maxRels, 100L);

content-retrievers/langchain4j-community-neo4j-retriever/src/main/java/dev/langchain4j/community/rag/content/retriever/neo4j/Neo4jGraphSchemaUtils.java

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,18 @@ class Neo4jGraphSchemaUtils {
1111

1212
static final String SCHEMA_FROM_META_DATA =
1313
"""
14-
CALL apoc.meta.data({maxRels: $maxRels, sample: $sample})
15-
YIELD label, other, elementType, type, property
16-
WITH label, elementType,
17-
apoc.text.join(collect(case when NOT type = "RELATIONSHIP" then property+": "+type else null end),", ") AS properties,
18-
collect(case when type = "RELATIONSHIP" AND elementType = "node" then "(:" + label + ")-[:" + property + "]->(:" + toString(other[0]) + ")" else null end) AS patterns
19-
WITH elementType AS type,
20-
collect(":"+label+" {"+properties+"}") AS entities,
21-
apoc.coll.flatten(collect(coalesce(patterns,[]))) AS patterns
22-
RETURN collect(case type when "relationship" then entities end)[0] AS relationships,
23-
collect(case type when "node" then entities end)[0] AS nodes,
24-
collect(case type when "node" then patterns end)[0] as patterns
25-
""";
14+
CALL apoc.meta.data({maxRels: $maxRels, sample: $sample})
15+
YIELD label, other, elementType, type, property
16+
WITH label, elementType,
17+
apoc.text.join(collect(case when NOT type = "RELATIONSHIP" then property+": "+type else null end),", ") AS properties,
18+
collect(case when type = "RELATIONSHIP" AND elementType = "node" then "(:" + label + ")-[:" + property + "]->(:" + toString(other[0]) + ")" else null end) AS patterns
19+
WITH elementType AS type,
20+
collect(":"+label+" {"+properties+"}") AS entities,
21+
apoc.coll.flatten(collect(coalesce(patterns,[]))) AS patterns
22+
RETURN collect(case type when "relationship" then entities end)[0] AS relationships,
23+
collect(case type when "node" then entities end)[0] AS nodes,
24+
collect(case type when "node" then patterns end)[0] as patterns
25+
""";
2626

2727
static Neo4jGraph.StructuredSchema getSchemaFromMetadata(Neo4jGraph graph, Long sample, Long maxRels) {
2828
final Record record = graph.executeRead(SCHEMA_FROM_META_DATA, Map.of("sample", sample, "maxRels", maxRels))

content-retrievers/langchain4j-community-neo4j-retriever/src/main/java/dev/langchain4j/community/rag/content/retriever/neo4j/Neo4jText2CypherRetriever.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -179,7 +179,7 @@ private RetrieveResult getRetrieveResult(Query query) {
179179
public String fromLLM(Query query) {
180180
RetrieveResult result = getRetrieveResult(query);
181181

182-
final Prompt prompt = FROM_LLM_PROMPT_TEMPLATE.apply(
182+
Prompt prompt = FROM_LLM_PROMPT_TEMPLATE.apply(
183183
Map.of("context", result.contents(), "cypher", result.cypherQuery(), "question", query.text()));
184184
String cypherQuery = chatModel.chat(prompt.text());
185185
return getBacktickText(cypherQuery);

embedding-stores/langchain4j-community-neo4j/src/main/java/dev/langchain4j/community/store/embedding/neo4j/HypotheticalQuestionGraphIngestor.java

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import static dev.langchain4j.internal.Utils.getOrDefault;
44

55
/**
6-
* A specialized ingestor for generating and storing hypothetical questions in a Neo4j graph database.
6+
* A specialized ingestor for generating and storing hypothetical questions in a Neo4j graph database.
77
* It implements the <a href="https://graphrag.com/reference/graphrag/hypothetical-question-retriever/">Hypothetical Question Retriever concept</a>
88
*
99
* <p>This ingestor is built on top of {@link Neo4jEmbeddingStoreIngestor} and is designed to process
@@ -31,11 +31,11 @@ public static class Builder extends Neo4jEmbeddingStoreIngestor.Builder {
3131

3232
private static final String DEFAULT_RETRIEVAL_QUERY =
3333
"""
34-
MATCH (node)<-[:HAS_QUESTION]-(parent)
35-
WITH parent, max(score) AS score, node // deduplicate parents
36-
RETURN parent.text AS text, score, properties(node) AS metadata
37-
ORDER BY score DESC
38-
LIMIT $maxResults""";
34+
MATCH (node)<-[:HAS_QUESTION]-(parent)
35+
WITH parent, max(score) AS score, node // deduplicate parents
36+
RETURN parent.text AS text, score, properties(node) AS metadata
37+
ORDER BY score DESC
38+
LIMIT $maxResults""";
3939

4040
private static final String DEFAULT_PARENT_QUERY =
4141
"""
@@ -52,17 +52,17 @@ RETURN count(*)
5252

5353
private static final String DEFAULT_SYSTEM_PROMPT =
5454
"""
55-
You are generating hypothetical questions based on the information found in the text.
56-
Make sure to provide full context in the generated questions.
57-
""";
55+
You are generating hypothetical questions based on the information found in the text.
56+
Make sure to provide full context in the generated questions.
57+
""";
5858

5959
private static final String DEFAULT_USER_PROMPT =
6060
"""
61-
Use the given format to generate hypothetical questions from the following input:
62-
{{input}}
61+
Use the given format to generate hypothetical questions from the following input:
62+
{{input}}
6363
64-
Hypothetical questions:
65-
""";
64+
Hypothetical questions:
65+
""";
6666
public static final String DEFAULT_CHUNK_CREATION_QUERY = "CREATE (:QuestionChunk $metadata)";
6767

6868
private Neo4jEmbeddingStore defaultEmbeddingStore() {

embedding-stores/langchain4j-community-neo4j/src/main/java/dev/langchain4j/community/store/embedding/neo4j/Neo4jEmbeddingStore.java

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -398,7 +398,7 @@ public EmbeddingSearchResult<TextSegment> search(EmbeddingSearchRequest request)
398398
/*
399399
Private methods
400400
*/
401-
private EmbeddingSearchResult getSearchResUsingVectorSimilarity(
401+
private EmbeddingSearchResult<TextSegment> getSearchResUsingVectorSimilarity(
402402
EmbeddingSearchRequest request, Filter filter, Value embeddingValue, Session session) {
403403
/* Build an
404404
CYPHER runtime = parallel parallelRuntimeSupport=all
@@ -635,9 +635,9 @@ private boolean indexExists() {
635635
if (!resIndex.hasNext()) {
636636
return false;
637637
}
638-
Record record = resIndex.single();
639-
List<String> idxLabels = record.get("labelsOrTypes").asList(Value::asString);
640-
List<Object> idxProps = record.get("properties").asList();
638+
Record singleRecord = resIndex.single();
639+
List<String> idxLabels = singleRecord.get("labelsOrTypes").asList(Value::asString);
640+
List<Object> idxProps = singleRecord.get("properties").asList();
641641

642642
boolean isIndexDifferent = !idxLabels.equals(singletonList(this.label))
643643
|| !idxProps.equals(singletonList(this.embeddingProperty));
@@ -781,8 +781,7 @@ public Builder retrievalQuery(String retrievalQuery) {
781781
}
782782

783783
/**
784-
* @param entityCreationQuery the optional entity creation query (default: {@link Neo4jEmbeddingStore#ENTITIES_CREATION})
785-
*
784+
* @param entityCreationQuery the optional entity creation query (default: {@link Neo4jEmbeddingStore#ENTITIES_CREATION})
786785
*/
787786
public Builder entityCreationQuery(String entityCreationQuery) {
788787
this.entityCreationQuery = entityCreationQuery;

embedding-stores/langchain4j-community-neo4j/src/main/java/dev/langchain4j/community/store/embedding/neo4j/Neo4jEmbeddingStoreIngestor.java

Lines changed: 28 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -96,29 +96,29 @@ public Neo4jEmbeddingStoreIngestor(Builder builder) {
9696
* <li>Embedding generation and storage of segments into Neo4j</li>
9797
* </ul>
9898
*
99-
* @param documentTransformer The {@link DocumentTransformer} applied to the original documents.
100-
* @param documentSplitter The {@link DocumentSplitter} used to split documents into parent segments.
101-
* @param textSegmentTransformer The {@link TextSegmentTransformer} applied to parent segments.
99+
* @param documentTransformer The {@link DocumentTransformer} applied to the original documents.
100+
* @param documentSplitter The {@link DocumentSplitter} used to split documents into parent segments.
101+
* @param textSegmentTransformer The {@link TextSegmentTransformer} applied to parent segments.
102102
* @param childTextSegmentTransformer The {@link TextSegmentTransformer} applied to child segments.
103-
* @param embeddingModel The {@link EmbeddingModel} used to generate embeddings from text segments.
104-
* @param embeddingStore The {@link EmbeddingStore} (specifically {@link Neo4jEmbeddingStore}) used to persist embeddings.
105-
* @param documentChildSplitter The {@link DocumentSplitter} used to generate child segments from parent segments.
106-
* @param driver The {@link Driver} used to execute Cypher queries against the Neo4j database.
107-
* @param query The Cypher query used to insert processed segments and metadata into Neo4j.
108-
* @param parentIdKey The metadata key used to extract the parent segment ID; if absent, a UUID will be generated.
109-
* @param params Additional query parameters to include in the Cypher execution, beyond segment metadata and text.
110-
* @param systemPrompt A system prompt for manipulating parent segment text via a {@link ChatModel}. Ignored if {@code questionModel} is {@code null}.
111-
* @param userPrompt A user prompt for manipulating parent segment text via a {@link ChatModel}. Ignored if {@code questionModel} is {@code null}.
112-
* @param questionModel A {@link ChatModel} used to further transform parent segment text based on provided prompts. If {@code null}, no chat-based manipulation occurs.
103+
* @param embeddingModel The {@link EmbeddingModel} used to generate embeddings from text segments.
104+
* @param embeddingStore The {@link EmbeddingStore} (specifically {@link Neo4jEmbeddingStore}) used to persist embeddings.
105+
* @param documentChildSplitter The {@link DocumentSplitter} used to generate child segments from parent segments.
106+
* @param driver The {@link Driver} used to execute Cypher queries against the Neo4j database.
107+
* @param query The Cypher query used to insert processed segments and metadata into Neo4j.
108+
* @param parentIdKey The metadata key used to extract the parent segment ID; if absent, a UUID will be generated.
109+
* @param params Additional query parameters to include in the Cypher execution, beyond segment metadata and text.
110+
* @param systemPrompt A system prompt for manipulating parent segment text via a {@link ChatModel}. Ignored if {@code questionModel} is {@code null}.
111+
* @param userPrompt A user prompt for manipulating parent segment text via a {@link ChatModel}. Ignored if {@code questionModel} is {@code null}.
112+
* @param questionModel A {@link ChatModel} used to further transform parent segment text based on provided prompts. If {@code null}, no chat-based manipulation occurs.
113113
*/
114114
public Neo4jEmbeddingStoreIngestor(
115-
final DocumentTransformer documentTransformer,
116-
final DocumentSplitter documentSplitter,
115+
DocumentTransformer documentTransformer,
116+
DocumentSplitter documentSplitter,
117117
TextSegmentTransformer textSegmentTransformer,
118118
TextSegmentTransformer childTextSegmentTransformer,
119-
final EmbeddingModel embeddingModel,
120-
final Neo4jEmbeddingStore embeddingStore,
121-
final DocumentSplitter documentChildSplitter,
119+
EmbeddingModel embeddingModel,
120+
Neo4jEmbeddingStore embeddingStore,
121+
DocumentSplitter documentChildSplitter,
122122
Driver driver,
123123
String query,
124124
String parentIdKey,
@@ -152,7 +152,7 @@ private TextSegmentTransformer getTextSegmentTransformer() {
152152
return segment -> {
153153
TextSegment parentSegment = getTextSegmentWithUniqueId(segment, neo4jEmbeddingStore.getIdProperty(), null);
154154
String textInput = parentSegment.text();
155-
final Map<String, Object> metadataMap = segment.metadata().toMap();
155+
Map<String, Object> metadataMap = segment.metadata().toMap();
156156
String parentId = "parent_" + UUID.randomUUID();
157157
metadataMap.put(parentIdKey, parentId);
158158
String text;
@@ -161,22 +161,19 @@ private TextSegmentTransformer getTextSegmentTransformer() {
161161
throw new RuntimeException(
162162
"Prompts cannot be null: systemPrompt=" + systemPrompt + ", userPrompt=" + userPrompt);
163163
}
164-
final SystemMessage systemMessage = Prompt.from(systemPrompt).toSystemMessage();
165-
166-
final PromptTemplate userTemplate = PromptTemplate.from(userPrompt);
167-
168-
final UserMessage userMessage =
164+
SystemMessage systemMessage = Prompt.from(systemPrompt).toSystemMessage();
165+
PromptTemplate userTemplate = PromptTemplate.from(userPrompt);
166+
UserMessage userMessage =
169167
userTemplate.apply(Map.of("input", textInput)).toUserMessage();
170-
171-
final List<ChatMessage> chatMessages = List.of(systemMessage, userMessage);
168+
List<ChatMessage> chatMessages = List.of(systemMessage, userMessage);
172169

173170
text = this.questionModel.chat(chatMessages).aiMessage().text();
174171
} else {
175172
text = textInput;
176173
}
177174
metadataMap.putIfAbsent("text", text);
178175

179-
final Map<String, Object> params = new HashMap<>(Map.of("metadata", metadataMap));
176+
Map<String, Object> params = new HashMap<>(Map.of("metadata", metadataMap));
180177
params.put(parentIdKey, parentId);
181178
getAdditionalParams(parentId);
182179
metadataMap.putAll(this.params);
@@ -193,14 +190,14 @@ private TextSegmentTransformer getDefaultChildTextSegmentTransformer() {
193190
}
194191

195192
private void getAdditionalParams(String parentId) {
196-
final Map<String, Object> params = new HashMap<>(this.params);
193+
Map<String, Object> params = new HashMap<>(this.params);
197194
params.put(parentIdKey, parentId);
198195
neo4jEmbeddingStore.setAdditionalParams(params);
199196
}
200197

201198
public static TextSegment getTextSegmentWithUniqueId(TextSegment segment, String idProperty, String parentId) {
202-
final Metadata metadata1 = segment.metadata();
203-
final Object idMeta = metadata1.toMap().get(idProperty);
199+
Metadata metadata1 = segment.metadata();
200+
Object idMeta = metadata1.toMap().get(idProperty);
204201
String value = parentId == null ? randomUUID() : parentId + "_" + randomUUID();
205202
if (idMeta != null) {
206203
value = idMeta + "_" + value;
@@ -219,6 +216,7 @@ public static Neo4jEmbeddingStoreIngestor.Builder builder() {
219216
}
220217

221218
public static class Builder extends ParentChildEmbeddingStoreIngestor.Builder<Builder> {
219+
222220
protected Driver driver;
223221
protected String query;
224222
protected String parentIdKey;

embedding-stores/langchain4j-community-neo4j/src/main/java/dev/langchain4j/community/store/embedding/neo4j/Neo4jEmbeddingUtils.java

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import static org.neo4j.cypherdsl.support.schema_name.SchemaNames.sanitize;
44

5+
import dev.langchain4j.Internal;
56
import dev.langchain4j.data.document.Metadata;
67
import dev.langchain4j.data.embedding.Embedding;
78
import dev.langchain4j.data.segment.TextSegment;
@@ -16,6 +17,7 @@
1617
import org.neo4j.driver.Value;
1718
import org.neo4j.driver.Values;
1819

20+
@Internal
1921
class Neo4jEmbeddingUtils {
2022

2123
private Neo4jEmbeddingUtils() throws InstantiationException {

embedding-stores/langchain4j-community-neo4j/src/main/java/dev/langchain4j/community/store/embedding/neo4j/Neo4jFilterMapper.java

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77

88
import com.fasterxml.jackson.databind.ObjectMapper;
99
import com.fasterxml.jackson.databind.json.JsonMapper;
10+
import dev.langchain4j.Internal;
1011
import dev.langchain4j.store.embedding.filter.Filter;
1112
import dev.langchain4j.store.embedding.filter.comparison.IsEqualTo;
1213
import dev.langchain4j.store.embedding.filter.comparison.IsGreaterThan;
@@ -29,9 +30,12 @@
2930
import org.neo4j.driver.internal.value.ListValue;
3031
import org.neo4j.driver.internal.value.PointValue;
3132

32-
public class Neo4jFilterMapper {
33+
@Internal
34+
class Neo4jFilterMapper {
3335

34-
public static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
36+
static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();
37+
38+
static final String UNSUPPORTED_FILTER_TYPE_ERROR = "Unsupported filter type: ";
3539

3640
private static FunctionInvocation convertToPoint(PointValue value1) {
3741
try {
@@ -47,7 +51,7 @@ private static FunctionInvocation convertToPoint(PointValue value1) {
4751
* The {@link Cypher#literalOf(Object)} doesn't handle all data types,
4852
* so we use this method to transform non-managed data
4953
*/
50-
public static Expression toCypherLiteral(Object value) {
54+
static Expression toCypherLiteral(Object value) {
5155
if (value instanceof OffsetDateTime) {
5256
return Cypher.datetime(literalOf(value.toString()));
5357
}
@@ -65,15 +69,13 @@ public static Expression toCypherLiteral(Object value) {
6569
return literalOf(value);
6670
}
6771

68-
public static String UNSUPPORTED_FILTER_TYPE_ERROR = "Unsupported filter type: ";
69-
70-
private Node node;
72+
private final Node node;
7173

72-
public Neo4jFilterMapper(Node node) {
74+
Neo4jFilterMapper(Node node) {
7375
this.node = node;
7476
}
7577

76-
public Condition getCondition(Filter filter) {
78+
Condition getCondition(Filter filter) {
7779
if (filter instanceof IsEqualTo item) {
7880
Expression cypherLiteral = toCypherLiteral(item.key());
7981
Expression cypherLiteral1 = toCypherLiteral(item.comparisonValue());
@@ -114,13 +116,13 @@ public Condition getCondition(Filter filter) {
114116
}
115117
}
116118

117-
public Condition mapIn(IsIn filter) {
119+
Condition mapIn(IsIn filter) {
118120
Expression cypherLiteral = toCypherLiteral(filter.key());
119121
Expression cypherLiteral1 = toCypherLiteral(filter.comparisonValues());
120122
return Cypher.includesAny(node.property(cypherLiteral), cypherLiteral1);
121123
}
122124

123-
public Condition mapNotIn(IsNotIn filter) {
125+
Condition mapNotIn(IsNotIn filter) {
124126
Expression cypherLiteral = toCypherLiteral(filter.key());
125127
Expression cypherLiteral1 = toCypherLiteral(filter.comparisonValues());
126128
Condition condition1 = Cypher.includesAny(node.property(cypherLiteral), cypherLiteral1);

embedding-stores/langchain4j-community-neo4j/src/main/java/dev/langchain4j/community/store/embedding/neo4j/Neo4jUtils.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,10 @@
66
@Internal
77
class Neo4jUtils {
88

9+
private Neo4jUtils() throws InstantiationException {
10+
throw new InstantiationException("Cannot instantiate utility class.");
11+
}
12+
913
static FunctionInvocation.FunctionDefinition functionDef(String functionName) {
1014
return new FunctionInvocation.FunctionDefinition() {
1115

0 commit comments

Comments
 (0)