Skip to content

Commit a1b353e

Browse files
jrriehlArchento
andauthored
feat: update uagents version and chat protocol (#68)
* feat: update uagents version and chat protocol * Update 6-deployed-agents/finance/company-overview-agent/functions.py Co-authored-by: Archento <[email protected]> * Update 6-deployed-agents/knowledge-base/claude.ai-agent/chat_proto.py Co-authored-by: Archento <[email protected]> * Update 6-deployed-agents/knowledge-base/openai-agent/chat_proto.py Co-authored-by: Archento <[email protected]> --------- Co-authored-by: Archento <[email protected]>
1 parent b8ba35d commit a1b353e

File tree

44 files changed

+603
-1003
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

44 files changed

+603
-1003
lines changed

6-deployed-agents/finance/company-overview-agent/agent.py

Lines changed: 6 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,17 @@
11
import os
22
import time
33
from enum import Enum
4-
from typing import Dict
54

6-
import requests
5+
from chat_proto import chat_proto, struct_output_client_proto
76
from uagents import Agent, Context, Model
87
from uagents.experimental.quota import QuotaProtocol, RateLimit
9-
from uagents.models import ErrorMessage
8+
from uagents_core.models import ErrorMessage
9+
10+
from functions import CompanyOverviewResponse, CompanyOverviewRequest, fetch_overview_json
1011

1112
AGENT_SEED = os.getenv("AGENT_SEED", "company-overview")
1213
AGENT_NAME = os.getenv("AGENT_NAME", "Company Overview Agent")
1314

14-
ALPHAVANTAGE_API_KEY = os.getenv("ALPHAVANTAGE_API_KEY")
15-
16-
if ALPHAVANTAGE_API_KEY is None:
17-
raise ValueError("You need to provide an API key for Alpha Vantage.")
18-
19-
20-
class CompanyOverviewRequest(Model):
21-
ticker: str
22-
23-
24-
class CompanyOverviewResponse(Model):
25-
overview: Dict[str, str]
26-
2715

2816
PORT = 8000
2917
agent = Agent(
@@ -41,24 +29,6 @@ class CompanyOverviewResponse(Model):
4129
)
4230

4331

44-
def fetch_overview_json(ticker: str) -> dict:
45-
url = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={ticker}&apikey={ALPHAVANTAGE_API_KEY}"
46-
47-
try:
48-
response = requests.get(url, timeout=10)
49-
except requests.exceptions.Timeout:
50-
return {"error": "The request timed out. Please try again."}
51-
except requests.exceptions.RequestException as e:
52-
return {"error": f"An error occurred: {e}"}
53-
54-
data = response.json()
55-
56-
if not data or "Symbol" not in data:
57-
return {"error": "No valid data found in the response."}
58-
59-
return data
60-
61-
6232
@proto.on_message(
6333
CompanyOverviewRequest, replies={CompanyOverviewResponse, ErrorMessage}
6434
)
@@ -91,6 +61,8 @@ async def handle_request(ctx: Context, sender: str, msg: CompanyOverviewRequest)
9161

9262

9363
agent.include(proto, publish_manifest=True)
64+
agent.include(chat_proto, publish_manifest=True)
65+
agent.include(struct_output_client_proto, publish_manifest=True)
9466

9567

9668
# Health check related code
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
from datetime import datetime
2+
import os
3+
import time
4+
from typing import Any
5+
from uagents import Context, Model, Protocol
6+
from uagents_core.contrib.protocols.chat import (
7+
ChatAcknowledgement,
8+
ChatMessage,
9+
EndSessionContent,
10+
StartSessionContent,
11+
TextContent,
12+
chat_protocol_spec,
13+
)
14+
15+
from uuid import uuid4
16+
17+
from functions import CompanyOverviewRequest, fetch_overview_json
18+
19+
20+
AI_AGENT_ADDRESS = os.getenv("AI_AGENT_ADDRESS")
21+
22+
23+
def create_text_chat(text: str, end_session: bool = True) -> ChatMessage:
24+
content = [TextContent(type="text", text=text)]
25+
if end_session:
26+
content.append(EndSessionContent(type="end-session"))
27+
return ChatMessage(
28+
timestamp=datetime.utcnow(),
29+
msg_id=uuid4(),
30+
content=content,
31+
)
32+
33+
34+
chat_proto = Protocol(spec=chat_protocol_spec)
35+
36+
struct_output_client_proto = Protocol(
37+
name="StructuredOutputClientProtocol", version="0.1.0"
38+
)
39+
40+
41+
class StructuredOutputPrompt(Model):
42+
prompt: str
43+
output_schema: dict[str, Any]
44+
45+
46+
class StructuredOutputResponse(Model):
47+
output: dict[str, Any]
48+
49+
50+
@chat_proto.on_message(ChatMessage)
51+
async def handle_message(ctx: Context, sender: str, msg: ChatMessage):
52+
await ctx.send(
53+
sender,
54+
ChatAcknowledgement(
55+
timestamp=datetime.utcnow(), acknowledged_msg_id=msg.msg_id
56+
),
57+
)
58+
for item in msg.content:
59+
if isinstance(item, StartSessionContent):
60+
ctx.logger.info(f"Got a start session message from {sender}")
61+
continue
62+
elif isinstance(item, TextContent):
63+
ctx.logger.info(f"Got a message from {sender}: {item.text}")
64+
ctx.storage.set(str(ctx.session), sender)
65+
await ctx.send(
66+
AI_AGENT_ADDRESS,
67+
StructuredOutputPrompt(
68+
prompt=item.text, output_schema=CompanyOverviewRequest.schema()
69+
),
70+
)
71+
else:
72+
ctx.logger.info(f"Got unexpected content from {sender}")
73+
74+
75+
@chat_proto.on_message(ChatAcknowledgement)
76+
async def handle_ack(ctx: Context, sender: str, msg: ChatAcknowledgement):
77+
ctx.logger.info(
78+
f"Got an acknowledgement from {sender} for {msg.acknowledged_msg_id}"
79+
)
80+
81+
82+
@struct_output_client_proto.on_message(StructuredOutputResponse)
83+
async def handle_structured_output_response(
84+
ctx: Context, sender: str, msg: StructuredOutputResponse
85+
):
86+
prompt = CompanyOverviewRequest.parse_obj(msg.output)
87+
session_sender = ctx.storage.get(str(ctx.session))
88+
if session_sender is None:
89+
ctx.logger.error(
90+
"Discarding message because no session sender found in storage"
91+
)
92+
return
93+
94+
cache = ctx.storage.get(prompt.ticker) or None
95+
if cache:
96+
if int(time.time()) - cache["timestamp"] < 86400:
97+
cache.pop("timestamp")
98+
chat_message = create_text_chat(
99+
f"Company: {cache['Name']} ({cache['Symbol']})\n"
100+
f"Exchange: {cache['Exchange']} | Currency: {cache['Currency']}\n"
101+
f"Industry: {cache['Industry']} | Sector: {cache['Sector']}\n"
102+
f"Market Cap: {cache['Currency']} {cache['MarketCapitalization']}\n"
103+
f"PE Ratio: {cache['PERatio']} | EPS: {cache['EPS']}\n"
104+
f"Website: {cache['OfficialSite']}\n\n"
105+
f"Description: {cache['Description']}"
106+
)
107+
await ctx.send(session_sender, chat_message)
108+
return
109+
110+
try:
111+
output_json = fetch_overview_json(prompt.ticker)
112+
except Exception as err:
113+
ctx.logger.error(err)
114+
await ctx.send(
115+
session_sender,
116+
create_text_chat(
117+
"Sorry, I couldn't process your request. Please try again later."
118+
),
119+
)
120+
return
121+
122+
if "error" in output_json:
123+
await ctx.send(session_sender, create_text_chat(str(output_json["error"])))
124+
return
125+
126+
chat_message = create_text_chat(
127+
f"Company: {output_json['Name']} ({output_json['Symbol']})\n"
128+
f"Exchange: {output_json['Exchange']} | Currency: {output_json['Currency']}\n"
129+
f"Industry: {output_json['Industry']} | Sector: {output_json['Sector']}\n"
130+
f"Market Cap: {output_json['Currency']} {output_json['MarketCapitalization']}\n"
131+
f"PE Ratio: {output_json['PERatio']} | EPS: {output_json['EPS']}\n"
132+
f"Website: {output_json['OfficialSite']}\n\n"
133+
f"Description: {output_json['Description']}"
134+
)
135+
136+
output_json["timestamp"] = int(time.time())
137+
ctx.storage.set(prompt.ticker, output_json)
138+
await ctx.send(session_sender, chat_message)
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
import os
2+
import requests
3+
from typing import Dict
4+
from uagents import Model, Field
5+
6+
ALPHAVANTAGE_API_KEY = os.getenv("ALPHAVANTAGE_API_KEY")
7+
8+
if ALPHAVANTAGE_API_KEY is None:
9+
raise ValueError("You need to provide an API key for Alpha Vantage.")
10+
11+
12+
class CompanyOverviewRequest(Model):
13+
ticker: str = Field(
14+
description="The stock ticker symbol (e.g., AAPL for Apple Inc.) used to identify the company on financial markets.",
15+
)
16+
17+
18+
class CompanyOverviewResponse(Model):
19+
overview: Dict[str, str]
20+
21+
22+
def fetch_overview_json(ticker: str) -> dict:
23+
url = f"https://www.alphavantage.co/query?function=OVERVIEW&symbol={ticker}&apikey={ALPHAVANTAGE_API_KEY}"
24+
25+
try:
26+
response = requests.get(url, timeout=10)
27+
except requests.exceptions.Timeout:
28+
return {"error": "The request timed out. Please try again."}
29+
except requests.exceptions.RequestException as e:
30+
return {"error": f"An error occurred: {e}"}
31+
32+
data = response.json()
33+
34+
if not data or "Symbol" not in data:
35+
return {"error": "No valid data found in the response."}
36+
37+
return data

6-deployed-agents/finance/company-overview-agent/pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ readme = "README.md"
77

88
[tool.poetry.dependencies]
99
python = "^3.10,<3.13"
10-
uagents = "^0.15.2"
10+
uagents = "^0.22.0"
1111
requests = "^2.32.3"
1212

1313
[build-system]

6-deployed-agents/finance/company-ticker-resolver-agent/agent.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import requests
77
from uagents import Agent, Context, Model
88
from uagents.experimental.quota import QuotaProtocol, RateLimit
9-
from uagents.models import ErrorMessage
9+
from uagents_core.models import ErrorMessage
1010

1111
AGENT_SEED = os.getenv("AGENT_SEED", "ticker-agent")
1212
AGENT_NAME = os.getenv("AGENT_NAME", "Company Ticker Resolver Agent")

6-deployed-agents/finance/finance-q&a-agent/agent.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
from chat_proto import chat_proto
66
from uagents import Agent, Context, Model
77
from uagents.experimental.quota import QuotaProtocol, RateLimit
8-
from uagents.models import ErrorMessage
8+
from uagents_core.models import ErrorMessage
99

1010
AGENT_SEED = os.getenv("AGENT_SEED", "finance_qa_agent")
1111
AGENT_NAME = os.getenv("AGENT_NAME", "Finance Q&A Agent")

0 commit comments

Comments
 (0)