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typing import List, Optional
|
5 |
+
from pydantic import BaseModel, Field
|
6 |
+
from together import Together
|
7 |
+
|
8 |
+
# Initialize Together API
|
9 |
+
together = Together(api_key=os.getenv("togetherai"))
|
10 |
+
|
11 |
+
# Define the schemas for different API operations
|
12 |
+
class OrderItem(BaseModel):
|
13 |
+
item_id: str
|
14 |
+
quantity: int
|
15 |
+
|
16 |
+
class CreateOrderExtract(BaseModel):
|
17 |
+
user_id: Optional[str] = Field(None, description="The user's ID if provided it can be a name as well")
|
18 |
+
items: List[OrderItem] = Field(..., description="List of items ordered")
|
19 |
+
|
20 |
+
class CancelOrderExtract(BaseModel):
|
21 |
+
order_id: str = Field(..., description="The ID of the order to cancel can be referenced as order id or order or id or order number")
|
22 |
+
|
23 |
+
class CheckOrderStatusExtract(BaseModel):
|
24 |
+
order_id: str = Field(..., description="The ID of the order to check can be referenced as order id or order or id or order number")
|
25 |
+
|
26 |
+
class CreateInvoiceExtract(BaseModel):
|
27 |
+
order_id: str = Field(..., description="The ID of the order for which to create an invoice")
|
28 |
+
amount: float = Field(..., description="The amount of the invoice")
|
29 |
+
|
30 |
+
class GetInvoiceDetailsExtract(BaseModel):
|
31 |
+
invoice_id: str = Field(..., description="The ID of the invoice to get details for")
|
32 |
+
|
33 |
+
class CreatePaymentExtract(BaseModel):
|
34 |
+
invoice_id: str = Field(..., description="The ID of the invoice to pay")
|
35 |
+
order_id: str = Field(..., description="The ID of the order associated with the payment")
|
36 |
+
amount: float = Field(..., description="The amount of the payment")
|
37 |
+
|
38 |
+
# Function to classify user message
|
39 |
+
def classify_message(message: str) -> str:
|
40 |
+
classify = together.chat.completions.create(
|
41 |
+
messages=[
|
42 |
+
{
|
43 |
+
"role": "system",
|
44 |
+
"content": "Classify the following message into one of these categories: create_order, cancel_order, check_order_status, create_invoice, get_invoice_details, create_payment. Respond only with the category name.",
|
45 |
+
},
|
46 |
+
{
|
47 |
+
"role": "user",
|
48 |
+
"content": message,
|
49 |
+
},
|
50 |
+
],
|
51 |
+
model="meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
|
52 |
+
)
|
53 |
+
return classify.choices[0].message.content.strip()
|
54 |
+
|
55 |
+
# Function to extract information based on classification
|
56 |
+
def extract_info(message: str, classification: str) -> dict:
|
57 |
+
schema_map = {
|
58 |
+
"create_order": CreateOrderExtract,
|
59 |
+
"cancel_order": CancelOrderExtract,
|
60 |
+
"check_order_status": CheckOrderStatusExtract,
|
61 |
+
"create_invoice": CreateInvoiceExtract,
|
62 |
+
"get_invoice_details": GetInvoiceDetailsExtract,
|
63 |
+
"create_payment": CreatePaymentExtract,
|
64 |
+
}
|
65 |
+
|
66 |
+
schema = schema_map[classification]
|
67 |
+
|
68 |
+
extract = together.chat.completions.create(
|
69 |
+
messages=[
|
70 |
+
{
|
71 |
+
"role": "system",
|
72 |
+
"content": f"Extract {classification} information from the following message. Respond only in JSON.",
|
73 |
+
},
|
74 |
+
{
|
75 |
+
"role": "user",
|
76 |
+
"content": message,
|
77 |
+
},
|
78 |
+
],
|
79 |
+
model="mistralai/Mixtral-8x7B-Instruct-v0.1",
|
80 |
+
response_format={
|
81 |
+
"type": "json_object",
|
82 |
+
"schema": schema.model_json_schema(),
|
83 |
+
},
|
84 |
+
)
|
85 |
+
return json.loads(extract.choices[0].message.content)
|
86 |
+
|
87 |
+
# Function to make API call
|
88 |
+
def make_api_call(classification: str, info: dict) -> dict:
|
89 |
+
base_url = os.getenv("baseurl")
|
90 |
+
|
91 |
+
api_map = {
|
92 |
+
"create_order": ("POST", f"{base_url}/orders"),
|
93 |
+
"cancel_order": ("POST", f"{base_url}/orders/{{order_id}}/cancel"),
|
94 |
+
"check_order_status": ("GET", f"{base_url}/orders/{{order_id}}/status"),
|
95 |
+
"create_invoice": ("POST", f"{base_url}/invoices"),
|
96 |
+
"get_invoice_details": ("GET", f"{base_url}/invoices/{{invoice_id}}"),
|
97 |
+
"create_payment": ("POST", f"{base_url}/payments"),
|
98 |
+
}
|
99 |
+
|
100 |
+
method, url_template = api_map[classification]
|
101 |
+
|
102 |
+
# Replace placeholders in the URL if necessary
|
103 |
+
try:
|
104 |
+
url = url_template.format(**info)
|
105 |
+
except KeyError as e:
|
106 |
+
return {"error": f"Missing required information: {str(e)}"}
|
107 |
+
|
108 |
+
try:
|
109 |
+
if method == "GET":
|
110 |
+
response = requests.get(url)
|
111 |
+
elif method == "POST":
|
112 |
+
response = requests.post(url, json=info)
|
113 |
+
response.raise_for_status()
|
114 |
+
return response.json()
|
115 |
+
except requests.RequestException as e:
|
116 |
+
return {"error": f"API request failed: {str(e)}"}
|
117 |
+
|
118 |
+
# Function to interpret API response
|
119 |
+
def interpret_response(user_message: str, classification: str, api_response: dict) -> str:
|
120 |
+
interpret = together.chat.completions.create(
|
121 |
+
messages=[
|
122 |
+
{
|
123 |
+
"role": "system",
|
124 |
+
"content": "Process user query and automated system API response to form a coherent natural reply that will help the user affirm the situation of their request. Your response will be streamed directly to the user. Do not include the fact that you are reading the API response. It should be natural and helpful. Make sure to give the user the relevant IDs and information, and do not talk more than that. Just give information and that's it.",
|
125 |
+
},
|
126 |
+
{
|
127 |
+
"role": "user",
|
128 |
+
"content": f"User message: {user_message}\nRequest type: {classification}\nAPI response: {json.dumps(api_response)}",
|
129 |
+
},
|
130 |
+
],
|
131 |
+
model="meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
|
132 |
+
)
|
133 |
+
return interpret.choices[0].message.content
|
134 |
+
|
135 |
+
# Main function to process the user request
|
136 |
+
def process_request(user_message: str) -> str:
|
137 |
+
# Classify the message
|
138 |
+
classification = classify_message(user_message)
|
139 |
+
|
140 |
+
# Extract information based on classification
|
141 |
+
info = extract_info(user_message, classification)
|
142 |
+
|
143 |
+
# Make API call
|
144 |
+
api_response = make_api_call(classification, info)
|
145 |
+
|
146 |
+
# Interpret the response
|
147 |
+
interpretation = interpret_response(user_message, classification, api_response)
|
148 |
+
|
149 |
+
return interpretation
|
150 |
+
|
151 |
+
# Define the API documentation with the repository link
|
152 |
+
api_documentation = """
|
153 |
+
## Available API Methods
|
154 |
+
|
155 |
+
### 1. Create Order
|
156 |
+
- **Endpoint:** POST /orders
|
157 |
+
- **Inputs:**
|
158 |
+
- user_id: (Optional) The user's ID or name.
|
159 |
+
- items: List of ordered items with `item_id` and `quantity`.
|
160 |
+
|
161 |
+
### 2. Cancel Order
|
162 |
+
- **Endpoint:** POST /orders/{order_id}/cancel
|
163 |
+
- **Inputs:**
|
164 |
+
- order_id: The ID of the order to be canceled.
|
165 |
+
|
166 |
+
### 3. Check Order Status
|
167 |
+
- **Endpoint:** GET /orders/{order_id}/status
|
168 |
+
- **Inputs:**
|
169 |
+
- order_id: The ID of the order to check status.
|
170 |
+
|
171 |
+
### 4. Create Invoice
|
172 |
+
- **Endpoint:** POST /invoices
|
173 |
+
- **Inputs:**
|
174 |
+
- order_id: The ID of the order.
|
175 |
+
- amount: The invoice amount.
|
176 |
+
|
177 |
+
### 5. Get Invoice Details
|
178 |
+
- **Endpoint:** GET /invoices/{invoice_id}
|
179 |
+
- **Inputs:**
|
180 |
+
- invoice_id: The ID of the invoice to retrieve.
|
181 |
+
|
182 |
+
### 6. Create Payment
|
183 |
+
- **Endpoint:** POST /payments
|
184 |
+
- **Inputs:**
|
185 |
+
- invoice_id: The ID of the invoice to pay.
|
186 |
+
- order_id: The ID of the associated order.
|
187 |
+
- amount: The payment amount.
|
188 |
+
|
189 |
+
You can use these examples when interacting with the system.
|
190 |
+
|
191 |
+
For more details on the API, including the routes and implementation, visit the GitHub repository:
|
192 |
+
[Order Management API Repository](https://github.com/akash-mondal/order-management-api)
|
193 |
+
"""
|
194 |
+
|
195 |
+
# Build the Gradio interface
|
196 |
+
with gr.Blocks() as demo:
|
197 |
+
gr.Markdown("# Function Calling Demo")
|
198 |
+
gr.Markdown("""
|
199 |
+
This is a demo for performing function calls using custom API endpoints. The demo uses Together AI for language models (LLMs), where:
|
200 |
+
|
201 |
+
- **Mixtral 8x7B** is used to extract API information from natural language.
|
202 |
+
- **Llama 3.1 70B** is used to classify which API to route to.
|
203 |
+
- **Llama 3.1 8B** is used to interpret API responses into natural language for the end user.
|
204 |
+
""")
|
205 |
+
|
206 |
+
with gr.Tab("User Input"):
|
207 |
+
user_input = gr.Textbox(label="Enter your message")
|
208 |
+
output = gr.Textbox(label="Response")
|
209 |
+
submit_button = gr.Button("Submit")
|
210 |
+
|
211 |
+
def handle_submit(user_message):
|
212 |
+
return process_request(user_message)
|
213 |
+
|
214 |
+
submit_button.click(handle_submit, inputs=user_input, outputs=output)
|
215 |
+
|
216 |
+
with gr.Tab("API Documentation"):
|
217 |
+
gr.Markdown(api_documentation)
|
218 |
+
|
219 |
+
# Run the demo
|
220 |
+
demo.launch()
|