TroyDoesAI commited on
Commit
c301b38
·
verified ·
1 Parent(s): a3d42d1

Uploading a more advanced Prompt Engineering Generic Use Case Example using my model for a more indepth diagrams.

Browse files

Instead of High Level Diagrams we can extract more info from the context and generate more detailed diagrams.

Remember we always want to cue this model to to ensure no wasted tokens, make sure you prompt all the way up to ```mermaid for the model to guarantee it will only make a mermaid diagram and nothing else stopping at the closing code block marker, it is trained to explain the code from mermaid diagrams as well as additional input and can really surprise you how much more it understands when you give it code and a diagram as input.

View/Modify Mermaid Diagrams here: https://mermaid.live/edit#pako:eNqVll1z2jgUhv-K1jd7QzPYhibQ2d3hG_MRKJCkiciFFqugqS15ZbmTFPjvK0s22ATi1BcM9nksnXPe15K2xoq52Kgba46CDVg0vywpkFcDzgXi4hl8-vQ3aMIZRi5waBAJMGcRX-HnhGsqoLXNxsDiNcD7BGgpYNclHt6Bth4ovgEtRgWm4jnPzQUndL0DHTgPPCJHVPdgypkfiDCF2wruQjnGT8wFEAwM5pPbNNzR4eSuq-56sIdFUsLJaPq3p7A-dCgRBHnkFwY9TDFHgvGU7CvGgXM5VBOFslLsBzEScXwYzlHQQEEyfYx80PXQOg0PVHiowpNIxPnE_cgnM1TQCCYZYHBHyX8RBjMcBoyGx8lGChzDB04k1fA80KGyZTg87clYgbewQ938VGH0r9b-4lyaiy-XcLwShNGjUY5JTOCIsQAsNpxF6835VsfXRNFTpYcOZ6NTFf16rDxN4_kLOFJfFTWD91IoN6bGmPuIuKBNkKzGz8EzBc9hw3XjrmSalMPmCltsk_K1Nv_ss8hCm_QRhztwJ52y4tiXHs7aIDfknW7MmSFu2Q7cy69B8NfcG_f5NzB107-X1Er7U6iS7tkDbCHZgEmAacMBjamTm_5BMd9g50VwtBKHwWWFLyJHflPk41Gn9xR4VPDTx-R6UnDDfE-vy325NEVhe7RLmmZ2UXF8tM4r2jT1giexDV790ISelIi8lC2Nts2tCued1DYzVuqYsRMiLjPiUX6-lIv90jXPGKargdlvOOZ3O6PV68Wz--wnBk2PycrHi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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
2
+
3
+ ### Instruction:
4
+ Create a highly detailed and annotated mermaid diagram for the following process/workflow/information. Include details about inputs, outputs, data transformations, decisions points, and other significant components. Make sure it covers all steps and branches. Break down complex sequences into smaller parts if necessary. Include edge cases, error handling, and any special considerations. Create multiple diagrams for different aspects if needed. Annotate key functions, variables, control flows, and data structures with their respective names or values. Provide clear descriptions alongside each portion of the process to aid understanding.
5
+
6
+ To achieve this, follow these guidelines:
7
+
8
+ 1. Start by identifying the main starting point of your input (e.g., a user action, external source, or data stream).
9
+ 2. Trace the flow of execution through each stage in the process.
10
+ 3. Identify critical data structures such as tables, queues, and files.
11
+ 4. Highlight variable changes and manipulations.
12
+ 5. Mark decision points and branching paths.
13
+ 6. Note exception handling and corner case considerations.
14
+ 7. Label external tools, resources, and human interventions.
15
+ 8. Annotate each segment with its corresponding part of the overall process.
16
+ 9. Use color or shading to differentiate between different stages or subprocesses.
17
+ 10. Finally, review and refine the diagrams based on the provided information.
18
+
19
+ ### Input:
20
+ import argparse
21
+ import json
22
+ import os
23
+ import requests
24
+ import subprocess
25
+ import tempfile
26
+
27
+ class MermaidDiagramGenerator:
28
+ def __init__(self, theme='dark', background='transparent'):
29
+ self._theme = theme
30
+ self._background = background
31
+ self._entries_dir = os.path.join(os.getcwd(), 'Entries')
32
+ os.makedirs(self._entries_dir, exist_ok=True)
33
+
34
+ def convert_to_image(self, mermaid_code, entry_number, output_number):
35
+ clean_code = self._remove_mermaid_block_markers(mermaid_code)
36
+ output_filename = f"entry_{entry_number}_{output_number}.png"
37
+ output_path = os.path.join(self._entries_dir, output_filename)
38
+ self._generate_image_from_code(clean_code, output_path)
39
+ return output_path
40
+
41
+ def _remove_mermaid_block_markers(self, code):
42
+ code_lines = code.strip().splitlines()
43
+ if code_lines[0].startswith("```mermaid") and code_lines[-1] == "```":
44
+ return "\n".join(code_lines[1:-1]).strip()
45
+ return code
46
+
47
+ def _generate_image_from_code(self, mermaid_code, output_path):
48
+ with tempfile.NamedTemporaryFile(delete=False, mode='w', suffix='.mmd') as temp_file:
49
+ temp_file.write(mermaid_code)
50
+ input_path = temp_file.name
51
+ result = subprocess.run(["mmdc", "-i", input_path, "-o", output_path, "-t", self._theme, "-b", self._background], shell=True, check=False)
52
+ os.remove(input_path)
53
+ if result.returncode != 0:
54
+ raise ValueError("Mermaid diagram generation failed.")
55
+
56
+ def read_input(input_source):
57
+ if os.path.isfile(input_source):
58
+ filename, file_extension = os.path.splitext(input_source)
59
+ if file_extension == '.json':
60
+ with open(input_source, 'r') as file:
61
+ return json.load(file)
62
+ elif file_extension == '.txt':
63
+ with open(input_source, 'r') as file:
64
+ return [{"input": file.read()}]
65
+ else:
66
+ return [{"input": input_source}]
67
+
68
+ def generate_response(prompt, base_temperatures, stream, generator, entry_number, unique_outputs):
69
+ # prompt_template = f"{prompt}\n\n```mermaid\n"
70
+
71
+ prompt_template = """
72
+ Below is an instruction that describes a task, paired with an input that provides further context. Write a response that appropriately completes the request.
73
+
74
+ ### Instruction:
75
+ Create the mermaid diagram for the following input:
76
+
77
+ ### Input:
78
+ {input}
79
+
80
+ ### Response:
81
+ ```mermaid
82
+ """.format(input=prompt)
83
+
84
+ url = "http://127.0.0.1:5000/v1/completions"
85
+ headers = {"Content-Type": "application/json"}
86
+ dataset_entries = []
87
+
88
+ for output_number, temp in enumerate(base_temperatures, start=1):
89
+ while True:
90
+ data = {
91
+ "prompt": prompt_template,
92
+ "max_tokens": 4096,
93
+ "temperature": temp,
94
+ "top_p": 1.0,
95
+ "seed": -1,
96
+ "top_k": 4,
97
+ "repetition_penalty": 1.0,
98
+ "guidance_scale": 1.0,
99
+ "typical_p": 1.0,
100
+ "stream": stream,
101
+ }
102
+
103
+ response = requests.post(url, headers=headers, json=data, verify=False)
104
+ response_text = response.json()['choices'][0]['text'].strip()
105
+
106
+ if response_text.endswith("```"): # Check if response ends with ```
107
+ response_text = response_text[:-3].strip() # Remove ``` from the end
108
+
109
+ if response_text not in unique_outputs:
110
+ try:
111
+ image_path = generator.convert_to_image(response_text, entry_number, output_number)
112
+ print(f"Mermaid diagram generated at: {image_path}")
113
+ unique_outputs.add(response_text)
114
+ break
115
+ except ValueError as e:
116
+ print(f"Validation failed, retrying... Error: {e}")
117
+ else:
118
+ temp += 0.1 # Adjust temperature if output is not unique
119
+
120
+ dataset_entry = {
121
+ "input": prompt,
122
+ "output": f"```mermaid\n{response_text}\n```",
123
+ "temperature": temp
124
+ }
125
+ dataset_entries.append(dataset_entry)
126
+
127
+ return dataset_entries
128
+
129
+ def generate_unique_responses(input_data, base_temperatures, stream, generator):
130
+ all_entries = []
131
+ unique_outputs = set()
132
+
133
+ for entry_number, entry in enumerate(input_data, start=1):
134
+ prompt = entry.get("input", "")
135
+ if prompt:
136
+ entries = generate_response(prompt, base_temperatures, stream, generator, entry_number, unique_outputs)
137
+ all_entries.extend(entries) # Extend the list with new entries
138
+
139
+ return all_entries
140
+
141
+ def main(input_source, stream=False):
142
+ generator = MermaidDiagramGenerator()
143
+ input_data = read_input(input_source)
144
+ base_temperatures = [i / 10 for i in range(5, 11)] # Adjusted for batch of unique outputs per input
145
+ output_file = "output.json"
146
+
147
+ all_entries = generate_unique_responses(input_data, base_temperatures, stream, generator)
148
+
149
+ # Write all entries to the JSON file at once
150
+ with open(output_file, "w") as f:
151
+ json.dump(all_entries, f, indent=4) # Dump the entire list of entries into the file
152
+
153
+ if __name__ == "__main__":
154
+ parser = argparse.ArgumentParser(description="Generate unique responses and validate Mermaid diagrams.")
155
+ parser.add_argument('input_source', type=str, help='A multi-line string, path to a .txt file, or a .json file with prompts.')
156
+ parser.add_argument('--stream', action='store_true', help='Use streaming responses.')
157
+ args = parser.parse_args()
158
+
159
+ main(args.input_source, args.stream)
160
+
161
+ ### Response:
162
+ ```mermaid
163
+ graph TB;
164
+ A[Start] --> B[Read Input Source];
165
+ B --> C{Input Source Type};
166
+ C --> |File| D[Read File Content];
167
+ C --> |String| E[Split String Prompts];
168
+ D --> F[Convert to JSON];
169
+ E --> F;
170
+ F --> G[Get Input Prompts];
171
+
172
+ G --> H[Initialize Generator];
173
+ H --> I[Set Base Temperatures];
174
+ I --> J[Set Stream Flag];
175
+ J --> K[Set Output File];
176
+
177
+ K --> L[Generate Unique Responses];
178
+ L --> M[Write All Entries to JSON];
179
+ M --> N[End];
180
+
181
+ subgraph Generate Unique Responses
182
+ direction TB;
183
+ L --> O[Loop Through Input Prompts];
184
+ O --> P[Get Prompt];
185
+ P --> Q[Generate Response];
186
+ Q --> R[Validate Mermaid Diagram];
187
+ R --> S[Add to All Entries];
188
+ S --> T{Unique Output?};
189
+ T --> |Yes| U[Increment Temperature];
190
+ U --> O;
191
+ T --> |No| V[Retry];
192
+ V --> O;
193
+ end;
194
+
195
+ subgraph Generate Response
196
+ direction TB;
197
+ Q --> W[Call OpenAI API];
198
+ W --> X[Extract Response Text];
199
+ X --> Y[Generate Mermaid Diagram];
200
+ Y --> Z[Validate Mermaid Diagram];
201
+ Z --> A1[Add to All Entries];
202
+ end;
203
+
204
+ subgraph Validate Mermaid Diagram
205
+ direction TB;
206
+ R --> B1[Convert to Image];
207
+ B1 --> C1[Check Image Validity];
208
+ C1 --> D1{Valid?};
209
+ D1 --> |Yes| E1[Return True];
210
+ D1 --> |No| F1[Retry];
211
+ F1 --> R;
212
+ end;
213
+
214
+ subgraph Generate Mermaid Diagram
215
+ direction TB;
216
+ Y --> G1[Remove Block Markers];
217
+ G1 --> H1[Generate Image from Code];
218
+ H1 --> I1[Return Image Path];
219
+ end;
220
+
221
+ subgraph Convert to Image
222
+ direction TB;
223
+ B1 --> C2[Generate Command];
224
+ C2 --> D2[Run Command];
225
+ D2 --> E2[Check Return Code];
226
+ E2 --> |0| F2[Return Image Path];
227
+ E2 --> |!=0| G2[Raise Error];
228
+ end;
229
+
230
+ subgraph Remove Block Markers
231
+ direction TB;
232
+ G1 --> H2[Split Lines];
233
+ H2 --> I2[Check First Line];
234
+ I2 --> |Starts With| J2[Remove Line];
235
+ I2 --> |Doesn't Start| K2[Keep Line];
236
+ J2 --> L2[Join Remaining Lines];
237
+ K2 --> L2;
238
+ L2 --> M2[Return Clean Code];
239
+ end;
240
+
241
+ subgraph Generate Command
242
+ direction TB;
243
+ C2 --> D3[Build Command];
244
+ D3 --> E3[Return Command];
245
+ end;
246
+
247
+ subgraph Run Command
248
+ direction TB;
249
+ D2 --> F3[Run Command];
250
+ F3 --> G3[Check Return Code];
251
+ G3 --> |0| H3[Return Image Path];
252
+ G3 --> |!=0| I3[Raise Error];
253
+ end;
254
+ ```