Skip to content

Instantly share code, notes, and snippets.

@kordless
Created June 14, 2023 19:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kordless/f0231c58aec461ae3ede10361d65baa2 to your computer and use it in GitHub Desktop.
Save kordless/f0231c58aec461ae3ede10361d65baa2 to your computer and use it in GitHub Desktop.
Developing an OpenAI Functions Decorator
"""
Hacker News Top Stories
Author:
Date: June 12, 2023
Description:
This script fetches the top 10 stories from Hacker News using Algolia's search API. It retrieves the stories posted within the last 24 hours and prints their titles and URLs.
Dependencies:
- requests: HTTP library for sending API requests
- bs4: Beautiful Soup library for parsing HTML content
API Used:
- Hacker News search API by Algolia
Note:
Make sure to install the necessary dependencies before running this script.
"""
import requests
from bs4 import BeautifulSoup
from datetime import datetime
import ast
import inspect
class FunctionWrapper:
def __init__(self, func):
self.func = func
self.info = self.extract_function_info()
def extract_function_info(self):
source = inspect.getsource(self.func)
tree = ast.parse(source)
# Extract function name
function_name = tree.body[0].name
# Extract function arguments and their types
args = tree.body[0].args
arguments = []
for arg in args.args:
argument_name = arg.arg
argument_type = ast.get_source_segment(source, arg.annotation)
arguments.append({
"name": argument_name,
"type": argument_type
})
# Extract function return type
return_type = None
if tree.body[0].returns:
return_type = ast.get_source_segment(source, tree.body[0].returns)
function_info = {
"name": function_name,
"parameters": {
"properties": {
"input": {
"type": arguments,
},
"output": {
"type": return_type,
}
}
}
}
return function_info
def __call__(self, *args, **kwargs):
return self.func(*args, **kwargs)
def function(self):
return self.info
def function_info_decorator(func):
return FunctionWrapper(func)
@function_info_decorator
def get_top_stories() -> dict[str,str]:
base_url = "https://hn.algolia.com/api/v1/search"
params = {
"tags": "story",
"numericFilters": "created_at_i>{0},created_at_i<{1}".format(
int(datetime.now().strftime("%s")) - 86400, # 24 hours ago
int(datetime.now().strftime("%s")) # current timestamp
),
"hitsPerPage": 10
}
response = requests.get(base_url, params=params)
if response.status_code == 200:
data = response.json()
# Create a dictionary to store the stories
document = {}
# Iterate over the top stories and extract title and URL
for index, hit in enumerate(data["hits"], start=1):
title = hit["title"]
url = hit["url"]
document[index] = {"title": title, "url": url}
return document
else:
return None
# Call the function and store the returned document
document = get_top_stories()
print(get_top_stories.function())
# Check for errors
if document is None:
print("Failed to retrieve top stories.")
else:
# Print the contents of the document
for index, story in document.items():
print(f"{index}. {story['title']} - {story['url']}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment