Views
No views yet
neo4j/text2cypher-gemma-2-9b-it-finetuned-2024v11import openai
2
3# Define the instruction and helper functions
4instruction = (
5 "Generate Cypher statement to query a graph database. "
6 "Use only the provided relationship types and properties in the schema. \n"
7 "Schema: {schema} \n Question: {question} \n Cypher output: "
8)
9
10def prepare_chat_prompt(question, schema):
11 # Build the messages list for the OpenAI API
12 return [
13 {
14 "role": "user",
15 "content": instruction.format(schema=schema, question=question),
16 }
17 ]
18
19def _postprocess_output_cypher(output_cypher: str) -> str:
20 # Remove any explanation text and code block markers
21 partition_by = "**Explanation:**"
22 output_cypher, _, _ = output_cypher.partition(partition_by)
23 output_cypher = output_cypher.strip("`\n")
24 output_cypher = output_cypher.lstrip("cypher\n")
25 output_cypher = output_cypher.strip("`\n ")
26 return output_cypher
27
28# Configure the OpenAI API endpoint to your Ollama server.
29# (Adjust the API base URL if your Ollama server is hosted at a different address/port.)
30openai.api_base = "http://localhost:11434/v1"
31openai.api_key = "YOUR_API_KEY" # Include if your setup requires an API key
32
33# Set the model name as used by Ollama (this should match the name configured on your Ollama server)
34model_name = "avinashm/text2cypher"
35
36# Define the question and schema
37question = "What are the movies of Tom Hanks?"
38schema = "(:Actor)-[:ActedIn]->(:Movie)"
39
40# Prepare the conversation messages
41messages = prepare_chat_prompt(question=question, schema=schema)
42
43# Call the API using similar generation parameters to your original script.
44response = openai.ChatCompletion.create(
45 model=model_name,
46 messages=messages,
47 temperature=0.2,
48 max_tokens=512, # equivalent to max_new_tokens in your original script
49 top_p=0.9,
50)
51
52# Extract and post-process the output
53raw_output = response["choices"][0]["message"]["content"]
54output = _postprocess_output_cypher(raw_output)
55
56print(output) In the dataset we used, the schemas are already provided.
They are created either by Directly using the schema the input data source provided OR
Creating schema using neo4j-graphrag package (Check: SchemaReader.get_schema(...) function)
In your own Neo4j database, you can utilize neo4j-graphrag package::SchemaReader functions1CALL apoc.meta.schema()
2CALL db.schema.visualization()1 x A100 PCIe
31 vCPU 117 GB RAM
runpod/pytorch:2.4.0-py3.11-cuda12.4.1-devel-ubuntu22.04
On-Demand - Secure Cloud
60 GB Disk
60 GB Pod Volume
Training Hyperparameters
lora_config = LoraConfig( r=64, lora_alpha=64, target_modules=target_modules, lora_dropout=0.05, bias="none", task_type="CAUSAL_LM", )
sft_config = SFTConfig( dataset_text_field=dataset_text_field, per_device_train_batch_size=4, gradient_accumulation_steps=8, dataset_num_proc=16, max_seq_length=1600, logging_dir="./logs", num_train_epochs=1, learning_rate=2e-5, save_steps=5, save_total_limit=1, logging_steps=5, output_dir="outputs", optim="paged_adamw_8bit", save_strategy="steps", )
bnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16, )