The following example outlines how to use OpenAI Function Calling and the Superface API.

If you want to run this example for yourself as a Jupyter Notebook, you can download the .ipynb file:

superface_agent_hub_openai_example.ipynb

Prerequisites

pip install openai

Setup

Import the dependencies, and setup the required constants.

import openai
import json
import random
import requests as r
from openai import OpenAI
from IPython.display import display, Markdown

# Set a random number of your choice, but don't change it
# once you have run the notebook, otherwise you will create another user.
SUPERFACE_USER_ID_CONSTANT =

# Use the number to create a unique ID
SUPERFACE_USER_ID = "sfoaidemo|" + str(SUPERFACE_USER_ID_CONSTANT)

# Default URL for Superface
SUPERFACE_BASE_URL = "<https://pod.superface.ai/api/hub>"

# Set the Superface authentication token
SUPERFACE_AUTH_TOKEN="<your-superface-auth-token>"

# Set the OpenAI API Key
OPENAI_API_KEY="<your-open-api-key>"

OpenAI setup

Next, set up the basis of the OpenAI SDK including which model to use. The system prompt below can be changed, but it is worth including if you have space for it to ensure that the prompts returned by Superface's API are handled correctly in context.

# OpenAI Config
client = OpenAI(api_key=OPENAI_API_KEY)
GPT_MODEL = "gpt-4-turbo-preview"
INIT_INSTRUCTIONS = """
You are a helpful assistant.
Respond to the following prompt by using function_call and then summarize actions.
Ask for clarification if a user request is ambiguous.
Display the agent_hint from the response to the user if it is present.
"""

Helper functions

Below, we have defined two helper functions.

These helpers are for example purposes and you are welcome to build different ways to approach these in whatever manner you choose.

# Helper function to return the tool function descriptors
def get_superface_tools():
  headers = {"Authorization": "Bearer "+ SUPERFACE_AUTH_TOKEN}
  tools = r.get(SUPERFACE_BASE_URL + "/fd", headers=headers)
  return tools.json()

# Helper function to perform the action for all the functions.
# This is the only API call required regardless of what the function is.
def perform_action(tool_name=None, tool_body=None):
  headers = {"Authorization": "Bearer "+ SUPERFACE_AUTH_TOKEN, "x-superface-user-id": SUPERFACE_USER_ID}
  perform = r.post(SUPERFACE_BASE_URL + "/perform/" + tool_name, headers=headers, json=tool_body)
  return json.dumps(perform.json())

# Helper function for calling the OpenAI Chat Completions API
def perform_chat_request(messages, tools=None, tool_choice=None, model=GPT_MODEL):
  try:
    response = client.chat.completions.create(
      model=model,
      messages=messages,
      tools=tools,
      tool_choice=tool_choice,
    )
    return response
  except Exception as e:
    print("Unable to generate ChatCompletion response")
    print(f"Exception: {e}")
    return e

Prompt