File size: 6,216 Bytes
360b354
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
import json
from fastapi import Query
import logging
from llama_index.core.agent import ReActAgent
from llama_index.core.indices.struct_store import JSONQueryEngine
from llama_index.core.llms import ChatMessage
from llama_index.core import PromptTemplate
from datetime import datetime
from .app import final_counts  # noqa
from .archive_orders import fetch_response
from typing import Optional
from datetime import datetime, timedelta
from ..utils import (
    llm,
)  # (this is to take llm from utils and llm in utils is called from config)
from .json_schema import json_schema
import ollama
from config import settings
import sys
import math

sys.path.append("..")


client = ollama.Client(host=settings.HOST_URI)


def fetch_data(
    store_id: str,
    brand_id: str,
    # period: Optional[str] = Query(None, enum=["week", "month", "six months", "whole", "yesterday", "today"]),
    start_date: Optional[str] = None,
    end_date: Optional[str] = None,
    # hours: Optional[int] = None,
    # minutes: Optional[int] = None,
    # seconds: Optional[int] = None,
    # number_of_days: Optional[int] = None
):
    if start_date and end_date:
        try:
            start_date_obj = datetime.strptime(start_date, "%Y-%m-%d")
            end_date_obj = datetime.strptime(end_date, "%Y-%m-%d")
        except ValueError:
            return {"error": "Dates must be in YYYY-MM-DD format."}

    data = fetch_response(store_id, brand_id, None, start_date_obj, end_date_obj)

    if data:
        return final_counts(data)
    else:
        return {"error": "Failed to fetch data"}


def greetings_function(query):
    query = query.lower()
    analysis_prompt = f"""
        You are a restaurant menu bot. Your task is to greet the user with one-liner.
        Keep your response short, playful, and engaging.
    """

    messages = [
        {"role": "system", "content": analysis_prompt},
        {"role": "user", "content": query},
    ]

    analysis_response = client.chat(model="llama3.1", messages=messages)

    print("----" * 20)
    print(analysis_response["message"])
    print("----" * 20)
    return analysis_response["message"]["content"].strip()


def get_data(
    query: str,
    start_date: str,
    end_date: str,
    store_id="634fdb58ad4c218c52bfaf4f",
    brand_id="6347b5f0851f703b75b39ad0",
) -> str:

    print(f"QUERY :: {query}")
    print(f"START DATE :: {start_date}")
    print(f"END DATE :: {end_date}")

    data = fetch_data(
        store_id=store_id,
        brand_id=brand_id,
        start_date=start_date,
        end_date=end_date,
    )

    if "error" in data:
        return data["error"]

    a = data
    

    def create_dynamic_prompt(query):
        """Create a dynamic prompt."""
        prompt = f"""

      now if dates are 00:00:0000 that means there will no nothing to get data , just pass the queary as it in simplified way dont try to fetch the data
      The following is a task for an intelligent assistant:

      Here is the JSON with order details of a restaurant named "Wrap and Dip Cafe":
      {json.dumps(a, indent=2)}
    {print("awdnjznnfjldznjnz : ",a)}

      Given the JSON schema for reference:
      {json.dumps(json_schema, indent=2)}

      You are a JSON analysis engine designed to answer questions based on the given restaurant order data. The data includes various aspects such as the number of times each item has been ordered, the number of orders per day, cancellations, completions, orders by aggregator, total revenue, total orders, and daily revenue.

      When asked a question, follow these steps:

      1. Understand the question and identify the relevant parts of the JSON data.
      2. Extract the necessary information from the JSON data.
      3. Perform any required calculations or comparisons.
      4. Provide a concise and accurate answer without including unnecessary details.
      5. If you encounter more than one answer, provide them in a list.
      6. Provide accurate, concise, and clear answers based on the JSON data provided.
      7. I only want the response to be printed after 'So,the answer is' or 'Therefore,the answer is' and not the based on json data line.

      Special attention should be given to queries about items ordered the most. These queries require looking into "number_of_times_item_ordered" and identifying the item(s) with the highest count.

      Here are a few examples of questions you should be able to answer:

      - "Which item is ordered the most?"
        - Look into "number_of_times_item_ordered" and find the item with the highest count.

      - "On which date was the highest revenue collected?"
        - Look into "revenue_daywise" and find the date with the highest revenue.

      - "How many orders were completed on 2024-04-22?"
        - Look into "number_of_order_completed" for the value corresponding to "2024-04-22".

      - "What is the total revenue generated?"
        - Return the value from the sum of "total_revenue".

      - "How many orders were canceled on 2024-03-13?"
        - Look into "number_of_order_canceled" for the value corresponding to "2024-03-13".

      - "Find the item with exactly 3 orders."
        - Look into "number_of_times_item_ordered" and find the item(s) with a count of 3.

      - "What is the revenue for last 16 days?"
        - Look into "revenue_day_wise" and take the revenues two at a time and do the sum and then third and so on."

      Use these examples to guide your responses to similar questions. If you encounter a new type of question, use the structure and examples to determine how to extract and compute the answer.

      Remember, your goal is to provide accurate, concise, and clear answers based on the JSON data provided. Do not generate lengthy responses or include detailed breakdowns unless explicitly asked. Return only the direct answer to the question.

      The user's query is as follows: "{query}"
      """
        messages = [
            ChatMessage(role="system", content=prompt),
            ChatMessage(role="user", content=query),
        ]
        resp = llm.chat(messages)
        return resp.message.content

    response = create_dynamic_prompt(query)
    return response