{"id":19944265,"url":"https://github.com/lazauk/aoai-gptfunctioncalling-stock","last_synced_at":"2025-05-03T16:30:53.642Z","repository":{"id":182674326,"uuid":"668900993","full_name":"LazaUK/AOAI-GPTFunctionCalling-Stock","owner":"LazaUK","description":"Use of Function Calling with Azure OpenAI GPT models to retrieve the lowest and highest stock prices for specific symbol and date.","archived":false,"fork":false,"pushed_at":"2023-12-19T17:10:45.000Z","size":54,"stargazers_count":3,"open_issues_count":0,"forks_count":3,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-04-07T18:06:57.472Z","etag":null,"topics":["ai","azure","function-calling","gpt","openai","openai-function-call"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/LazaUK.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-07-20T21:38:09.000Z","updated_at":"2023-11-24T22:24:33.000Z","dependencies_parsed_at":"2024-11-13T00:29:53.651Z","dependency_job_id":null,"html_url":"https://github.com/LazaUK/AOAI-GPTFunctionCalling-Stock","commit_stats":null,"previous_names":["lazauk/aoai-gptfunctioncalling-stock"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LazaUK%2FAOAI-GPTFunctionCalling-Stock","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LazaUK%2FAOAI-GPTFunctionCalling-Stock/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LazaUK%2FAOAI-GPTFunctionCalling-Stock/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/LazaUK%2FAOAI-GPTFunctionCalling-Stock/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/LazaUK","download_url":"https://codeload.github.com/LazaUK/AOAI-GPTFunctionCalling-Stock/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":252216058,"owners_count":21713088,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["ai","azure","function-calling","gpt","openai","openai-function-call"],"created_at":"2024-11-13T00:19:43.982Z","updated_at":"2025-05-03T16:30:53.374Z","avatar_url":"https://github.com/LazaUK.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Azure OpenAI - Function Calling to retrieve Stock Price\n\nAs of 20th of July 2023, Azure OpenAI now supports the use of Function Calling with GPT-3.5 and GPT-4 models. This repo contains Jupyter notebook to test functional calling first-hand by retrieving stock price from [Alpha Vantage API](https://www.alphavantage.co/).\n\n### 0. Pre-requisites:\n\n1. Install the latest version of openai Python package and set **openai.api_version** code variable to July 2023 version or above;\n    ``` Python\n    openai.api_version = \"2023-07-01-preview\"\n    ```\n3. Retrieve GPT model deployment name, API endpoint and API key from Azure OpenAI settings and assign them to \"**OPENAI_API_DEPLOY**\", \"**OPENAI_API_BASE**\" and \"**OPENAI_API_KEY**\" environment variables, respectively;\n4. Generator your Alpha Vantage API key on the vendor's Web site and assign it to \"**ALPHAVANTAGE_API_KEY**\" environment variable.\n\n### 1. Function to get stock price from Alpha Vantage API:\n\nWe'll use **get_stock_price** custom function to interact with stock API and retrieve the lowest and highest prices on specific date for the stock symbol of interest. JSON structure returned by API endpoint is parsed to extract only specific time series values.\n``` Python\ndef get_stock_price(symbol, date):\n    print(f\"Getting stock price for {symbol} on {date}\")\n    try:\n        stock_url = f\"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY\u0026symbol={symbol}\u0026apikey={av_api_key}\"\n        stock_data = requests.get(stock_url)\n        stock_low = stock_data.json()[\"Time Series (Daily)\"][date][\"3. low\"]\n        stock_high = stock_data.json()[\"Time Series (Daily)\"][date][\"2. high\"]\n        return stock_low, stock_high\n    except:\n        return \"NA\", \"NA\"\n```\n\n### 2. JSON structure for GPT function definition:\n\nAzure OpenAI GPT models v0613 were trained to understand function structure that contain \"**name**\" and \"**parameters**\" fields. In my example, I indicate that the model can extract and match 2 mandatory properties: stock symbol for requested company and date in _YYYY-MM-DD_ format.\n\n``` JSON\nfunctions = [\n    {\n        \"name\": \"get_stock_price\",\n        \"description\": \"Retrieve lowest and highest stock price for a given stock symbol and date\",\n        \"parameters\": {\n            \"type\": \"object\",\n            \"properties\": {\n                \"symbol\": {\n                    \"type\": \"string\",\n                    \"description\": \"Stock symbol, for example MSFT for Microsoft\"\n                },\n                \"date\": {\n                    \"type\": \"string\",\n                    \"description\": \"Date in YYYY-MM-DD format\"\n                }\n            },\n            \"required\": [\"symbol\", \"date\"],\n        }   \n    }\n]\n```\n\n### 3. Helper function to check provided arguments:\n\nI copied function \"**check_args**\" from [Azure Samples code](https://github.com/Azure-Samples/openai/tree/main/Basic_Samples/Functions) \"as is\". It helps to verify whether GPT model provided all requirements arguments / parameters, and also if it tried to submit ones which our function doesn't expect.\n\n### 4. Helper function to interact with Azure OpenAI GPT model:\n\nThis helper function follows 3-step logic:\n1. First, it submits user's prompts, informs GPT model about available functions and sets calling mode to \"**auto**\", so that the model automatically decides whether it wants to call a function based on the prompt details and matching function's capabilities\n    ``` Python\n    response = openai.ChatCompletion.create(\n        deployment_id=aoai_deployment,\n        messages=messages,\n        functions=functions,\n        function_call=\"auto\", \n    )\n    ```\n2. Next, it checks what functions the model wanted to call, if any.\n   ``` Python\n    response_message = response[\"choices\"][0][\"message\"]\n\n    # Step 2: Check if GPT model wanted to call a function\n    if response_message.get(\"function_call\"):\n        print(\"Recommended function call:\")\n        print(response_message.get(\"function_call\"))\n        print()\n   ```\n3. Finally, if there is a matching function and it passes previous help function's test on validity of its arguments, I call the target function with parameter values extracted from the user's prompt.\n   ``` Python\n   function_response1, function_response2 = function_to_call(function_args[\"symbol\"], function_args[\"date\"])\n   function_response = f\"Lowest stock price: {function_response1}, Highest stock price: {function_response2}\"\n   ```\n### 5. Practical testing:\n\nThe last cell in the notebook helps to test everything end to end. On requested stock price for Microsoft shares from 20th of July, 2023 it correctly retrieves the lowest and highest prices of the day.\n``` JSON\nRecommended function call:\n{\n  \"name\": \"get_stock_price\",\n  \"arguments\": \"{\\n  \\\"symbol\\\": \\\"MSFT\\\",\\n  \\\"date\\\": \\\"2023-07-20\\\"\\n}\"\n}\n\nGetting stock price for MSFT on 2023-07-20\nOutput of function call:\nLowest stock price: 345.3700, Highest stock price: 357.9700\n\nMessages in second request:\n{'role': 'user', 'content': 'What was the stock price of Microsoft shares on 20th of July 2023?'}\n{'role': 'assistant', 'name': 'get_stock_price', 'content': '{\\n  \"symbol\": \"MSFT\",\\n  \"date\": \"2023-07-20\"\\n}'}\n{'role': 'function', 'name': 'get_stock_price', 'content': 'Lowest stock price: 345.3700, Highest stock price: 357.9700'}\n\n{\n  \"role\": \"assistant\",\n  \"content\": \"On the 20th of July 2023, the stock price of Microsoft (MSFT) had a low of $345.37 and a high of $357.97.\"\n}\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flazauk%2Faoai-gptfunctioncalling-stock","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flazauk%2Faoai-gptfunctioncalling-stock","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flazauk%2Faoai-gptfunctioncalling-stock/lists"}