File size: 4,906 Bytes
358424c
 
 
 
 
 
1bd9947
572cc27
358424c
d92c861
1b846eb
358424c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f077ece
 
 
 
358424c
 
 
 
 
 
 
f077ece
 
81dbe97
358424c
 
 
 
 
 
 
 
 
 
 
 
 
1556bea
358424c
 
 
 
 
 
 
 
 
 
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
import os 
import aiohttp
import asyncio
import requests
from fastapi import FastAPI, HTTPException
import openai


# Initialize FastAPI app
app = FastAPI()

# Set your OpenAI API key here
openai.api_key = os.environ["OPENAI_API_KEY"]

# Authorization headers
AUTH_HEADERS = {
    'X-Tenant': 'royalexpress',
    'Accept': 'application/json',
    'Authorization': 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiYjczMDAxYzMyMTE1ZGIyNTY4ODUzMTg2OWVjMzUwNTdjZmE3YTJmN2I3ZWZjMjQzNjdmZTA2ZTk4ZjY4ZjMwMTE0ZTIzOGUwY2I0ZmQ0YjIiLCJpYXQiOjE3MzA3ODIxNjEuMjkyNDM0LCJuYmYiOjE3MzA3ODIxNjEuMjkyNDM3LCJleHAiOjQ4ODY0NTU3NjEuMDc2ODExLCJzdWIiOiIxIiwic2NvcGVzIjpbXX0.I4wGFzoepmAC2RaADetE95BdbY4AYPUfUouFepVthZq_KewQLoYEiYMmxErgAOvYDL9IdhTg8pHm3KtCjtfF79Toigvzl-4RIYE9qwavVYabUaIMtxdkvLmzC2uSSxNkQ-Jx4ZsEVt34NpMMZ6ZsMsgszkreed_s7i5I6ek6T2-p9cZYPpFfGhlRIrgAhOL1yZe0t5HQMM7P1cULB7IMb3s0fvwLNBimPC4Iznick5o2lWO6KcubsKSAMyPwBaCQhjGTKd0eJCde1IvL8mEaMvhu8v853AIDSiBsC83hjK41hPAaiBHeev1JjdDhEd6_qO9dpucKaGCqYiVfBFH_pgnynErmhKlPEIz7sZlBWz8zxISDW5PRo9d-jXRP-A31W76Q3H-ZKfnam0D8yYFY0EIZHhvgvZUl3r0dR4PRh7PYlNZgnyfAcAYmK9Bektjbbx5RuzH6gtT9hLQrxYiQNg0irCNwgTYnuQ4AjPA3BpZuOfWtygeDZKgv1gnveTzMJG7T6s95k8yNSNT1_OfRQONPX8LBasRwZWCGkWj7fopO6K8gcrEU5FIpql0UviwGJOTZeFmqwWJ1AIcOM0MHWNp--Y8evHrvuNGk3SDcjBcvhF58I2Hd5F4MefN_ZB9N7oxUUDBYbxnTH6SN7Wx-VsluEOlf9ShfBNvHZaUi61E'
}

# Helper function to get the order ID from the waybill number
def get_order_id(waybill_no):
    url = f"https://dev3.api.curfox.parallaxtec.com/api/ml/order/{waybill_no}"
    response = requests.get(url, headers=AUTH_HEADERS)
    if response.status_code == 200:
        return response.json().get("data", {}).get("id")
    else:
        raise HTTPException(status_code=404, detail="Order ID not found")

# Asynchronous function to fetch data concurrently
async def fetch_data(session, url):
    async with session.get(url, headers=AUTH_HEADERS) as response:
        return await response.text()

# Asynchronous function to get all order data
async def get_all_order_data(order_id):
    urls = [
        f"https://dev3.api.curfox.parallaxtec.com/api/ml/order/{order_id}/time-line",
        f"https://dev3.api.curfox.parallaxtec.com/api/ml/order/{order_id}/finance-time-line",
        f"https://dev3.api.curfox.parallaxtec.com/api/ml/order/{order_id}/invoice-time-line"
    ]

    async with aiohttp.ClientSession() as session:
        tasks = [fetch_data(session, url) for url in urls]
        responses = await asyncio.gather(*tasks)

    full_data = {
        "Timeline Details": responses[0],
        "Finance Time Line": responses[1],
        "Invoice Time Line": responses[2]
    }
    return full_data

# Function to interact with OpenAI API
def ask_openai(messages):
    response = openai.ChatCompletion.create(model="gpt-4o-mini", messages=messages)
    return response.choices[0].message['content']

# Main endpoint to handle user queries
@app.post("/process_query/")
async def process_query(query: str):
    # Initial message to check for waybill number in the query
    messages = [
        {"role": "system", "content": "You are a helpful assistant for Curfox delivery system."},
        {"role": "user", "content": f"""always check user query mentioned the order number/id (example : CA000001)
                                   if order id provided then output is only : "done"
                                   if user not given the order number then ask the number from user (include or response to greetings)
                                   user query : {query}""" }
    ]
    result = ask_openai(messages)

    if result == "done":
        # Extract the waybill number
        extract_message = [
            {"role": "system", "content": "You are a helpful assistant for Curfox delivery system."},
            {"role": "user", "content": f"""extract the number from the user query example output is only : CA000001
                                    user query : {query}""" }
        ]
        waybill_number = ask_openai(extract_message)

        # Fetch order ID and order details
        try:
            order_id = get_order_id(waybill_number)
            full_data = await get_all_order_data(order_id)
        except HTTPException as e:
            return {"error": str(e.detail)}

        # Generate final response based on collected data
        response_message = [
            {"role": "system", "content": "You are a helpful assistant for Curfox delivery system."},
            {"role": "user", "content": f"Answer based on the provided data only. Data: {full_data}. User query: {query}"}
        ]
        final_answer = ask_openai(response_message)
        return {"answer": final_answer}
    else:
        # If no order number is found, prompt the user
        return {"message": result}

# Start the FastAPI app
# Run the app on Colab using Uvicorn
# import uvicorn
# uvicorn.run(app, host="0.0.0.0", port=8000)