BlockBerg commited on
Commit
efb0194
Β·
verified Β·
1 Parent(s): c718140

Added source code.

Browse files
Files changed (1) hide show
  1. app.py +89 -59
app.py CHANGED
@@ -1,64 +1,94 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
3
-
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
-
9
-
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
-
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
25
-
26
- messages.append({"role": "user", "content": message})
27
-
28
- response = ""
29
-
30
- for message in client.chat_completion(
31
- messages,
32
- max_tokens=max_tokens,
33
- stream=True,
34
- temperature=temperature,
35
- top_p=top_p,
36
- ):
37
- token = message.choices[0].delta.content
38
-
39
- response += token
40
- yield response
41
-
42
-
43
- """
44
- For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
45
- """
46
- demo = gr.ChatInterface(
47
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
59
  ],
 
60
  )
61
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
- if __name__ == "__main__":
64
- demo.launch()
 
1
  import gradio as gr
2
+ from agno.agent import Agent
3
+ from agno.models.openai import OpenAIChat
4
+ from agno.tools.decorator import tool
5
+ from datetime import datetime, timedelta
6
+ from dotenv import load_dotenv
7
+ load_dotenv()
8
+
9
+ # βœ… Tool definition
10
+ @tool(name="treasury_data", description="Returns detailed account balances, FX exposure, and liabilities")
11
+ def get_treasury_data(input: str) -> str:
12
+ today = datetime.now().strftime("%Y-%m-%d")
13
+ due_date = (datetime.now() + timedelta(days=5)).strftime("%Y-%m-%d")
14
+ return f"""
15
+ As of {today}, here is the treasury snapshot:
16
+
17
+ βœ… Cash Balances:
18
+ - USD Operating Account: $2,800,000
19
+ - EUR Revenue Account: €1,500,000
20
+ - GBP Payroll Account: Β£600,000
21
+
22
+ πŸ“‰ FX Market Rates:
23
+ - EUR/USD: 1.08
24
+ - GBP/USD: 1.27
25
+
26
+ 🧾 Upcoming Liabilities:
27
+ - USD Vendor Payments: $2,200,000 due on {due_date}
28
+ - EUR Convertible Bond Maturity: €900,000 due on {due_date}
29
+ - GBP Payroll Run: Β£500,000 due on {due_date}
30
+
31
+ πŸ“Š Policy Thresholds:
32
+ - Minimum USD liquidity buffer: $500,000
33
+ - FX hedge threshold for EUR: 70% exposure
34
+ """
35
+
36
+ # βœ… Agent definition
37
+ agent = Agent(
38
+ model=OpenAIChat(id="gpt-4o"),
39
+ tools=[get_treasury_data],
40
+ instructions=[
41
+ "You are a Treasury Analyst AI.",
42
+ "Analyze liquidity and FX exposure.",
43
+ "Recommend actions such as FX hedging, internal fund transfers, or delay of liabilities.",
44
+ "Always ensure minimum liquidity buffers are met.",
45
+ "Convert foreign currency exposures to USD for a consolidated view.",
46
+ "Provide your analysis in bullet points with numbers.",
 
 
 
 
 
 
 
 
 
 
 
 
47
  ],
48
+ markdown=True,
49
  )
50
 
51
+ # βœ… Chat function
52
+ def ask_agent(messages, history):
53
+ print("====== DEBUG: ask_agent START ======")
54
+ print("πŸ“₯ Incoming messages:", messages)
55
+ print("πŸ“š Chat history:", history)
56
+
57
+ if isinstance(messages, str):
58
+ print("πŸ§ͺ Detected string instead of message list. Wrapping as message.")
59
+ messages = [{"role": "user", "content": messages}]
60
+
61
+ if not isinstance(messages, list) or not messages:
62
+ print("⚠️ Invalid or empty messages list.")
63
+ return {"role": "assistant", "content": "Hi! How can I help you with treasury insights today?"}
64
+
65
+ try:
66
+ latest_user_message = messages[-1]["content"]
67
+ print(f"πŸ’¬ Latest user message: {latest_user_message}")
68
+ except Exception as e:
69
+ print(f"❌ Error extracting latest message: {e}")
70
+ return {"role": "assistant", "content": "Sorry, I couldn't read your message."}
71
+
72
+ try:
73
+ response = agent.run(latest_user_message)
74
+ print(f"βœ… Agent response:\n{response}")
75
+ return {"role": "assistant", "content": response.content} # βœ… FIXED HERE
76
+ except Exception as e:
77
+ print(f"❌ Agent failed: {e}")
78
+ return {"role": "assistant", "content": "Something went wrong on my end. Try again?"}
79
+
80
+ print("====== DEBUG: ask_agent END ======")
81
+
82
+
83
+ def yes(message, history):
84
+ return "yes"
85
+
86
+ # βœ… Launch Gradio UI
87
+ gr.ChatInterface(
88
+ fn=ask_agent,
89
+ title="AI Treasury Assistant",
90
+ description="Ask about cash positions, FX risk, or liquidity outlook.",
91
+ chatbot=gr.Chatbot(show_copy_button=True),
92
+ type="messages" # βœ… Fixes the warning
93
+ ).launch()
94