LlamaIndex OpenAI Agent

0.4.12 · active · verified Fri Apr 10

The `llama-index-agent-openai` library provides an integration for creating agents within LlamaIndex that leverage OpenAI's language models. It allows defining tools and orchestrating them with OpenAI's function-calling capabilities, making it easy to build powerful LLM-powered applications. As part of the LlamaIndex ecosystem, it stays current with LlamaIndex's modular architecture (v0.10+). The current version is `0.4.12`, with updates typically aligning with LlamaIndex core releases.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to initialize an `OpenAIAgent` with a custom `FunctionTool` and use it to perform calculations through conversational prompts. Ensure your `OPENAI_API_KEY` environment variable is set for successful authentication with OpenAI.

import os
from llama_index.agent.openai import OpenAIAgent
from llama_index.llms.openai import OpenAI
from llama_index.core.tools import FunctionTool

def multiply(a: int, b: int) -> int:
    """Multiply two integers and return the result integer"""
    return a * b

# Define a tool from a function
multiply_tool = FunctionTool.from_defaults(fn=multiply)

# Initialize LLM with API key (ensure OPENAI_API_KEY is set in environment)
llm = OpenAI(
    model="gpt-3.5-turbo",
    api_key=os.environ.get('OPENAI_API_KEY', '') # Use os.environ.get for security
)

# Initialize OpenAI agent with tools
agent = OpenAIAgent.from_tools(
    tools=[multiply_tool],
    llm=llm,
    verbose=True,
)

# Chat with the agent
response = agent.chat("What is 2 * 2?")
print(f"Agent Response: {response}")

response_complex = agent.chat("What is 10 times 5 plus 3?")
print(f"Agent Response (complex): {response_complex}")

view raw JSON →