nagarmayank commited on
Commit
e04da09
·
1 Parent(s): e01d6d5

Initial Commit

Browse files
Files changed (2) hide show
  1. app.py +116 -2
  2. requirements.txt +1 -0
app.py CHANGED
@@ -1,7 +1,121 @@
1
  from fastapi import FastAPI
 
2
 
3
  app = FastAPI()
4
 
5
- @app.get("/")
6
  def greet_json():
7
- return {"Hello": "World!"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  from fastapi import FastAPI
2
+ import os
3
 
4
  app = FastAPI()
5
 
6
+ @app.post("/")
7
  def greet_json():
8
+ return {"Hello": "World!"}
9
+
10
+ GOOGLESHEETS_CREDENTIALS = os.getenv("GOOGLESHEETS_CREDENTIALS")
11
+
12
+ # from langchain_core.prompts import ChatPromptTemplate
13
+ # from langchain_groq import ChatGroq
14
+ # from pydantic import BaseModel, Field
15
+ # import pygsheets
16
+ # import json
17
+ # from langgraph.graph import StateGraph, END
18
+ # from typing import TypedDict, Annotated
19
+ # import operator
20
+ # from langchain_core.messages import SystemMessage, HumanMessage, AnyMessage
21
+ # from langchain_ollama import ChatOllama
22
+ # import groq
23
+ # from tqdm import tqdm
24
+ # from opik.integrations.langchain import OpikTracer
25
+ # from langgraph.pregel import RetryPolicy
26
+
27
+ # MODEL = "llama3-70b-8192" # "meta-llama/llama-4-scout-17b-16e-instruct" #
28
+
29
+ # class TransactionParser(BaseModel):
30
+ # """This Pydantic class is used to parse the transaction message."""
31
+
32
+ # amount: str = Field(description="The amount of the transaction in decimal format. If the transaction is a credit or a reversal, then include negative sign. DO not insert currency.", example="123.45")
33
+ # dr_or_cr: str = Field(description="Identify if the transaction was debit (spent) or credit (received). Strictly choose one of the values - Debit or Credit")
34
+ # receiver: str = Field(description="The recipient of the transaction. Identify the Merchant Name from the value.")
35
+ # category: str = Field(description="The category of the transaction. The category of the transaction is linked to the Merchant Name. Strictly choose from one the of values - Shopping,EMI,Education,Miscellaneous,Grocery,Utility,House Help,Travel,Transport")
36
+ # transaction_date: str = Field(description="The date of the transaction in yyyy-mm-dd format. If the year is not provided then use current year.")
37
+ # transaction_origin: str = Field(description="The origin of the transaction. Provide the card or account number as well.")
38
+
39
+ # class AgentState(TypedDict):
40
+ # messages: Annotated[list[AnyMessage], operator.add]
41
+
42
+ # class Agent:
43
+ # def __init__(self, model, system=""):
44
+ # self.system = system
45
+ # graph = StateGraph(AgentState)
46
+ # graph.add_node("classify_txn_type", self.classify_txn_type, retry=RetryPolicy(retry_on=[groq.BadRequestError], max_attempts=2))
47
+ # graph.add_node("parse_message", self.parse_message, retry=RetryPolicy(retry_on=[groq.BadRequestError], max_attempts=2))
48
+ # graph.add_node("write_message", self.write_message)
49
+ # graph.add_conditional_edges(
50
+ # "classify_txn_type",
51
+ # self.check_txn_and_decide,
52
+ # {True: "parse_message", False: END}
53
+ # )
54
+ # graph.add_edge("parse_message", "write_message")
55
+ # graph.add_edge("write_message", END)
56
+ # graph.set_entry_point("classify_txn_type")
57
+ # self.graph = graph.compile()
58
+ # self.model = model
59
+
60
+ # def classify_txn_type(self, state: AgentState) -> AgentState:
61
+ # messages = state["messages"]
62
+ # if self.system:
63
+ # messages = [SystemMessage(content=self.system)] + messages
64
+
65
+ # message = self.model.invoke(messages)
66
+ # return {"messages": [message]}
67
+
68
+ # def parse_message(self, state: AgentState) -> AgentState:
69
+ # message = state["messages"][0].content
70
+ # system = """
71
+ # You are a helpful assistant skilled at parsing transaction messages and providing structured responses.
72
+ # """
73
+ # human = "Categorize the transaction message and provide the output in a structed format: {topic}"
74
+
75
+ # prompt = ChatPromptTemplate.from_messages([("system", system), ("human", human)])
76
+ # chain = prompt | model.with_structured_output(TransactionParser)
77
+ # result = chain.invoke({"topic": message})
78
+
79
+ # return {"messages": [result]}
80
+
81
+ # def write_message(self, state: AgentState) -> AgentState:
82
+ # result = state["messages"][-1]
83
+ # client = pygsheets.authorize(service_account_file="serviceaccount.json")
84
+ # worksheet = client.open_by_url("https://docs.google.com/spreadsheets/d/1t4bOM4fULdaVsjDDnqEG1g8Zey6M00UuFhTZC03_4xo")
85
+ # wk = worksheet[0]
86
+ # # Get number of rows in the worksheet
87
+ # df = wk.get_as_df(start='A1', end='G999')
88
+ # nrows = df.shape[0]
89
+ # wk.update_value(f'A{nrows+2}', result.amount)
90
+ # wk.update_value(f'B{nrows+2}', result.dr_or_cr)
91
+ # wk.update_value(f'C{nrows+2}', result.receiver)
92
+ # wk.update_value(f'D{nrows+2}', result.category)
93
+ # wk.update_value(f'E{nrows+2}', result.transaction_date)
94
+ # wk.update_value(f'F{nrows+2}', result.transaction_origin)
95
+ # wk.update_value(f'G{nrows+2}', state["messages"][0].content)
96
+ # return {"messages": ["Transaction Completed"]}
97
+
98
+ # def check_txn_and_decide(self, state: AgentState):
99
+ # try:
100
+ # result = json.loads(state['messages'][-1].content)['classification']
101
+ # except json.JSONDecodeError:
102
+ # result = state['messages'][-1].content.strip()
103
+
104
+ # return result == "Transaction"
105
+
106
+ # prompt = """You are a smart assistant adept at classifying different messages. \
107
+ # You will be penalized heavily for incorrect classification. \
108
+ # Your task is to classify the message into one of the following categories: \
109
+ # Transaction, OTP, Promotional, Scheduled. \
110
+ # Output the classification in a structured format like below. \
111
+ # {"classification": "OTP"} \
112
+ # """
113
+
114
+ # model = ChatGroq(temperature=1, groq_api_key=GROQ_API_KEY, model_name=MODEL)
115
+ # # model = ChatOllama(model="gemma3:4b", temperature=1, callback=OpikTracer())
116
+
117
+ # transaction_bot = Agent(model, system=prompt)
118
+
119
+ # for message in tqdm(messages):
120
+ # message = [HumanMessage(content=message)]
121
+ # result = transaction_bot.graph.invoke({"messages": message}, config={"callbacks" : [OpikTracer(graph=transaction_bot.graph.get_graph(xray=True))]})
requirements.txt CHANGED
@@ -1,2 +1,3 @@
 
1
  fastapi
2
  uvicorn[standard]
 
1
+ os
2
  fastapi
3
  uvicorn[standard]