Back to Llama Index

Setup OpenAI Agent

llama-index-integrations/tools/llama-index-tools-google/examples/google_search.ipynb

0.14.211.1 KB
Original Source
python
# Setup OpenAI Agent
import os

os.environ["OPENAI_API_KEY"] = "sk-your-key"

from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.openai import OpenAI
python
# Import and initialize our tool spec
from llama_index.tools.tool_spec.load_and_search.base import LoadAndSearchToolSpec
from llama_index.tools.google_search.base import GoogleSearchToolSpec

google_spec = GoogleSearchToolSpec(key="your-key", engine="your-engine")

# Wrap the google search tool as it returns large payloads
tools = LoadAndSearchToolSpec.from_defaults(
    google_spec.to_tool_list()[0],
).to_tool_list()
python
# Create the Agent with our tools
agent = FunctionAgent(
    tools=tools,
    llm=OpenAI(model="gpt-4.1"),
)

# Context to store chat history
from llama_index.core.workflow import Context

ctx = Context(agent)
python
await agent.run("who is barack obama", ctx=ctx)
python
await agent.run("when is the last time barrack obama visited michigan", ctx=ctx)
python
await agent.run("when else did he visit michigan", ctx=ctx)
python
await agent.run("what is his favourite sport", ctx=ctx)