|
| 1 | +"""rabbithole.planner module""" |
| 2 | + |
| 3 | +import json |
| 4 | + |
| 5 | +import openai |
| 6 | + |
| 7 | + |
| 8 | +def generate_plan(summaries: dict[str, str], keywords: dict[str, list[str]]) -> dict: |
| 9 | + """ |
| 10 | + Generate a plan from a list of summaries and keywords. |
| 11 | + :param summaries: Summaries for each document. |
| 12 | + :param keywords: List of keywords for each document. |
| 13 | + :return: Generated plan. |
| 14 | + """ |
| 15 | + |
| 16 | + def format_document(name: str, summary: str, keywords: list[str]) -> str: |
| 17 | + """Format a document for the plan.""" |
| 18 | + |
| 19 | + # Create a string of comma-separated keywords |
| 20 | + keywords_str = ', '.join(keywords) |
| 21 | + |
| 22 | + # Construct the formatted document |
| 23 | + document = f"{name}\n{'=' * len(name)}\n{summary}\nKeywords: {keywords_str}\n\n" |
| 24 | + |
| 25 | + return document |
| 26 | + |
| 27 | + prompt = f""" |
| 28 | + I have the following documents with summaries and keywords: |
| 29 | + {''.join([format_document(name, summary, keywords) for name, summary, keywords in zip(summaries.keys(), summaries.values(), keywords.values())])} |
| 30 | + \n\n |
| 31 | + The plan should be formatted as follows: |
| 32 | + |
| 33 | + {{ |
| 34 | + "plan": [ |
| 35 | + {{ |
| 36 | + "Document 1": {{ |
| 37 | + "Background Concepts": ["Concept 1", "Concept 2", ...], |
| 38 | + "Key concepts": ["Concept 1", "Concept 2", ...], |
| 39 | + "Further reading": ["Concept 1", "Concept 2", ...] |
| 40 | + }} |
| 41 | + }} |
| 42 | + ... |
| 43 | + ] |
| 44 | + }} |
| 45 | + |
| 46 | + Only provide the JSON response and do not provide any other information other than it. |
| 47 | + Make sure the JSON is formatted correctly and without any errors. |
| 48 | + """ |
| 49 | + |
| 50 | + print("Making a request to OpenAI's API to generate a plan...") |
| 51 | + try: |
| 52 | + response = openai.ChatCompletion.create( |
| 53 | + model="gpt-4", |
| 54 | + messages=[ |
| 55 | + {"role": "system", |
| 56 | + "content": "You are an experienced professor helping a student plan their studies. You know everything about all subjects and need to answer factually and logically."}, |
| 57 | + {"role": "user", "content": prompt} |
| 58 | + ], |
| 59 | + ) |
| 60 | + print(response) |
| 61 | + except Exception as e: |
| 62 | + print(e) |
| 63 | + return { |
| 64 | + "plan": "Error generating a plan.\nPlease try again." |
| 65 | + } |
| 66 | + |
| 67 | + # Get the JSON response |
| 68 | + response = response.choices[0].message.content |
| 69 | + first_bracket = response.find('{') |
| 70 | + last_bracket = response.rfind('}') |
| 71 | + |
| 72 | + # Convert the JSON response to a dictionary |
| 73 | + return json.loads(response[first_bracket:last_bracket + 1]) |
0 commit comments