What is NPi?
NPi (Natural-language Programming Interface), pronounced as "N π", is an open-source platform providing Tool-use APIs to empower AI agents with the ability to operate and interact with a diverse array of software tools and applications.
Quick Start
Installation
Begin by installing the NPi AI package via pip:
pip install npiai
Create a New Tool
Let's create a new tool to compute the nth Fibonacci number. Start by crafting a new Python file titled main.py
and insert the following snippet:
from npiai import FunctionTool, function
class MyTool(FunctionTool):
def __init__(self):
super().__init__(
name='Fibonacci',
description='My first NPi tool',
)
@function
def fibonacci(self, n: int) -> int:
"""
Get the nth Fibonacci number.
Args:
n: The index of the Fibonacci number in the sequence.
"""
if n == 0:
return 0
if n == 1:
return 1
return self.fibonacci(n - 1) + self.fibonacci(n - 2)
Run the Tool
You could use NPi tools in two different ways: function mode
and agent mode
. Let's explore both modes.
Function Mode
Function mode enables the integration of NPi tools with existing LLM-based AI application. In this mode, tools are packaged as callable functions that the AI agent can invoke in response to user prompts, the chosen of functions will be decided by user-side agent.
import asyncio
import json
import os
from openai import OpenAI
from my_tool import MyTool
async def main():
async with MyTool() as tool:
print(f'The schema of the tool is\n\n {json.dumps(tool.tools, indent=2)}')
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))
messages = [
{
"role": "user",
"content": "What's the 10-th fibonacci number?",
}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
tools=tool.tools,
tool_choice="auto",
max_tokens=4096,
)
response_message = response.choices[0].message
if response_message.tool_calls:
result = await tool.call(tool_calls=response_message.tool_calls)
print(f'The result of calling\n\n {json.dumps(result, indent=2)}')
if __name__ == "__main__":
asyncio.run(main())
[
{
"role": "tool",
"name": "fibonacci",
"tool_call_id": "call_UhkeQxrVr2LQoJOfUdR9WPdw",
"content": "55"
}
]
Agent Mode
Agent mode allows an NPi tools to serve as an independent Tool agents that can directly take plain queries and generate
responses. In this mode, the tool receives instructions, do in-tool planning
to decide the sequence of function calling,
and returns the result as an output message. This mode simplify the problem-solving for domain-specific questions.
We suggest you use this mode in your Agentic AI applications.
import asyncio
from npiai import agent, Context
from my_tool import MyTool
async def main():
async with agent.wrap(MyTool()) as tool:
# make sure you have set the OPENAI_API_KEY in your environment variables
result = await tool.chat(ctx=Context(), instruction="What's the 10-th fibonacci number?")
print(result)
if __name__ == "__main__":
asyncio.run(main())
The 10th Fibonacci number is 55.