DataDrivenInvestor

empowerment through data, knowledge, and expertise. subscribe to DDIntel at…

Follow publication

Creating Your First GPT Agent with Python

NUTHDANAI WANGPRATHAM
DataDrivenInvestor
Published in
9 min readJun 2, 2024

--

The concept of agents is widely employed in developing large language models (LLMs), such as the GPT series, which develops specialized agents for particular tasks. An illustrative example of this application is OpenAI Assistant. These “agents,” often called LLM agents, are designed to perform specific functions within the broader architecture of language processing and generation, thereby enhancing the efficacy and adaptability of the models in handling complex dialogues and tasks. Today we will discuss Agent in GPT and show some examples for developing Agent in Open AI API and Python.

Whether you are looking to create a simple chatbot, for personal use or complex virtual assistants for business applications This tutorial provides the basic knowledge and step-by-step instructions needed to bring your AI project to life. At the end of this article, You’ll have a fully functioning agent who can engage in meaningful conversations. with the potential to expand and customize agent capabilities to meet your needs.

What about Agent

The concept of an agent is not a novel idea; rather, it is deeply rooted in philosophical thought, with contributions from notable philosophers such as Aristotle and Hume. Broadly defined, an “agent” is an entity capable of action, and “agency” refers to the expression or demonstration of this capability. In a more specific context, “agency” typically pertains to the execution of deliberate actions. Consequently, the term “agent” applies to entities that hold desires, beliefs, intentions, and the capacity for action.

Crucially, the notion of an agent encompasses individual autonomy, endowing entities with the capacity for volition, decision-making, and proactive behavior, in contrast to mere passive responses to external forces.

Efforts to develop Artificial General Intelligence (AGI) have been ongoing, with significant milestones such as the advent of GPT-3.5, which astonished the global community with its capabilities. Despite these advancements, it has become evident that GPT-3.5 is far from AGI.
The complexity of developing a single AI system capable of performing all cognitive tasks at human levels is widely acknowledged. Consequently, a more pragmatic approach has emerged, focusing on the development of specialized AI systems that can collaborate effectively. This strategy leverages the strengths of various AI constructs, facilitating a composite intelligence that can operate synergistically in complex environments.

How to develop Agent in Open AI API and Python.

By leveraging OpenAI’s API, you can create intelligent and interactive agents that can understand and respond to natural language input. we will discuss on through the process of developing AI agents using the OpenAI API and Python on step by step

Assistants API

The Assistants API allows you to build AI assistants within your own applications. An Assistant has instructions and can leverage models, tools, and files to respond to user queries. The Assistants API currently supports three types of tools: Code Interpreter, File Search, and Function calling.

On the left sidebar, you have access to various features and settings:

  • Playground: Experiment with the models and fine-tune them to your specific needs.
  • Fine-tuning: Customize models to better suit your unique requirements.
  • Batches: Manage and monitor batch processing tasks.
  • Storage: Access and organize your stored data.
  • Usage: Keep track of your API usage and manage your plan.
  • API Keys: Generate and manage API keys for secure access to OpenAI services.
  • Settings: Adjust your account and project settings.
  • Docs: Access comprehensive documentation to help you understand and utilize the platform effectively.

In the ASSISTANT page, there are four components: the Name section, where you can assign a name to your ASSISTANT, personalizing the interaction; the Instruction section, Provide instructions for the assistant. In this example, the instruction is “You are a helpful assistant.” This sets the tone and behavior for the assistant’s responses.

the Model Selection section,hoose the model that the assistant will use. In this case, “gpt-4o” is selected, indicating the latest and most advanced model available. ; and the Tool section, where you select the tools you want to use with your ASSISTANT, extending its functionalities for a wider range of tasks and more comprehensive assistance

  • File Search: Toggle this option to enable or disable file search capabilities for the assistant.
  • Code Interpreter: Toggle this option to enable or disable code interpretation capabilities, allowing the assistant to execute and understand code.
  • Functions: Add or remove functions that the assistant can use, enhancing its abilities to perform specific tasks.

Model Configuration

  • Response Format: Choose the format in which responses should be returned. In this example, JSON object format is available as an option.
  • Temperature: Adjust the temperature setting to control the randomness of the assistant’s responses. A higher value (up to 1) makes the output more random, while a lower value makes it more deterministic.
  • Top P: Adjust the Top P setting to control the diversity of the generated responses. Setting this to 1 ensures the assistant considers the top percentage of probability mass for generating responses.

Built you first AI Agent with Python

Now, grab your keyboard, put on your coding hat, and let’s dive into the fun-filled world of AI development with Python. this section we will create firt your ai agent.

I am assign GPTs to Economic Analyst.I think there is some problem in the Python code. I still can’t select the “gpt-4o” model.

from openai import OpenAI

OPENAI_KEY= ### You Open API Key
client = OpenAI(api_key= OPENAI_KEY)
assistant = client.beta.assistants.create(
name="Economic Analyst",
instructions="You are Economic Analyst work at one of the most prestigious investment firms in the world. You have a deep knowledge of macroeconomics and market trends.",
model="gpt-4-turbo",
)

Oh! You have first AI Agent. We will try chat with your agent.Using the OpenAI client, create a new thread and store its ID and define the user message

assistant_id = ## assistant ID(thsi first time you can use "assistant.id" )

thread_id = client.beta.threads.create().id

user_message = "Who are yor"

Create some function for pretty printing helper.

def submit_message(assistant_id, thread, user_message):
client.beta.threads.messages.create(
thread_id=
thread.id, role="user", content=user_message
)
return client.beta.threads.runs.create(
thread_id=thread.id,
assistant_id=assistant_id,
)


def get_response(thread):
return client.beta.threads.messages.list(thread_id=thread.id, order="asc")



def create_thread_and_run(user_input):
thread = client.beta.threads.create()
run = submit_message(assistant_id, thread, user_input)
return thread, run


thread1, run1 = create_thread_and_run(
"Who are you"
)
import time

def pretty_print(messages):
print("# Messages")
for m in messages:
print(f"{m.role}: {m.content[0].text.value}")
print()


def wait_on_run(run, thread):
while run.status == "queued" or run.status == "in_progress":
run = client.beta.threads.runs.retrieve(
thread_id=thread.id,
run_id=run.id,
)
time.sleep(0.5)
return run


run1 = wait_on_run(run1, thread1)
pretty_print(get_response(thread1))

Greet!

Tool

A standout feature of the Assistants API is its ability to enhance our Assistants with powerful Tools, such as the Code Interpreter, Retrieval, and custom Functions. Let’s dive into what each of these Tools can do.

Standard Tools include the “Code Interpreter” and “File Search”, and you also have the option to add custom Functions.

 
thread, run = create_thread_and_run(
"Generate the first 20 fibbonaci numbers with code. "
)
run = wait_on_run(run, thread)
pretty_print(get_response(thread))

We can extract Python code by following these steps:

run_steps = client.beta.threads.runs.steps.list(
thread_id=thread.id, run_id=run.id, order="asc"
)

for step in run_steps.data:
step_details = step.step_details
print(json.dumps(show_json(step_details), indent=4))

Retrieval

One of the standout tools in the Assistants API is Retrieval. This feature lets you supercharge your Assistant by uploading files that it can use as a knowledge base to answer questions more effectively. Whether you’re uploading directly from the Dashboard or via the API, you can ensure your Assistant is well-informed and ready to tackle any query with the right information at its fingertips.

# Upload the file
file = client.files.create(
file=open(
"mi-investment-outlook-ce-en.pdf",
"rb",
),
purpose="assistants",
)
# Update Assistant
assistant = client.beta.assistants.update(
assistant_id,
tools=[{"type": "code_interpreter"}, {"type": "retrieval"}],
file_ids=[file.id],
)
show_json(assistant)
thread, run = create_thread_and_run(
"What about US Econmic"
)
run = wait_on_run(run, thread)
pretty_print(get_response(thread))

user: What about US Econmic

assistant: The document describes the state of the U.S. economy as it heads into 2024. Here are some critical insights from the report:

1. **Economic Condition**: The U.S. economy has exhibited resilience in the face of higher interest rates introduced by the Federal Reserve. Despite initial fears of a recession similar to the 1970s stagflation, this did not materialize, and the economic conditions have remained robust, leading to a shift in market narrative toward the possibility of a soft landing.

2. **Inflation and Monetary Policy**: Inflation pressures that were heightened during the pandemic have started to ease. However, the report expresses caution regarding Central Banks declaring victory over inflation too soon. The “long and variable lags” associated with monetary policy transmission suggest that the current economic resilience might not fully capture the future impacts of past policy changes.

3. **Interest Rate Sensitivity**: In the U.S., many households locked in low mortgage rates during the pandemic, which has helped mitigate the direct impact of rising rates. However, there is concern about non-mortgage debt, where interest rates are still variable, and recent data shows increasing delinquencies in auto and credit card loans.

4. **Housing Market**: Elevated mortgage rates have significantly impacted housing activity. High rates are making new loans costly, thus depressing housing-related spending and construction.

5. **Fiscal Policy**: In response to the economic situation and to support the economy, the U.S. has continued with expansionary fiscal policies, including pandemic-related tax moratoriums and large-scale stimulus programs like the CHIPS and Science Act, the JOBS Act, and the Inflation Reduction Act.

Overall, while the U.S. economy is currently showing signs of robustness against the backdrop of high interest rates, there are underlying vulnerabilities, especially related to non-mortgage debt and housing market activity, that could affect future economic stability. The report advises cautious optimism and suggests focusing on high-quality bonds as a preventive measure against potential financial turbulence.

Final Thoughts

Creating a GPT agent with Python involves leveraging the OpenAI Assistants API, which allows developers to build intelligent and interactive agents. The concept of agents, deeply rooted in philosophical thought, pertains to entities capable of deliberate action and decision-making. This guide walks you through the process of developing such agents using the OpenAI API and Python, providing step-by-step instructions for creating functional AI assistants.

Key tools available in the Assistants API include the Code Interpreter, File Search, and custom Functions. These tools enhance the capabilities of the AI, enabling it to handle specific tasks more effectively. By following the tutorial, you will learn how to set up your Python environment, integrate the OpenAI API, and create a chatbot that can engage in meaningful conversations. The guide also covers advanced features like uploading files for the assistant to use as a knowledge base, ensuring your AI is well-informed and capable of handling complex queries.

In the next article, we will build on this foundational knowledge to tackle more complex and exciting tasks. We’ll explore advanced functionalities, such as integrating multiple tools to create more versatile assistants, utilizing sophisticated APIs for dynamic data retrieval, and implementing custom functions to extend the capabilities of your AI agents. By delving into these advanced topics, you’ll learn how to create highly specialized and powerful AI systems that can handle a wide range of applications, from business automation to personalized user interactions. Stay tuned for a deeper dive into the fascinating world of AI development with Python and the OpenAI API.

Ref:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Written by NUTHDANAI WANGPRATHAM

I am a learner and have a multipotential life. You can contact me at nutdnuy@gmail.com

No responses yet

Write a response