forked from onlyphantom/llm-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproject_assignment_04.py
More file actions
102 lines (87 loc) · 3.68 KB
/
project_assignment_04.py
File metadata and controls
102 lines (87 loc) · 3.68 KB
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
import os
import asyncio
import json
import requests
from typing import List
from agents import Agent, Runner, function_tool
from dotenv import load_dotenv
load_dotenv()
SECTORS_API_KEY = os.getenv("SECTORS_API_KEY")
if not SECTORS_API_KEY:
raise ValueError("SECTORS_API_KEY environment variable is not set")
headers = {"Authorization": SECTORS_API_KEY}
def retrieve_from_endpoint(url: str) -> str:
try:
response = requests.get(url, headers=headers, timeout=30)
response.raise_for_status()
data = response.json()
except requests.exceptions.HTTPError as err:
raise RuntimeError(f"HTTP error occurred: {err}") from err
except requests.exceptions.RequestException as err:
raise RuntimeError(f"Request error occurred: {err}") from err
except json.JSONDecodeError as err:
raise RuntimeError(f"JSON decode error: {err}") from err
return json.dumps(data)
@function_tool
def get_company_overview(ticker: str, country: str) -> str:
"""
Get company overview from Singapore Exchange (SGX), Bursa Malaysia (KLSE), or Indonesia Exchange (IDX)
"""
valid_countries = ["indonesia", "singapore", "malaysia"]
country_lower = country.lower()
if country_lower not in valid_countries:
raise ValueError(f"Country must be one of {valid_countries}")
if not ticker or not ticker.strip():
raise ValueError("Ticker cannot be empty")
# Returns a comprehensive company report organized into distinct sections. By default all sections are included.
# Use sections to request only the data you need and reduce response size.
if country.lower() == "indonesia":
url = f"https://api.sectors.app/v2/company/report/{ticker}/?sections=overview"
elif country.lower() == "singapore":
url = f"https://api.sectors.app/v2/sgx/company/report/{ticker}/"
elif country.lower() == "malaysia":
url = f"https://api.sectors.app/v2/klse/company/report/{ticker}/"
try:
return retrieve_from_endpoint(url)
except Exception as e:
error_msg = f"Error retrieving company overview for {ticker}: {e}"
print(error_msg)
return json.dumps({"error": error_msg})
@function_tool
def find_companies_screener(query: str) -> str:
"""
High-performance API for filtering and sorting IDX-listed companies.
Supports both structured SQL-like queries (where, order_by) and natural language queries (q).
"""
if not query or not query.strip():
raise ValueError("Query cannot be empty")
url = f"https://api.sectors.app/v2/companies/?q={query.strip()}"
try:
return retrieve_from_endpoint(url)
except Exception as e:
error_msg = f"Error searching companies: {e}"
print(error_msg)
return json.dumps({"error": error_msg})
research_assistant = Agent(
name="Research Assistant",
instructions="""Your are a financial research assistant that cover stock exchange information from Indonesia, Singapore, and Malaysia.
If the user query ask report of information by providing company's {ticker}, use get_company_overview tool.
If the user query is not clear what companies, ask for company's ticker.
If the user query ask for general information of Indonesian companies or based on certain criteria, use find_companies_screener tool.
""",
tools=[
get_company_overview,
find_companies_screener,
],
tool_use_behavior="run_llm_again"
)
async def main():
query = input("Enter your query: ")
result = await Runner.run(
research_assistant,
query
)
print(f"😊: {query}")
print(f"🤖: {result.final_output}")
if __name__ == "__main__":
asyncio.run(main())