update prompt

This commit is contained in:
heroding77
2024-01-24 17:17:36 +08:00
parent 3e8bd07d19
commit 324efed221
21 changed files with 280 additions and 106 deletions

1
.gitignore vendored
View File

@@ -4,7 +4,6 @@ Auto-GPT/
Agents/
utils/
/examples/log/*
working_dir/*.log
.vs/

View File

@@ -10,11 +10,11 @@ class GAIALoader:
assert os.path.exists(cache_dir), f"Cache directory {cache_dir} does not exist."
self.cache_dir = cache_dir
try:
self.dataset = load_dataset("gaia-benchmark/GAIA", "2023_level1", cache_dir=self.cache_dir)
self.dataset = load_dataset("gaia-benchmark/GAIA", "2023_level2", cache_dir=self.cache_dir)
except Exception as e:
raise Exception(f"Failed to load GAIA dataset: {e}")
else:
self.dataset = load_dataset("gaia-benchmark/GAIA", "2023_level1")
self.dataset = load_dataset("gaia-benchmark/GAIA", "2023_level2")
def get_data_by_task_id(self, task_id, type):
@@ -33,9 +33,9 @@ def main():
parser.add_argument('--config_path', type=str, default='config.json', help='openAI config file path')
parser.add_argument('--query', type=str, default=None, help='user query')
parser.add_argument('--query_file_path', type=str, default='', help='user query file path')
parser.add_argument('--task_id', type=str, default="66bd1b1c-443b-4b4e-a108-0fa06527dd62", help='GAIA dataset task_id')
parser.add_argument('--task_id', type=str, default="6178671d-6f80-4e0d-9672-54afaf7b527b", help='GAIA dataset task_id')
parser.add_argument('--cache_dir', type=str, default=None, help='GAIA dataset cache dir path')
parser.add_argument('--logging_filedir', type=str, default='log/test_level1', help='GAIA dataset cache dir path')
parser.add_argument('--logging_filedir', type=str, default='log/test_level2', help='GAIA dataset cache dir path')
args = parser.parse_args()
task_id = args.task_id

View File

@@ -0,0 +1 @@
Calculate the distances between each pair of adjacent site using latitude and longitude.

View File

@@ -0,0 +1 @@
Execute the Python code read from a file and get the original output.

View File

@@ -0,0 +1 @@
Read the full text content of a specified text file.

View File

@@ -0,0 +1 @@
Read the full text content of the specified XML file.

View File

@@ -54,5 +54,21 @@
"read_json_file": {
"code": "\nfrom jarvis.action.base_action import BaseAction\nimport json\nimport os\n\nclass read_json_file(BaseAction):\n def __init__(self):\n self._description = \"Read the content of the specified JSON file.\"\n\n def __call__(self, json_file_path, *args, **kwargs):\n \"\"\"\n Read the content of the specified JSON file and return its content.\n\n Args:\n json_file_path (str): The absolute path to the JSON file to be read.\n\n Returns:\n dict: The content of the JSON file.\n \"\"\"\n try:\n # Ensure the JSON file exists\n if not os.path.isfile(json_file_path):\n print(f\"The JSON file {json_file_path} does not exist.\")\n return\n\n # Read the JSON file\n with open(json_file_path, 'r', encoding='utf-8') as file:\n content = json.load(file)\n\n print(f\"Task execution complete. Content of the JSON file {json_file_path} read successfully.\")\n return content\n except FileNotFoundError:\n print(f\"The JSON file {json_file_path} does not exist.\")\n except json.JSONDecodeError as e:\n print(f\"An error occurred while parsing the JSON file {json_file_path}: {e}\")\n except Exception as e:\n print(f\"An unexpected error occurred: {e}\")\n\n# Example of how to use the class (this should be in the comments):\n# reader = read_json_file()\n# content = reader(json_file_path='/home/heroding/.cache/huggingface/datasets/downloads/bb3eef7d0e0a0283bff6e45060ed0fc57055c2e324d7efc7dc322d5055d1e2da.json')\n",
"description": "Read the content of the specified JSON file."
},
"calculate_adjacent_distances": {
"code": "from jarvis.action.base_action import BaseAction\nimport pandas as pd\nimport os\nfrom geopy.distance import geodesic\n\nclass calculate_adjacent_distances(BaseAction):\n def __init__(self):\n self._description = \"Calculate the distances between each pair of adjacent site using latitude and longitude.\"\n\n def __call__(self, stations, *args, **kwargs):\n \"\"\"\n Calculate the distances between each pair of adjacent stations using the geopy library.\n\n Args:\n stations - A list of tuples, where each tuple contains the name of the station and its coordinates.\n The format of each tuple is (station_name, (latitude, longitude)).\n\n \n Returns:\n A list of strings, each describing the distance between a pair of adjacent stations.\n Each string is formatted as \"Distance between [Station1] and [Station2]: [distance] km\".\n\n \"\"\"\n distances = []\n for i in range(len(stations) - 1):\n name1, coords1 = stations[i]\n name2, coords2 = stations[i + 1]\n distance = geodesic(coords1, coords2).kilometers # Calculating distance using geodesic method\n distances.append(f\"Distance between {name1} and {name2}: {distance:.2f} km\")\n return distances\n\n# Example of how to use the class (this should be in the comments):\n# calculator = calculate_distances()\n# stations = [\n# ('Alpha', (40.757707, -73.997332)),\n# ('Beta', (40.817108, -73.958537)),\n# # ... add other stations here\n# ]\n# distances = calculator(stations)",
"description": "Calculate the distances between each pair of adjacent site using latitude and longitude."
},
"execute_original_python_code": {
"code": "from jarvis.action.base_action import BaseAction\nimport subprocess\nimport os\nimport sys\nimport tempfile\n\nclass execute_original_python_code(BaseAction):\n def __init__(self):\n self._description = \"Execute the Python code read from a file and get the original output.\"\n\n def __call__(self, python_code, working_dir=None, *args, **kwargs):\n \"\"\"\n Execute the provided Python code and print the output.\n\n Args:\n python_code (str): The Python code to be executed.\n working_dir (str, optional): The working directory where the code should be executed. Defaults to the current working directory.\n\n Returns:\n The result of the Code execution.\n \"\"\"\n # Set the working directory if provided, otherwise use the current working directory\n if working_dir:\n os.chdir(working_dir)\n else:\n working_dir = os.getcwd()\n\n # Create a temporary file to store the Python code\n with tempfile.NamedTemporaryFile(mode='w+', suffix='.py', dir=working_dir, delete=False) as temp_file:\n temp_file_name = temp_file.name\n temp_file.write(python_code)\n temp_file.flush()\n\n # Execute the Python code using the Python interpreter\n try:\n result = subprocess.run([sys.executable, temp_file_name], capture_output=True, text=True, check=True)\n return result.stdout.strip()\n except subprocess.CalledProcessError as e:\n print(f\"An error occurred while executing the Python code: {e.stderr}\", file=sys.stderr)\n finally:\n # Remove the temporary file\n os.unlink(temp_file_name)\n\n# Example of how to use the class (this should be in the comments):\n# executor = execute_original_python_code()\n# executor(python_code=read_python_code_return_val[0], working_dir='/home/heroding/\u684c\u9762/Jarvis/working_dir')",
"description": "Execute the Python code read from a file and get the original output."
},
"read_text_file": {
"code": "\nfrom jarvis.action.base_action import BaseAction\nimport os\n\nclass read_text_file(BaseAction):\n def __init__(self):\n self._description = \"Read the full text content of a specified text file.\"\n\n def __call__(self, file_path, *args, **kwargs):\n \"\"\"\n Read the content of the specified text file and return its content.\n\n Args:\n file_path (str): The absolute path to the text file to be read.\n\n Returns:\n str: The content of the text file, or None if an error occurs.\n \"\"\"\n try:\n with open(file_path, 'r', encoding='utf-8') as file:\n content = file.read()\n print(f\"Task execution complete. Content of the file {file_path} read successfully.\")\n return content\n except FileNotFoundError:\n print(f\"The file {file_path} does not exist.\")\n return None\n except Exception as e:\n print(f\"An error occurred while reading the file {file_path}: {e}\")\n return None\n\n# Example of how to use the class (this should be in the comments):\n# reader = read_text_file()\n# content = reader(file_path='/home/heroding/.cache/huggingface/datasets/downloads/90d142b33359cd5fba1aa1ac9be83cd48d112baf51a675fc08e26d5b1d5c0402.txt')\n",
"description": "Read the full text content of a specified text file."
},
"read_xml_file": {
"code": "\nfrom jarvis.action.base_action import BaseAction\nimport os\nimport xml.etree.ElementTree as ET\n\nclass read_xml_file(BaseAction):\n def __init__(self):\n self._description = \"Read the full text content of the specified XML file.\"\n\n def __call__(self, file_path, *args, **kwargs):\n \"\"\"\n Read the content of the specified XML file and return its content.\n\n Args:\n file_path (str): The absolute path to the XML file to be read.\n\n Returns:\n str: The content of the XML file, or None if an error occurs.\n \"\"\"\n try:\n # Change the current working directory to the directory of the file\n os.chdir(os.path.dirname(file_path))\n \n # Parse the XML file\n tree = ET.parse(os.path.basename(file_path))\n root = tree.getroot()\n \n # Convert the XML tree to a string\n content = ET.tostring(root, encoding='unicode')\n \n print(f\"Task execution complete. Content of the XML file {file_path} read successfully.\")\n return content\n except FileNotFoundError:\n print(f\"The XML file {file_path} does not exist.\")\n return None\n except ET.ParseError as e:\n print(f\"An error occurred while parsing the XML file {file_path}: {e}\")\n return None\n except Exception as e:\n print(f\"An error occurred while reading the XML file {file_path}: {e}\")\n return None\n\n# Example of how to use the class (this should be in the comments):\n# reader = read_xml_file()\n# content = reader(file_path='/home/heroding/.cache/huggingface/datasets/downloads/4b570797236b2208d14d90be2da93e5c6ce24b1e73d43d9632136e43effa2ad1.xml')\n",
"description": "Read the full text content of the specified XML file."
}
}

View File

@@ -0,0 +1,7 @@
Read the content of the specified text file and return its content.
Args:
file_path (str): The absolute path to the text file to be read.
Returns:
str: The content of the text file, or None if an error occurs.

View File

@@ -0,0 +1,7 @@
Read the content of the specified XML file and return its content.
Args:
file_path (str): The absolute path to the XML file to be read.
Returns:
str: The content of the XML file, or None if an error occurs.

View File

@@ -0,0 +1,39 @@
from jarvis.action.base_action import BaseAction
import pandas as pd
import os
from geopy.distance import geodesic
class calculate_adjacent_distances(BaseAction):
def __init__(self):
self._description = "Calculate the distances between each pair of adjacent site using latitude and longitude."
def __call__(self, stations, *args, **kwargs):
"""
Calculate the distances between each pair of adjacent stations using the geopy library.
Args:
stations - A list of tuples, where each tuple contains the name of the station and its coordinates.
The format of each tuple is (station_name, (latitude, longitude)).
Returns:
A list of strings, each describing the distance between a pair of adjacent stations.
Each string is formatted as "Distance between [Station1] and [Station2]: [distance] km".
"""
distances = []
for i in range(len(stations) - 1):
name1, coords1 = stations[i]
name2, coords2 = stations[i + 1]
distance = geodesic(coords1, coords2).kilometers # Calculating distance using geodesic method
distances.append(f"Distance between {name1} and {name2}: {distance:.2f} km")
return distances
# Example of how to use the class (this should be in the comments):
# calculator = calculate_distances()
# stations = [
# ('Alpha', (40.757707, -73.997332)),
# ('Beta', (40.817108, -73.958537)),
# # ... add other stations here
# ]
# distances = calculator(stations)

View File

@@ -0,0 +1,46 @@
from jarvis.action.base_action import BaseAction
import subprocess
import os
import sys
import tempfile
class execute_original_python_code(BaseAction):
def __init__(self):
self._description = "Execute the Python code read from a file and get the original output."
def __call__(self, python_code, working_dir=None, *args, **kwargs):
"""
Execute the provided Python code and print the output.
Args:
python_code (str): The Python code to be executed.
working_dir (str, optional): The working directory where the code should be executed. Defaults to the current working directory.
Returns:
The result of the Code execution.
"""
# Set the working directory if provided, otherwise use the current working directory
if working_dir:
os.chdir(working_dir)
else:
working_dir = os.getcwd()
# Create a temporary file to store the Python code
with tempfile.NamedTemporaryFile(mode='w+', suffix='.py', dir=working_dir, delete=False) as temp_file:
temp_file_name = temp_file.name
temp_file.write(python_code)
temp_file.flush()
# Execute the Python code using the Python interpreter
try:
result = subprocess.run([sys.executable, temp_file_name], capture_output=True, text=True, check=True)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
print(f"An error occurred while executing the Python code: {e.stderr}", file=sys.stderr)
finally:
# Remove the temporary file
os.unlink(temp_file_name)
# Example of how to use the class (this should be in the comments):
# executor = execute_original_python_code()
# executor(python_code=read_python_code_return_val[0], working_dir='/home/heroding/桌面/Jarvis/working_dir')

View File

@@ -0,0 +1,33 @@
from jarvis.action.base_action import BaseAction
import os
class read_text_file(BaseAction):
def __init__(self):
self._description = "Read the full text content of a specified text file."
def __call__(self, file_path, *args, **kwargs):
"""
Read the content of the specified text file and return its content.
Args:
file_path (str): The absolute path to the text file to be read.
Returns:
str: The content of the text file, or None if an error occurs.
"""
try:
with open(file_path, 'r', encoding='utf-8') as file:
content = file.read()
print(f"Task execution complete. Content of the file {file_path} read successfully.")
return content
except FileNotFoundError:
print(f"The file {file_path} does not exist.")
return None
except Exception as e:
print(f"An error occurred while reading the file {file_path}: {e}")
return None
# Example of how to use the class (this should be in the comments):
# reader = read_text_file()
# content = reader(file_path='/home/heroding/.cache/huggingface/datasets/downloads/90d142b33359cd5fba1aa1ac9be83cd48d112baf51a675fc08e26d5b1d5c0402.txt')

View File

@@ -0,0 +1,45 @@
from jarvis.action.base_action import BaseAction
import os
import xml.etree.ElementTree as ET
class read_xml_file(BaseAction):
def __init__(self):
self._description = "Read the full text content of the specified XML file."
def __call__(self, file_path, *args, **kwargs):
"""
Read the content of the specified XML file and return its content.
Args:
file_path (str): The absolute path to the XML file to be read.
Returns:
str: The content of the XML file, or None if an error occurs.
"""
try:
# Change the current working directory to the directory of the file
os.chdir(os.path.dirname(file_path))
# Parse the XML file
tree = ET.parse(os.path.basename(file_path))
root = tree.getroot()
# Convert the XML tree to a string
content = ET.tostring(root, encoding='unicode')
print(f"Task execution complete. Content of the XML file {file_path} read successfully.")
return content
except FileNotFoundError:
print(f"The XML file {file_path} does not exist.")
return None
except ET.ParseError as e:
print(f"An error occurred while parsing the XML file {file_path}: {e}")
return None
except Exception as e:
print(f"An error occurred while reading the XML file {file_path}: {e}")
return None
# Example of how to use the class (this should be in the comments):
# reader = read_xml_file()
# content = reader(file_path='/home/heroding/.cache/huggingface/datasets/downloads/4b570797236b2208d14d90be2da93e5c6ce24b1e73d43d9632136e43effa2ad1.xml')

View File

@@ -36,11 +36,12 @@ prompt = {
17. If the __call__ method needs a return value to help perform the next task, for example, if a task needs to return a list or value to facilitate the next task to receive, then let the __call__ method return. Otherwise, there is no need to return
18. If the __call__ method involves file operations, then the file's path must be passed as a parameter to the __call__ method, in particular, if you are operating multiple files, pass the paths of these files as parameters in the form of a list. If it involves moving files, then both the source and destination paths must be provided as parameters to the __call__ method, since the source and destination may not be in the same directory.
19. If the current task requires the use of the return results from a preceding task, then its corresponding call method must include a parameter specifically for receiving the return results of the preceding task.
20. Please note that I have provided you with some codes similar to the current task in the Relevant Code of the user information. If the current task can be directly implemented with a certain code, then use this code directly.
20. Please note that I have provided you with some codes similar to the current task in the Relevant Code of the user information. If the current task can be directly implemented with a certain code, then use this code directly without modifying code.
21. If the code involves the output of file paths, ensure that the output includes the files' absolute path.
22. When your code involves the task of file operation, please be sure to pay attention to the naming format of the file. If it is a jpg file called XXX, the name should be XXX.jpg. If it is an mp4 file called XXX, the name should be XXX.mp4. Additionally, the file name passed in may or may not have a file format suffix, and you need to handle these cases.
23. Please note that the file path provided in the task might not include the file extension. This does not necessarily mean that the path is for a folder. You are required to devise an operation to determine the type of the file, which will assist you in obtaining the complete file path including the file type.
24. Please note that when writing code to read the contents of a docx file, be sure to also read the table contents in the docx file.
25. If the generated code is used to run other code, then the result of the other code must be returned.
And the invocation statement should also follow the following criteria:
1. The __call__ method invocation must be syntactically correct as per Python standards.
2. Clearly identify any fake or placeholder parameters used in the invocation.
@@ -316,9 +317,9 @@ prompt = {
You are a helpful ai assistant that can answer the question with the help of the context provided by the user in a step by step manner. The full question may help you to solve the current question.
If you don't know how to answer the user's question, answer "I don't know." instead of making up an answer.
And you should also follow the following criteria:
1. Pay attention to task involving calculations. Please make sure not to make mistakes in calculations.
2. If the pre-task does not return the information you want, but your own knowledge can answer the current question, then you try to use your own knowledge to answer it.
3. If your current answer is incorrect but you have a potential solution, please implement your potential solution directly.
1. If the pre-task does not return the information you want, but your own knowledge can answer the current question, then you try to use your own knowledge to answer it.
2. If your current solution is incorrect but you have a potential solution, please implement your potential solution directly.
3. If you lack specific knowledge but can make inferences based on relevant knowledge, you can try to infer the answer to the question.
''',
'_USER_QA_PROMPT' : '''
Context: {context}
@@ -374,13 +375,14 @@ prompt = {
18. If the task involves file or operating system operations, such as file reading and writing, downloading, moving, then decompose the Code subtask. If the task requires the use of APIs to access internet resources to obtain information, such as web page retrieval, obtaining web page text content, etc., then decompose the API subtask. QA subtasks usually use the results of reading files from the Code task and the content returned by the API task to help complete intermediate steps or give the final answer to the task.
19. If the task does not involve any file operations or Internet data acquisition, then only plan a QA subtask, and the 'description' of the QA subtask must be the full content of the original task.
20. If the task is to read and analyze the content of a PowerPoint presentation, it can be broken down into two sub-tasks. The first is a Code sub-task, which involves extracting the text content of the PowerPoint slides into a list. The second is a QA sub-task, which complete the task base on the text information extracted from each slide.
21. If the attached file is a csv, xlsx or xls file, the task must first be decomposed into Code subtask, which involves extracting the full text content of the file. If it is necessary to obtain information from the Internet, then an API subtask should be executed. Otherwise, proceed with a QA subtask, which involves analyzing the file's content and completing the task based on this analysis.
22. Once the task involves obtaining knowledge such as books, articles, character information, etc., you need to plan API tasks to obtain this knowledge from the Internet.
23. When decomposing an API subtask which uses the Bing Search API or the Bing Load Page API, you need to proceed to plan a QA subtask for analyzing and summarizing the information returned by that API subtask. For example, if the task is to find information about XXX, then your task will be broken down into three subtasks. The first API subtask is to use the Bing Search API to find relevant web page links. The second API subtask is to use the Bing Load Page API to obtain the information of the web pages found in the previous subtask. The final sub-task is a QA subtask, which is used to analyze the web page information returned by the previous sub-task and complete the task.
24. When the task involves retrieving a certain detailed content, then after decomposing the API subtask using '/tools/bing/searchv2', you also need to decompose an API subtask using '/tools/bing/load_pagev2', using for more detailed content.
25. If the attached file is a png or jpg file, the task must first be decomposed a API subtask, which uses image caption API to analyze image and solve problem. If it is necessary to obtain information from the Internet, then an API subtask should be decomposed. Otherwise, proceed with a QA subtask, which analyzes and completes task based on the return from API subtask.
26. Please note that all available APIs are only in the API List. You should not make up APIs that are not in the API List.
27. If the attached file is a csv file, you must first decompose a Code subtask,, which involves extracting all information from the csv file, and the description of this subtask only needs to say "extract data from the csv file". Then proceed with a QA subtask, which involves analyzing the file's content and completing the task based on this analysis.
21. Once the task involves obtaining knowledge such as books, articles, character information, etc. you need to plan API tasks to obtain this knowledge from the Internet.
22. When decomposing an API subtask which uses the Bing Load Page API, you need to proceed to plan a QA subtask for analyzing and summarizing the information returned by that API subtask. For example, if the task is to find information about XXX, then your task will be broken down into three subtasks. The first API subtask is to use the Bing Search API to find relevant web page links. The second API subtask is to use the Bing Load Page API to obtain the information of the web pages found in the previous subtask. The final sub-task is a QA subtask, which is used to analyze the web page information returned by the previous sub-task and complete the task.
23. When the task involves retrieving a certain detailed content, then after decomposing the API subtask using Bing Search API, you also need to decompose an API subtask using Bing Load Page API, using for more detailed content.
24. If the attached file is a png or jpg file, the task must first be decomposed a API subtask, which uses image caption API to analyze image and solve problem. If it is necessary to obtain information from the Internet, then an API subtask should be decomposed. Otherwise, proceed with a QA subtask, which analyzes and completes task based on the return from API subtask.
25. Please note that all available APIs are only in the API List. You should not make up APIs that are not in the API List.
26. If the attached file is a mp3 file, you can only break out two subtasks! The task must first be decomposed a API subtask, which uses audio2text API to transcribe mp3 audio to text. Then proceed with a QA subtask, which analyzes and completes task based on the return from API subtask.
35. Since the analyse or the content of the file are in the return value of the first subtask, if the following subtask requires the content or the analyse, the first subtask needs to be added to the dependencies of that subtask.
36. If the task has a path to the file, then the subtask that reads the file must write the full path of the file in the task description.
''',
'_USER_TASK_DECOMPOSE_PROMPT' : '''
User's information are as follows:

View File

@@ -221,7 +221,7 @@ if __name__ == '__main__':
# print(res[0])
# 删除
# actionManager.delete_action("implement_newtons_method")
# actionManager.delete_action("execute_original_python_code")
# actionManager.delete_action("zip_files")
# print(actionManager.action_code('zip_files'))
@@ -231,9 +231,9 @@ if __name__ == '__main__':
# code = file.read()
# info = {
# "task_name" : "implement_newtons_method",
# "task_name" : "execute_original_python_code",
# "code" : code,
# "description" : "Implement Newton's Method to find a root of the function f(x)."
# "description" : "Execute the Python code read from a file and get the original output."
# }
# actionManager.add_new_action(info)

View File

@@ -40,43 +40,6 @@
}
}
}
},
"/tools/arxiv": {
"get": {
"summary": "tool to get Arxiv Article Information",
"description": "Run Arxiv search and get the article meta information.",
"operationId": "get_arxiv_article_information_tools_arxiv_get",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ArxivQuery"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "Successful Response",
"content": {
"application/json": {
"schema": {}
}
}
},
"422": {
"description": "Validation Error",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/HTTPValidationError"
}
}
}
}
}
}
},
"/tools/bing/searchv2": {
"get": {

View File

@@ -4,16 +4,21 @@ from jarvis.core.tool_request_util import ToolRequestUtil
tool_request_util = ToolRequestUtil()
# Define the API path
api_path = '/tools/bing/searchv2'
api_path = '/tools/bing/load_pagev2'
# Define the method to be used for the API request
method = 'get'
# Define the parameters for the API request
# The query is constructed to include information about koi fish, the watershed id, and the year
# Based on the context provided, the URL for the Lego 4855 instruction manual is obtained from the previous search
url = "https://www.lego.com/en-us/service/buildinginstructions"
# Define the query for the API request
query = ''
# Define the params for the API request
params = {
"query": "koi fish 02040203",
"top_k": None # Assuming we want the default number of results
'url': url,
'query': query
}
# Define the content type for the API request
@@ -22,5 +27,5 @@ content_type = 'application/json'
# Make the API request and store the response
response = tool_request_util.request(api_path, method, params=params, content_type=content_type)
# Print the response from the API
# Print the return value of the API
print(response)

View File

@@ -12,10 +12,10 @@ api_path = '/tools/image_caption'
method = 'post'
# Define the query parameter to specify the task of extracting butterfat content information
query_params = {'query': 'As a comma separated list with no whitespace, using the provided image provide all the fractions that use / as the fraction line and the answers to the sample problems. Order the list by the order in which the fractions appear.'}
query_params = {'query': 'The opponent of the player who has the grid in the attached image file calls out the first move made in Game 10 of the World Chess Championship title match won by Bobby Fischer, using algebraic notation. What is the name of the game piece into which the player will have to put a red peg as a result, according to the 1990 Milton Bradley rules for the game? Answer without articles.'}
# Define the file to be uploaded
file_path = '/home/heroding/.cache/huggingface/datasets/downloads/2105d7660150b62c9b52b778082c3ba8bd69ecc463e61343dbf0f6e79c96294a.png'
file_path = '/home/heroding/.cache/huggingface/datasets/downloads/ed21e60f7812244ba022e33c79b47baeeb30c332753afa4a0d0b01fdca48763b.png'
files = {'image_file': open(file_path, 'rb')}
# Make the API call using the ToolRequestUtil

View File

@@ -3,19 +3,27 @@ from jarvis.core.tool_request_util import ToolRequestUtil
# Initialize the ToolRequestUtil
tool_request_util = ToolRequestUtil()
# Extract the URL for the lyrics page from the context
lyrics_page_url = "https://www.fao.org/3/ca8753en/ca8753en.pdf" # URL from the first search result
# Set up the parameters for the API call
# Define the API path
api_path = '/tools/bing/load_pagev2'
# Define the method for the API call
method = 'get'
# Extract the URL from the previous task's context
bls_page_url = "https://www.bls.gov/news.release/archives/empsit_07022009.pdf"
# Define the query for the API call
query = ''
# Define the params for the API call
params = {
"url": lyrics_page_url,
"query": ""
'url': bls_page_url,
'query': query
}
# Call the API
response = tool_request_util.request(api_path, method, params=params, content_type='application/json')
# Define the content type
content_type = 'application/json'
# Print the return value of the API
# Make the API call and print the return value
response = tool_request_util.request(api_path, method, params=params, content_type=content_type)
print(response)

View File

@@ -1,46 +1,46 @@
from jarvis.action.base_action import BaseAction
from sympy import symbols, diff, Rational
import subprocess
import os
import sys
import tempfile
class implement_newtons_method(BaseAction):
class execute_original_python_code(BaseAction):
def __init__(self):
self._description = "Implement Newton's Method to find a root of the function f(x)."
self._description = "Execute the Python code read from a file and get the original output."
def __call__(self, f_expression, x0, denominator_digits, max_iter=100, *args, **kwargs):
def __call__(self, python_code, working_dir=None, *args, **kwargs):
"""
Approximate the roots of the function using Newton's Method starting from x_0.
Iterate until the denominator of the fraction, when fully reduced, has a specified number of digits.
Execute the provided Python code and print the output.
Args:
f_expression (string): The function expression for which the root is to be found.
x0 (float or sympy expression): The initial guess for the root.
denominator_digits (int): The number of digits in the denominator to check for.
max_iter (int, optional): Maximum number of iterations. Defaults to 100.
python_code (str): The Python code to be executed.
working_dir (str, optional): The working directory where the code should be executed. Defaults to the current working directory.
Returns:
tuple: A tuple containing the smallest n where the denominator of the approximation has 25 digits and the corresponding approximation.
Returns (None, None) if no such n is found within max_iter.
"""
# Create a symbol x dynamically
x = symbols('x')
The result of the Code execution.
"""
# Set the working directory if provided, otherwise use the current working directory
if working_dir:
os.chdir(working_dir)
else:
working_dir = os.getcwd()
# Convert the string expression to a sympy expression
f = eval(f_expression)
# Create a temporary file to store the Python code
with tempfile.NamedTemporaryFile(mode='w+', suffix='.py', dir=working_dir, delete=False) as temp_file:
temp_file_name = temp_file.name
temp_file.write(python_code)
temp_file.flush()
# First derivative of the function
f_prime = diff(f, x)
for n in range(max_iter):
# Calculate the next approximation
x1 = x0 - f.subs(x, x0)/f_prime.subs(x, x0)
# Check if the denominator has the specified number of digits when the fraction is fully reduced
if len(str(Rational(x1).q)) >= denominator_digits:
return n + 1, x1 # n + 1 because we start counting from 1
x0 = x1
return None, None
# Execute the Python code using the Python interpreter
try:
result = subprocess.run([sys.executable, temp_file_name], capture_output=True, text=True, check=True)
return result.stdout.strip()
except subprocess.CalledProcessError as e:
print(f"An error occurred while executing the Python code: {e.stderr}", file=sys.stderr)
finally:
# Remove the temporary file
os.unlink(temp_file_name)
# Example of how to use the class (this should be in the comments):
# newtons_method = implement_newtons_method()
# n, approximation = newtons_method(f_expression="x**3 - 5*x**2 + 2*x", x0=1, denominator_digits=25, max_iter=100)
# executor = execute_original_python_code()
# executor(python_code=read_python_code_return_val[0], working_dir='/home/heroding/桌面/Jarvis/working_dir')