# !pip3 install openai -U
Welcome to our comprehensive guide on leveraging function calling in the OpenAI Assistant API. Whether you’re a seasoned developer or a curious beginner, this tutorial is designed to help you understand and implement this powerful feature in your AI projects.
Here’s what we’ll be diving into:
- The basics of function calling in the OpenAI Assistant API
- Steps to create an assistant
- Crafting a message and initiating a thread
- Identifying when a message requires a function call
- Determining which function to call and what arguments to pass
- Retrieving the response from a function call
- Understanding the final response
OpenAI Assistants are equipped with a variety of tools, including retrieval, code interpretation, and function calling. In this guide, we’ll be focusing primarily on the function calling capabilities.
To illustrate these concepts, we’ll walk you through a simple demo. We’ll start by demonstrating a common challenge - reversing a string - and then show you how to overcome this challenge by creating a function that reverses the string and integrating it with the assistant.
Our goal is to provide you with a clear, practical understanding of function calling in the OpenAI Assistant API, empowering you to create more dynamic and interactive AI applications. Let’s get started!
In general, assistants can use tools such as retrrieval, code interpreter, and function calling.
In this tutorial we focus more on function calling capabilities of assistants.
We create a simple demo that shows the failure of reversing a string and then we create a function that reverses the string and connect it with the assistant.
# dictionary print indentatio
import json
import os
from dotenv import load_dotenv
import openai
from openai import OpenAI
= OpenAI()
client
load_dotenv()# openai key
= os.getenv("OPENAI_API_KEY")
OPENAI_API_KEY = OPENAI_API_KEY
openai.api_key from IPython.display import display, Markdown
# openai version
openai.__version__
'1.6.1'
= client.chat.completions.create(
response ="gpt-4-1106-preview",
model=[
messages"role": "user", "content": "reverse the string openaichatgpt"},
{
],=0.3,
temperature=1,
seed )
0].message.content)) display(Markdown(response.choices[
To reverse the string “openaichatgpt”, you would simply reverse the order of the characters to get “tpgtahciapeneo”.
"tpgtahciapeneo" == "openaichatgpt"[::-1]
False
Large Language Models use tokens to split text into smaller pieces, and reversing a string is not a usual data that is has seen during training, so it is not able to predict it correctly.
We can fix this by creating a function that will reverse the string, and use the model to ask us to call the function and get results and pass it to the model.
def reverse_string(string):
return string[::-1]
Creating an Assistant
# function_json for reverse_string
= {'type':'function',
function_json 'function':{
'name': 'reverse_string',
'parameters':{
"type":"object",
"properties":{
"string": {'type':'string','description':"A single word"},
},'required' : ["string"]
}
} }
= {
available_functions "reverse_string": reverse_string
}
from openai import OpenAI
= OpenAI() client
= client.beta.assistants.create(
assistant ="Python Tutor",
name="You are a personal python tutor.",
instructions=[function_json],
tools="gpt-4-1106-preview"
model )
assistant
Assistant(id='asst_UQEBrB5fuKnzx472Sf5qWYdH', created_at=1704457106, description=None, file_ids=[], instructions='You are a personal python tutor.', metadata={}, model='gpt-4-1106-preview', name='Python Tutor', object='assistant', tools=[ToolFunction(function=FunctionDefinition(name='reverse_string', description=None, parameters={'type': 'object', 'properties': {'string': {'type': 'string', 'description': 'A single word'}}, 'required': ['string']}), type='function')])
print(json.dumps(assistant.model_dump(), indent=4))
{
"id": "asst_UQEBrB5fuKnzx472Sf5qWYdH",
"created_at": 1704457106,
"description": null,
"file_ids": [],
"instructions": "You are a personal python tutor.",
"metadata": {},
"model": "gpt-4-1106-preview",
"name": "Python Tutor",
"object": "assistant",
"tools": [
{
"function": {
"name": "reverse_string",
"description": null,
"parameters": {
"type": "object",
"properties": {
"string": {
"type": "string",
"description": "A single word"
}
},
"required": [
"string"
]
}
},
"type": "function"
}
]
}
type(assistant)
openai.types.beta.assistant.Assistant
Thread
= client.beta.threads.create() thread
thread.model_dump()
{'id': 'thread_3fT59LTUrodHJPjBQYsIYm6F',
'created_at': 1704457106,
'metadata': {},
'object': 'thread'}
thread
Thread(id='thread_3fT59LTUrodHJPjBQYsIYm6F', created_at=1704457106, metadata={}, object='thread')
Add a Message to a Thread
= client.beta.threads.messages.create(
message =thread.id,
thread_id="user",
role="what are different loops in python?"
content )
message
ThreadMessage(id='msg_UDx8nMLlKxvriXAEBeW0AJ9f', assistant_id=None, content=[MessageContentText(text=Text(annotations=[], value='what are different loops in python?'), type='text')], created_at=1704457107, file_ids=[], metadata={}, object='thread.message', role='user', run_id=None, thread_id='thread_3fT59LTUrodHJPjBQYsIYm6F')
message.model_dump()
{'id': 'msg_UDx8nMLlKxvriXAEBeW0AJ9f',
'assistant_id': None,
'content': [{'text': {'annotations': [],
'value': 'what are different loops in python?'},
'type': 'text'}],
'created_at': 1704457107,
'file_ids': [],
'metadata': {},
'object': 'thread.message',
'role': 'user',
'run_id': None,
'thread_id': 'thread_3fT59LTUrodHJPjBQYsIYm6F'}
= client.beta.threads.messages.list(thread_id=thread.id)
thread_messages thread_messages.data
[ThreadMessage(id='msg_UDx8nMLlKxvriXAEBeW0AJ9f', assistant_id=None, content=[MessageContentText(text=Text(annotations=[], value='what are different loops in python?'), type='text')], created_at=1704457107, file_ids=[], metadata={}, object='thread.message', role='user', run_id=None, thread_id='thread_3fT59LTUrodHJPjBQYsIYm6F')]
thread_messages.model_dump()
{'data': [{'id': 'msg_UDx8nMLlKxvriXAEBeW0AJ9f',
'assistant_id': None,
'content': [{'text': {'annotations': [],
'value': 'what are different loops in python?'},
'type': 'text'}],
'created_at': 1704457107,
'file_ids': [],
'metadata': {},
'object': 'thread.message',
'role': 'user',
'run_id': None,
'thread_id': 'thread_3fT59LTUrodHJPjBQYsIYm6F'}],
'object': 'list',
'first_id': 'msg_UDx8nMLlKxvriXAEBeW0AJ9f',
'last_id': 'msg_UDx8nMLlKxvriXAEBeW0AJ9f',
'has_more': False}
= client.beta.threads.runs.create(
run =thread.id,
thread_id=assistant.id,
assistant_id )
print(json.dumps(run.model_dump(), indent=4))
{
"id": "run_BLZnD60Vl7wePLUsdmUFR5zd",
"assistant_id": "asst_UQEBrB5fuKnzx472Sf5qWYdH",
"cancelled_at": null,
"completed_at": null,
"created_at": 1704457108,
"expires_at": 1704457708,
"failed_at": null,
"file_ids": [],
"instructions": "You are a personal python tutor.",
"last_error": null,
"metadata": {},
"model": "gpt-4-1106-preview",
"object": "thread.run",
"required_action": null,
"started_at": null,
"status": "queued",
"thread_id": "thread_3fT59LTUrodHJPjBQYsIYm6F",
"tools": [
{
"function": {
"name": "reverse_string",
"description": null,
"parameters": {
"type": "object",
"properties": {
"string": {
"type": "string",
"description": "A single word"
}
},
"required": [
"string"
]
}
},
"type": "function"
}
]
}
= client.beta.threads.runs.retrieve(
run =thread.id,
thread_id=run.id
run_id )
print(json.dumps(run.model_dump(), indent=4))
{
"id": "run_BLZnD60Vl7wePLUsdmUFR5zd",
"assistant_id": "asst_UQEBrB5fuKnzx472Sf5qWYdH",
"cancelled_at": null,
"completed_at": null,
"created_at": 1704457108,
"expires_at": 1704457708,
"failed_at": null,
"file_ids": [],
"instructions": "You are a personal python tutor.",
"last_error": null,
"metadata": {},
"model": "gpt-4-1106-preview",
"object": "thread.run",
"required_action": null,
"started_at": 1704457108,
"status": "in_progress",
"thread_id": "thread_3fT59LTUrodHJPjBQYsIYm6F",
"tools": [
{
"function": {
"name": "reverse_string",
"description": null,
"parameters": {
"type": "object",
"properties": {
"string": {
"type": "string",
"description": "A single word"
}
},
"required": [
"string"
]
}
},
"type": "function"
}
]
}
run
Run(id='run_BLZnD60Vl7wePLUsdmUFR5zd', assistant_id='asst_UQEBrB5fuKnzx472Sf5qWYdH', cancelled_at=None, completed_at=None, created_at=1704457108, expires_at=1704457708, failed_at=None, file_ids=[], instructions='You are a personal python tutor.', last_error=None, metadata={}, model='gpt-4-1106-preview', object='thread.run', required_action=None, started_at=1704457108, status='in_progress', thread_id='thread_3fT59LTUrodHJPjBQYsIYm6F', tools=[ToolAssistantToolsFunction(function=FunctionDefinition(name='reverse_string', description=None, parameters={'type': 'object', 'properties': {'string': {'type': 'string', 'description': 'A single word'}}, 'required': ['string']}), type='function')])
run.status
'in_progress'
import time
while run.status == "queued" or run.status == "in_progress":
= client.beta.threads.runs.retrieve(
run =thread.id,
thread_id=run.id
run_id
)print(run.status)
2)
time.sleep(
in_progress
in_progress
in_progress
in_progress
in_progress
in_progress
in_progress
in_progress
in_progress
in_progress
in_progress
in_progress
in_progress
completed
run
Run(id='run_BLZnD60Vl7wePLUsdmUFR5zd', assistant_id='asst_UQEBrB5fuKnzx472Sf5qWYdH', cancelled_at=None, completed_at=1704457140, created_at=1704457108, expires_at=None, failed_at=None, file_ids=[], instructions='You are a personal python tutor.', last_error=None, metadata={}, model='gpt-4-1106-preview', object='thread.run', required_action=None, started_at=1704457108, status='completed', thread_id='thread_3fT59LTUrodHJPjBQYsIYm6F', tools=[ToolAssistantToolsFunction(function=FunctionDefinition(name='reverse_string', description=None, parameters={'type': 'object', 'properties': {'string': {'type': 'string', 'description': 'A single word'}}, 'required': ['string']}), type='function')])
= client.beta.threads.messages.list(
messages =thread.id
thread_id
)
messages
SyncCursorPage[ThreadMessage](data=[ThreadMessage(id='msg_a5FW3oicgn271ztQwcIa6kQ6', assistant_id='asst_UQEBrB5fuKnzx472Sf5qWYdH', content=[MessageContentText(text=Text(annotations=[], value='In Python, there are two primary types of loops that allow you to execute a block of code repeatedly:\n\n1. `for` Loop: This loop is used for iterating over a sequence (which could be a list, tuple, dictionary, set, or string) with the ability to execute a block of code for each item in the sequence. An example of a `for` loop:\n\n```python\nfor item in ["apple", "banana", "cherry"]:\n print(item)\n```\n\n2. `while` Loop: This loop repeatedly executes the target statement(s) as long as the given condition is true. The condition is evaluated before executing the body of the loop. Here\'s an example of a `while` loop:\n\n```python\ncount = 0\nwhile count < 5:\n print(count)\n count += 1\n```\n\nPython also provides some loop control statements that can be used within these loops:\n\n- `break`: Terminates the loop and transfers execution to the statement immediately following the loop.\n- `continue`: Skips the remaining part of the loop for the current iteration and moves to the next iteration.\n- `else`: An optional clause associated with loops that is executed if the loop completes normally (i.e., not terminated by a `break` statement).\n\nHere\'s an example of using `break`, `continue`, and `else` with a `for` loop:\n\n```python\nfor num in range(2, 10):\n if num % 2 == 0:\n print("Found an even number", num)\n continue\n print("Found a number", num)\nelse:\n print("The loop is completed without a break statement.")\n```\n\nAnd an example using `while` loop:\n\n```python\ncount = 1\nwhile count < 10:\n if count == 5:\n break\n print(count)\n count += 1\nelse:\n print("Reached the value of 5 and stopped the loop with a break statement.")\n```\n\nAdditionally, Python allows the use of nested loops (a loop inside another loop), which can be useful for more complex iteration scenarios. However, it\'s important to use them judiciously as they can lead to high computational complexity, especially with large datasets.'), type='text')], created_at=1704457109, file_ids=[], metadata={}, object='thread.message', role='assistant', run_id='run_BLZnD60Vl7wePLUsdmUFR5zd', thread_id='thread_3fT59LTUrodHJPjBQYsIYm6F'), ThreadMessage(id='msg_UDx8nMLlKxvriXAEBeW0AJ9f', assistant_id=None, content=[MessageContentText(text=Text(annotations=[], value='what are different loops in python?'), type='text')], created_at=1704457107, file_ids=[], metadata={}, object='thread.message', role='user', run_id=None, thread_id='thread_3fT59LTUrodHJPjBQYsIYm6F')], object='list', first_id='msg_a5FW3oicgn271ztQwcIa6kQ6', last_id='msg_UDx8nMLlKxvriXAEBeW0AJ9f', has_more=False)
print(json.dumps(messages.model_dump(), indent=4))
{
"data": [
{
"id": "msg_a5FW3oicgn271ztQwcIa6kQ6",
"assistant_id": "asst_UQEBrB5fuKnzx472Sf5qWYdH",
"content": [
{
"text": {
"annotations": [],
"value": "In Python, there are two primary types of loops that allow you to execute a block of code repeatedly:\n\n1. `for` Loop: This loop is used for iterating over a sequence (which could be a list, tuple, dictionary, set, or string) with the ability to execute a block of code for each item in the sequence. An example of a `for` loop:\n\n```python\nfor item in [\"apple\", \"banana\", \"cherry\"]:\n print(item)\n```\n\n2. `while` Loop: This loop repeatedly executes the target statement(s) as long as the given condition is true. The condition is evaluated before executing the body of the loop. Here's an example of a `while` loop:\n\n```python\ncount = 0\nwhile count < 5:\n print(count)\n count += 1\n```\n\nPython also provides some loop control statements that can be used within these loops:\n\n- `break`: Terminates the loop and transfers execution to the statement immediately following the loop.\n- `continue`: Skips the remaining part of the loop for the current iteration and moves to the next iteration.\n- `else`: An optional clause associated with loops that is executed if the loop completes normally (i.e., not terminated by a `break` statement).\n\nHere's an example of using `break`, `continue`, and `else` with a `for` loop:\n\n```python\nfor num in range(2, 10):\n if num % 2 == 0:\n print(\"Found an even number\", num)\n continue\n print(\"Found a number\", num)\nelse:\n print(\"The loop is completed without a break statement.\")\n```\n\nAnd an example using `while` loop:\n\n```python\ncount = 1\nwhile count < 10:\n if count == 5:\n break\n print(count)\n count += 1\nelse:\n print(\"Reached the value of 5 and stopped the loop with a break statement.\")\n```\n\nAdditionally, Python allows the use of nested loops (a loop inside another loop), which can be useful for more complex iteration scenarios. However, it's important to use them judiciously as they can lead to high computational complexity, especially with large datasets."
},
"type": "text"
}
],
"created_at": 1704457109,
"file_ids": [],
"metadata": {},
"object": "thread.message",
"role": "assistant",
"run_id": "run_BLZnD60Vl7wePLUsdmUFR5zd",
"thread_id": "thread_3fT59LTUrodHJPjBQYsIYm6F"
},
{
"id": "msg_UDx8nMLlKxvriXAEBeW0AJ9f",
"assistant_id": null,
"content": [
{
"text": {
"annotations": [],
"value": "what are different loops in python?"
},
"type": "text"
}
],
"created_at": 1704457107,
"file_ids": [],
"metadata": {},
"object": "thread.message",
"role": "user",
"run_id": null,
"thread_id": "thread_3fT59LTUrodHJPjBQYsIYm6F"
}
],
"object": "list",
"first_id": "msg_a5FW3oicgn271ztQwcIa6kQ6",
"last_id": "msg_UDx8nMLlKxvriXAEBeW0AJ9f",
"has_more": false
}
0].content[0].text.value)) display(Markdown(messages.data[
In Python, there are two primary types of loops that allow you to execute a block of code repeatedly:
for
Loop: This loop is used for iterating over a sequence (which could be a list, tuple, dictionary, set, or string) with the ability to execute a block of code for each item in the sequence. An example of afor
loop:
for item in ["apple", "banana", "cherry"]:
print(item)
while
Loop: This loop repeatedly executes the target statement(s) as long as the given condition is true. The condition is evaluated before executing the body of the loop. Here’s an example of awhile
loop:
= 0
count while count < 5:
print(count)
+= 1 count
Python also provides some loop control statements that can be used within these loops:
break
: Terminates the loop and transfers execution to the statement immediately following the loop.continue
: Skips the remaining part of the loop for the current iteration and moves to the next iteration.else
: An optional clause associated with loops that is executed if the loop completes normally (i.e., not terminated by abreak
statement).
Here’s an example of using break
, continue
, and else
with a for
loop:
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
else:
print("The loop is completed without a break statement.")
And an example using while
loop:
= 1
count while count < 10:
if count == 5:
break
print(count)
+= 1
count else:
print("Reached the value of 5 and stopped the loop with a break statement.")
Additionally, Python allows the use of nested loops (a loop inside another loop), which can be useful for more complex iteration scenarios. However, it’s important to use them judiciously as they can lead to high computational complexity, especially with large datasets.
# new message
= client.beta.threads.messages.create(
message =thread.id,
thread_id="user",
role="what's the reverse of the string openaichatgpt?"
content )
# new run
= client.beta.threads.runs.create(
run =thread.id,
thread_id=assistant.id,
assistant_id
)
# wait for run to complete
while run.status == "queued" or run.status == "in_progress":
= client.beta.threads.runs.retrieve(
run =thread.id,
thread_id=run.id
run_id
)print(run.status)
2) time.sleep(
in_progress
in_progress
requires_action
run.status
'requires_action'
print(json.dumps(run.model_dump(), indent=4))
{
"id": "run_dmH9mQUYjLLQJEYuXZQZJOHH",
"assistant_id": "asst_UQEBrB5fuKnzx472Sf5qWYdH",
"cancelled_at": null,
"completed_at": null,
"created_at": 1704457145,
"expires_at": 1704457745,
"failed_at": null,
"file_ids": [],
"instructions": "You are a personal python tutor.",
"last_error": null,
"metadata": {},
"model": "gpt-4-1106-preview",
"object": "thread.run",
"required_action": {
"submit_tool_outputs": {
"tool_calls": [
{
"id": "call_aQzOoDu3V00J5lkG6zVNtdqc",
"function": {
"arguments": "{\"string\":\"openaichatgpt\"}",
"name": "reverse_string"
},
"type": "function"
}
]
},
"type": "submit_tool_outputs"
},
"started_at": 1704457145,
"status": "requires_action",
"thread_id": "thread_3fT59LTUrodHJPjBQYsIYm6F",
"tools": [
{
"function": {
"name": "reverse_string",
"description": null,
"parameters": {
"type": "object",
"properties": {
"string": {
"type": "string",
"description": "A single word"
}
},
"required": [
"string"
]
}
},
"type": "function"
}
]
}
run.required_action
RequiredAction(submit_tool_outputs=RequiredActionSubmitToolOutputs(tool_calls=[RequiredActionFunctionToolCall(id='call_aQzOoDu3V00J5lkG6zVNtdqc', function=Function(arguments='{"string":"openaichatgpt"}', name='reverse_string'), type='function')]), type='submit_tool_outputs')
if run.status == "requires_action":
= run.required_action.submit_tool_outputs.tool_calls[0]
tool_call print("Tool call: ", tool_call)
= tool_call.function.name
function_name print("Function name: ", function_name)
= json.loads(tool_call.function.arguments)
arguments print("Function arguments: ", arguments)
Tool call: RequiredActionFunctionToolCall(id='call_aQzOoDu3V00J5lkG6zVNtdqc', function=Function(arguments='{"string":"openaichatgpt"}', name='reverse_string'), type='function')
Function name: reverse_string
Function arguments: {'string': 'openaichatgpt'}
# call the function
if run.status == "requires_action":
= run.required_action.submit_tool_outputs.tool_calls[0]
tool_call = tool_call.function.name
function_name = json.loads(tool_call.function.arguments)
arguments = available_functions[function_name]
function = function(**arguments)
output print("Function output: ", output)
Function output: tpgtahcianepo
print(json.dumps(run.model_dump(), indent=4))
{
"id": "run_dmH9mQUYjLLQJEYuXZQZJOHH",
"assistant_id": "asst_UQEBrB5fuKnzx472Sf5qWYdH",
"cancelled_at": null,
"completed_at": null,
"created_at": 1704457145,
"expires_at": 1704457745,
"failed_at": null,
"file_ids": [],
"instructions": "You are a personal python tutor.",
"last_error": null,
"metadata": {},
"model": "gpt-4-1106-preview",
"object": "thread.run",
"required_action": {
"submit_tool_outputs": {
"tool_calls": [
{
"id": "call_aQzOoDu3V00J5lkG6zVNtdqc",
"function": {
"arguments": "{\"string\":\"openaichatgpt\"}",
"name": "reverse_string"
},
"type": "function"
}
]
},
"type": "submit_tool_outputs"
},
"started_at": 1704457145,
"status": "requires_action",
"thread_id": "thread_3fT59LTUrodHJPjBQYsIYm6F",
"tools": [
{
"function": {
"name": "reverse_string",
"description": null,
"parameters": {
"type": "object",
"properties": {
"string": {
"type": "string",
"description": "A single word"
}
},
"required": [
"string"
]
}
},
"type": "function"
}
]
}
Let the Model Know about the function outputs
= client.beta.threads.runs.submit_tool_outputs(
run =thread.id,
thread_id=run.id,
run_id=[{"tool_call_id": tool_call.id, "output": json.dumps(output)}],
tool_outputs )
while run.status == "queued" or run.status == "in_progress":
= client.beta.threads.runs.retrieve(
run =thread.id,
thread_id=run.id
run_id
)print(run.status)
2) time.sleep(
in_progress
completed
Retrieve the message from history and display the output
= client.beta.threads.messages.list(
messages =thread.id
thread_id )
print(json.dumps(messages.model_dump(), indent=4))
{
"data": [
{
"id": "msg_vp29v6UA7Amr7isw4LdGNhcW",
"assistant_id": "asst_UQEBrB5fuKnzx472Sf5qWYdH",
"content": [
{
"text": {
"annotations": [],
"value": "The reverse of the string \"openaichatgpt\" is \"tpgtahcianepo\"."
},
"type": "text"
}
],
"created_at": 1704457154,
"file_ids": [],
"metadata": {},
"object": "thread.message",
"role": "assistant",
"run_id": "run_dmH9mQUYjLLQJEYuXZQZJOHH",
"thread_id": "thread_3fT59LTUrodHJPjBQYsIYm6F"
},
{
"id": "msg_QPbWzZkoRFveMIRPWtvREz0s",
"assistant_id": null,
"content": [
{
"text": {
"annotations": [],
"value": "what's the reverse of the string openaichatgpt?"
},
"type": "text"
}
],
"created_at": 1704457145,
"file_ids": [],
"metadata": {},
"object": "thread.message",
"role": "user",
"run_id": null,
"thread_id": "thread_3fT59LTUrodHJPjBQYsIYm6F"
},
{
"id": "msg_a5FW3oicgn271ztQwcIa6kQ6",
"assistant_id": "asst_UQEBrB5fuKnzx472Sf5qWYdH",
"content": [
{
"text": {
"annotations": [],
"value": "In Python, there are two primary types of loops that allow you to execute a block of code repeatedly:\n\n1. `for` Loop: This loop is used for iterating over a sequence (which could be a list, tuple, dictionary, set, or string) with the ability to execute a block of code for each item in the sequence. An example of a `for` loop:\n\n```python\nfor item in [\"apple\", \"banana\", \"cherry\"]:\n print(item)\n```\n\n2. `while` Loop: This loop repeatedly executes the target statement(s) as long as the given condition is true. The condition is evaluated before executing the body of the loop. Here's an example of a `while` loop:\n\n```python\ncount = 0\nwhile count < 5:\n print(count)\n count += 1\n```\n\nPython also provides some loop control statements that can be used within these loops:\n\n- `break`: Terminates the loop and transfers execution to the statement immediately following the loop.\n- `continue`: Skips the remaining part of the loop for the current iteration and moves to the next iteration.\n- `else`: An optional clause associated with loops that is executed if the loop completes normally (i.e., not terminated by a `break` statement).\n\nHere's an example of using `break`, `continue`, and `else` with a `for` loop:\n\n```python\nfor num in range(2, 10):\n if num % 2 == 0:\n print(\"Found an even number\", num)\n continue\n print(\"Found a number\", num)\nelse:\n print(\"The loop is completed without a break statement.\")\n```\n\nAnd an example using `while` loop:\n\n```python\ncount = 1\nwhile count < 10:\n if count == 5:\n break\n print(count)\n count += 1\nelse:\n print(\"Reached the value of 5 and stopped the loop with a break statement.\")\n```\n\nAdditionally, Python allows the use of nested loops (a loop inside another loop), which can be useful for more complex iteration scenarios. However, it's important to use them judiciously as they can lead to high computational complexity, especially with large datasets."
},
"type": "text"
}
],
"created_at": 1704457109,
"file_ids": [],
"metadata": {},
"object": "thread.message",
"role": "assistant",
"run_id": "run_BLZnD60Vl7wePLUsdmUFR5zd",
"thread_id": "thread_3fT59LTUrodHJPjBQYsIYm6F"
},
{
"id": "msg_UDx8nMLlKxvriXAEBeW0AJ9f",
"assistant_id": null,
"content": [
{
"text": {
"annotations": [],
"value": "what are different loops in python?"
},
"type": "text"
}
],
"created_at": 1704457107,
"file_ids": [],
"metadata": {},
"object": "thread.message",
"role": "user",
"run_id": null,
"thread_id": "thread_3fT59LTUrodHJPjBQYsIYm6F"
}
],
"object": "list",
"first_id": "msg_vp29v6UA7Amr7isw4LdGNhcW",
"last_id": "msg_UDx8nMLlKxvriXAEBeW0AJ9f",
"has_more": false
}
for message in messages.data:
0].text.value))
display(Markdown(message.content[print("*" * 80)
The reverse of the string “openaichatgpt” is “tpgtahcianepo”.
********************************************************************************
********************************************************************************
********************************************************************************
********************************************************************************
what’s the reverse of the string openaichatgpt?
In Python, there are two primary types of loops that allow you to execute a block of code repeatedly:
for
Loop: This loop is used for iterating over a sequence (which could be a list, tuple, dictionary, set, or string) with the ability to execute a block of code for each item in the sequence. An example of afor
loop:
for item in ["apple", "banana", "cherry"]:
print(item)
while
Loop: This loop repeatedly executes the target statement(s) as long as the given condition is true. The condition is evaluated before executing the body of the loop. Here’s an example of awhile
loop:
= 0
count while count < 5:
print(count)
+= 1 count
Python also provides some loop control statements that can be used within these loops:
break
: Terminates the loop and transfers execution to the statement immediately following the loop.continue
: Skips the remaining part of the loop for the current iteration and moves to the next iteration.else
: An optional clause associated with loops that is executed if the loop completes normally (i.e., not terminated by abreak
statement).
Here’s an example of using break
, continue
, and else
with a for
loop:
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print("Found a number", num)
else:
print("The loop is completed without a break statement.")
And an example using while
loop:
= 1
count while count < 10:
if count == 5:
break
print(count)
+= 1
count else:
print("Reached the value of 5 and stopped the loop with a break statement.")
Additionally, Python allows the use of nested loops (a loop inside another loop), which can be useful for more complex iteration scenarios. However, it’s important to use them judiciously as they can lead to high computational complexity, especially with large datasets.
what are different loops in python?
Delete the Assistant
= client.beta.assistants.delete(assistant_id=assistant.id)
response print(response)
AssistantDeleted(id='asst_UQEBrB5fuKnzx472Sf5qWYdH', deleted=True, object='assistant.deleted')