qwenlm--qwen-agent
64 行
2.0 KiB
Python
64 行
2.0 KiB
Python
# Copyright 2023 The Qwen team, Alibaba Group. All rights reserved.
|
|
#
|
|
# Licensed under the Apache License, Version 2.0 (the "License");
|
|
# you may not use this file except in compliance with the License.
|
|
# You may obtain a copy of the License at
|
|
#
|
|
# http://www.apache.org/licenses/LICENSE-2.0
|
|
#
|
|
# Unless required by applicable law or agreed to in writing, software
|
|
# distributed under the License is distributed on an "AS IS" BASIS,
|
|
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
# See the License for the specific language governing permissions and
|
|
# limitations under the License.
|
|
|
|
import json5
|
|
|
|
from qwen_agent.log import logger
|
|
from qwen_agent.utils.utils import extract_code, extract_urls, print_traceback
|
|
|
|
FN_NAME = 'Action'
|
|
FN_ARGS = 'Action Input'
|
|
FN_RESULT = 'Observation'
|
|
FN_EXIT = 'Response'
|
|
|
|
|
|
def extract_obs(text):
|
|
k = text.rfind('\nObservation:')
|
|
j = text.rfind('\nThought:')
|
|
obs = text[k + len('\nObservation:'):j]
|
|
return obs.strip()
|
|
|
|
|
|
def format_answer(text):
|
|
if 'code_interpreter' in text:
|
|
rsp = ''
|
|
code = extract_code(text)
|
|
rsp += ('\n```py\n' + code + '\n```\n')
|
|
obs = extract_obs(text)
|
|
if '![fig' in obs:
|
|
rsp += obs
|
|
return rsp
|
|
elif 'image_gen' in text:
|
|
# get url of FA
|
|
# img_urls = URLExtract().find_urls(text.split("Final Answer:")[-1].strip())
|
|
obs = text.split(f'{FN_RESULT}:')[-1].split(f'{FN_EXIT}:')[0].strip()
|
|
img_urls = []
|
|
if obs:
|
|
logger.info(repr(obs))
|
|
try:
|
|
obs = json5.loads(obs)
|
|
img_urls.append(obs['image_url'])
|
|
except Exception:
|
|
print_traceback()
|
|
img_urls = []
|
|
if not img_urls:
|
|
img_urls = extract_urls(text.split(f'{FN_EXIT}:')[-1].strip())
|
|
logger.info(img_urls)
|
|
rsp = ''
|
|
for x in img_urls:
|
|
rsp += '\n + ')'
|
|
return rsp
|
|
else:
|
|
return text.split(f'{FN_EXIT}:')[-1].strip()
|