Skip to main content

Step 1: Install Required Libraries

pip install pydantic requests

Step 2: Set Up API Configuration

import os
import requests
import json

os.environ["OPENAI_API_KEY"] = "YOUR OPENAI API KEY"
BASE_URL = "https://orch.zenbase.ai/api"
API_KEY = "YOUR ZENBASE API KEY"

def api_call(method, endpoint, data=None):
    url = f"{BASE_URL}/{endpoint}"
    headers = {
        "Content-Type": "application/json",
        "Authorization": f"Api-Key {API_KEY}"
    }
    response = requests.request(method, url, headers=headers, data=json.dumps(data) if data else None)
    return response

Step 3: Define Your Models

Define the input and output models for your task. Here we define the input and output models for the sentiment analysis task, which involves analyzing the sentiment of a given text.
from pydantic import BaseModel, Field
from enum import Enum

from pydantic import BaseModel, Field
from typing import Literal

class SentimentInput(BaseModel):
    text: str = Field(..., description="The text to be analyzed for sentiment.")

class SentimentOutput(BaseModel):
    sentiment: Literal["positive", "negative", "neutral"] = Field(..., description="The sentiment of the input text.")

Step 4: Create a Function

Create a function that encapsulates the task’s objective, how the prompt is structured, and the expected inputs and outputs. In this case, we define a function for the sentiment analysis task.
from textwrap import dedent
function_data = {
    "name": "Sentiment Analysis",
    "description": "Analyze the sentiment of a given text.",
    "prompt": dedent("""Analyze the sentiment of the given text.
                    Determine if the sentiment is positive, negative, or neutral.

                    Definitions:
                    - Positive: The text expresses a favorable or happy sentiment.
                    - Negative: The text expresses an unfavorable or unhappy sentiment.
                    - Neutral: The text does not express a clearly positive or negative sentiment.
                    """),
    "input_schema": SentimentInput.model_json_schema(),
    "output_schema": SentimentOutput.model_json_schema(),
    "api_key": os.environ.get("OPENAI_API_KEY"),
    "model": "gpt-4o-mini"
}

function = api_call("POST", "functions/", function_data)
function_id = function.json()['id']

Step 5: Get results from Zenbase function

test_input = {
    "text": "I absolutely love this new restaurant! The food is delicious, the service is excellent, and the atmosphere is wonderful. I can't wait to go back again."
}

result = api_call("POST", f"functions/{function_id}/run/", {"inputs": test_input})

print(f"Manual function result: {result.json()}")