-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
111 lines (92 loc) · 2.56 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import { RunnableSequence } from "@langchain/core/runnables"
import { PromptTemplate } from "@langchain/core/prompts"
import { ChatOpenAI } from "@langchain/openai"
import { StringOutputParser } from "@langchain/core/output_parsers"
import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import { Neo4jGraphQL } from "@neo4j/graphql";
import neo4j from "neo4j-driver";
import { config } from "dotenv"
// Load .env file
config()
// Create driver instance
const driver = neo4j.driver(
process.env.NEO4J_URI,
neo4j.auth.basic(
process.env.NEO4J_USERNAME,
process.env.NEO4J_PASSWORD
)
);
// Type Defs
const typeDefs = `
interface CanGenerate {
generate(prompt: String!): GeneratedResponse!
}
type GeneratedResponse {
text: String!
}
type Movie implements CanGenerate {
title: String!
plot: String!
generateReview(stars: Int!): GeneratedResponse! @customResolver
generate(prompt: String!): GeneratedResponse! @customResolver
}
type ActedIn @relationshipProperties {
role: String
}
type Actor implements CanGenerate {
name: String!
born: Date
actedInMovies: [Movie!]! @relationship(type: "ACTED_IN", properties: "ActedIn", direction: OUT)
generate(prompt: String!): GeneratedResponse! @customResolver
}
`;
// Generate function
const generate = async (source, args) => {
const prompt = PromptTemplate.fromTemplate(args.prompt)
const model = new ChatOpenAI({
openAIApiKey: process.env.OPENAI_API_KEY,
model: args.model
})
const output = new StringOutputParser()
const chain = RunnableSequence.from([
prompt,
model,
output,
])
const input = Object.fromEntries(
Object.entries({...source, ...args}
)
.map(([ key, value]) => [
key,
typeof value === 'object' ? JSON.stringify(value) : value
]))
const res = await chain.invoke(input)
return { text: res }
}
// Assign resolver to many types
const withGenerateResolver = (types = []) =>
Object.fromEntries(
types.map(type => [
type,
{ generate }
])
)
const resolvers = withGenerateResolver(['Movie', 'Actor']);
// Define schema
const neoSchema = new Neo4jGraphQL({
typeDefs,
driver,
resolvers: withGenerateResolver(['Movie', 'Actor']),
});
// Create server
const server = new ApolloServer({
schema: await neoSchema.getSchema(),
resolvers,
});
// Listen
const { url } = await startStandaloneServer(server, {
context: async ({ req }) => ({ req }),
listen: { port: 4000 },
});
console.log(`🚀 Server ready at ${url}`);