AI Integrations
OpenAI Python SDK
Code execution for OpenAI in Python
Install the required dependencies
pip install openai freestyle
Get your Freestyle API Key from the Freestyle Dashboard
Set up the Code Executor
The simplest code executor looks like this:
import os
from freestyle.openai import execute_tool
(definition, runner) = freestyle.openai.execute_tool(
os.environ.get("FREESTYLE_API_KEY"),
)
Adding Node Modules
When you want your AI code execution to have access to specific node modules, you can pass them in through the configuration parameter:
import os
from freestyle.openai import execute_tool
import freestyle
(definition, runner) = freestyle.openai.execute_tool(
os.environ.get("FREESTYLE_API_KEY"),
freestyle.FreestyleExecuteScriptParamsConfiguration(
nodeModules={"mathjs": "14.3.1"}
),
)
Adding Environment Variables
You can also pass in environment variables that your AI code execution will have access to:
import os
from freestyle.openai import execute_tool
import freestyle
(definition, runner) = freestyle.openai.execute_tool(
os.environ.get("FREESTYLE_API_KEY"),
freestyle.FreestyleExecuteScriptParamsConfiguration(
envVars={"RESEND_API_KEY": os.environ.get("RESEND_API_KEY")}
nodeModules={"resend":"4.1.2"}
),
)
Other Configuration Options
- timeout: The maximum time in seconds that the code execution is allowed to run.
- networkPermissions: A list of URLs that the code execution is allowed to access.
- peerDependencyResolution: Configure if peer dependencies should be resolved — do not use this unless you know what you are doing.
Set up the OpenAI Python SDK
import openai
client = openai.OpenAI(
api_key=os.environ.get("OPENAI_API_KEY"),
)
query = "What is the sum of every number from 50 to 65 divided by 17"
messages = [{"role": "user", "content": query}]
res = client.chat.completions.create(
model="gpt-4-turbo", messages=messages, tools=[definition]
)
result = runner(res.choices[0].message)
The
definition
and runner
variables are from the code executor setup. The definition
is an OpenAI compatible tool definition, and the runner
is a function that takes in an OpenAI Compatible Model response and returns the output of the code execution if there is one. Runner
is made to be called on every response from the OpenAI model, if there is no code execution then it returns None
and does nothing.