Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
allwefantasy committed Nov 18, 2024
1 parent 2e77f6f commit cdeece2
Show file tree
Hide file tree
Showing 6 changed files with 142 additions and 89 deletions.
Binary file modified output.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
21 changes: 15 additions & 6 deletions src/autocoder/agent/designer.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,23 +23,27 @@ def __init__(self, args: AutoCoderArgs, llm: byzerllm.ByzerLLM):
self.args = args

@byzerllm.prompt()
def extract_logo_info(self, query: str) -> LogoDesign:
def extract_logo_info(self, query: str) -> str:
"""
根据用户的需求,抽取相关信息,生成一个LogoDesign对象。
根据用户的需求,抽取相关信息,生成一个LogoDesign对象。生成的信息必须使用英文,对于没有提及的信息,请
根据你对用户需求的理解,给出合理的默认值。
用户需求:
我想创建一个闪亮前卫的科技公司logo,我的公司名叫做"ByteWave",喜欢深蓝色和白色的搭配。我们是一家专注于人工智能的公司。
LogoDesign对象示例:
```json
{
"selectedStyle": "Tech",
"companyName": "ByteWave",
"selectedBackgroundColor": "white",
"selectedPrimaryColor": "dark blue",
"additionalInfo": "AI technology focused company"
}
```
现在请根据如下用户需求生成一个LogoDesign对象:
现在请根据如下用户需求生成一个LogoDesign Json对象:
{{ query }}
"""
Expand Down Expand Up @@ -143,12 +147,17 @@ def enhance_query(self, query: str) -> str:
"""

def run(self, query: str):
logo_design = self.extract_logo_info.with_llm(self.llm).with_return_type(LogoDesign).run(query)

enhanced_query_str = (
self.enhance_logo_generate.with_llm(self.llm)
.with_extractor(lambda x: code_utils.extract_code(x)[0][1])
.run(query)
)
print(enhanced_query_str)
.run(selectedStyle = logo_design.selectedStyle,
companyName = logo_design.companyName,
selectedBackgroundColor = logo_design.selectedBackgroundColor,
selectedPrimaryColor = logo_design.selectedPrimaryColor,
additionalInfo = logo_design.additionalInfo)
)
response = self.sd_model_llm.chat_oai(
conversations=[
{
Expand Down
144 changes: 87 additions & 57 deletions src/autocoder/auto_coder.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,8 @@ def load_include_files(config, base_path, max_depth=10, current_depth=0):
with open(abs_include_path, "r") as f:
include_config = yaml.safe_load(f)
if not include_config:
logger.info(f"Include file {abs_include_path} is empty,skipping.")
logger.info(
f"Include file {abs_include_path} is empty,skipping.")
continue
config.update(
{
Expand Down Expand Up @@ -99,7 +100,7 @@ def main(input_args: Optional[List[str]] = None):
config = load_include_files(config, args.file)
for key, value in config.items():
if key != "file": # 排除 --file 参数本身
## key: ENV {{VARIABLE_NAME}}
# key: ENV {{VARIABLE_NAME}}
if isinstance(value, str) and value.startswith("ENV"):
template = Template(value.removeprefix("ENV").strip())
value = template.render(os.environ)
Expand Down Expand Up @@ -154,14 +155,16 @@ def main(input_args: Optional[List[str]] = None):
)
return
os.makedirs(os.path.join(args.source_dir, "actions"), exist_ok=True)
os.makedirs(os.path.join(args.source_dir, ".auto-coder"), exist_ok=True)
os.makedirs(os.path.join(args.source_dir,
".auto-coder"), exist_ok=True)

from autocoder.common.command_templates import create_actions

source_dir = os.path.abspath(args.source_dir)
create_actions(
source_dir=source_dir,
params={"project_type": args.project_type, "source_dir": source_dir},
params={"project_type": args.project_type,
"source_dir": source_dir},
)
git_utils.init(os.path.abspath(args.source_dir))

Expand Down Expand Up @@ -204,28 +207,33 @@ def main(input_args: Optional[List[str]] = None):

if raw_args.from_yaml:
# If --from_yaml is specified, copy content from the matching YAML file
from_files = [f for f in action_files if f.startswith(raw_args.from_yaml)]
from_files = [
f for f in action_files if f.startswith(raw_args.from_yaml)]
if from_files:
from_file = from_files[0] # Take the first match
with open(os.path.join(actions_dir, from_file), "r") as f:
content = f.read()
new_file = os.path.join(actions_dir, f"{new_seq}_{raw_args.name}.yml")
new_file = os.path.join(
actions_dir, f"{new_seq}_{raw_args.name}.yml")
with open(new_file, "w") as f:
f.write(content)
else:
print(f"No YAML file found matching prefix: {raw_args.from_yaml}")
print(
f"No YAML file found matching prefix: {raw_args.from_yaml}")
return
else:
# If --from_yaml is not specified, use the previous logic
if not prev_files:
new_file = os.path.join(actions_dir, f"{new_seq}_{raw_args.name}.yml")
new_file = os.path.join(
actions_dir, f"{new_seq}_{raw_args.name}.yml")
with open(new_file, "w") as f:
pass
else:
prev_file = sorted(prev_files)[-1] # 取序号最大的文件
with open(os.path.join(actions_dir, prev_file), "r") as f:
content = f.read()
new_file = os.path.join(actions_dir, f"{new_seq}_{raw_args.name}.yml")
new_file = os.path.join(
actions_dir, f"{new_seq}_{raw_args.name}.yml")
with open(new_file, "w") as f:
f.write(content)

Expand Down Expand Up @@ -311,7 +319,8 @@ def intercept_callback(
logger.warning(get_message("clipboard_not_supported"))
console.print(
Panel(
get_message("human_as_model_instructions_no_clipboard"),
get_message(
"human_as_model_instructions_no_clipboard"),
title="Instructions",
border_style="blue",
expand=False,
Expand Down Expand Up @@ -343,7 +352,8 @@ def intercept_callback(

lines = []
while True:
line = prompt(FormattedText([("#00FF00", "> ")]), multiline=False)
line = prompt(FormattedText(
[("#00FF00", "> ")]), multiline=False)
line_lower = line.strip().lower()
if line_lower in ["eof", "/eof"]:
break
Expand All @@ -352,7 +362,8 @@ def intercept_callback(
print("\033[2J\033[H") # Clear terminal screen
continue
elif line_lower in ["/break"]:
raise Exception("User requested to break the operation.")
raise Exception(
"User requested to break the operation.")
lines.append(line)

result = "\n".join(lines)
Expand All @@ -369,7 +380,8 @@ def intercept_callback(
]
return False, v

llm.add_event_callback(EventName.BEFORE_CALL_MODEL, intercept_callback)
llm.add_event_callback(
EventName.BEFORE_CALL_MODEL, intercept_callback)
code_model = llm.get_sub_client("code_model")
if code_model:
code_model.add_event_callback(
Expand Down Expand Up @@ -537,7 +549,8 @@ def intercept_callback(
import tempfile

transcribe_audio = TranscribeAudio()
temp_wav_file = os.path.join(tempfile.gettempdir(), "voice_input.wav")
temp_wav_file = os.path.join(
tempfile.gettempdir(), "voice_input.wav")

console = Console()

Expand Down Expand Up @@ -644,7 +657,7 @@ def intercept_callback(
return

elif raw_args.agent_command == "designer":
from autocoder.agent.designer import SVGDesigner, SDDesigner,LogoDesigner
from autocoder.agent.designer import SVGDesigner, SDDesigner, LogoDesigner

if args.agent_designer_mode == "svg":
designer = SVGDesigner(args, llm)
Expand All @@ -662,7 +675,8 @@ def intercept_callback(
request_queue.add_request(
args.request_id,
RequestValue(
value=DefaultValue(value="Successfully generated image"),
value=DefaultValue(
value="Successfully generated image"),
status=RequestOption.COMPLETED,
),
)
Expand Down Expand Up @@ -716,7 +730,8 @@ def intercept_callback(
"content": f"下面是一些文档和源码,如果用户的问题和他们相关,请参考他们:\n{file_content}",
},
)
pre_conversations.append({"role": "assistant", "content": "read"})
pre_conversations.append(
{"role": "assistant", "content": "read"})
source_count += 1

from autocoder.index.index import IndexManager, build_index_and_filter_files
Expand All @@ -732,18 +747,21 @@ def intercept_callback(
pp = SuffixProject(args=args, llm=llm, file_filter=None)
pp.run()
sources = pp.sources
s = build_index_and_filter_files(llm=llm, args=args, sources=sources)
s = build_index_and_filter_files(
llm=llm, args=args, sources=sources)
if s:
pre_conversations.append(
{
"role": "user",
"content": f"下面是一些文档和源码,如果用户的问题和他们相关,请参考他们:\n{s}",
}
)
pre_conversations.append({"role": "assistant", "content": "read"})
pre_conversations.append(
{"role": "assistant", "content": "read"})
source_count += 1

loaded_conversations = pre_conversations + chat_history["ask_conversation"]
loaded_conversations = pre_conversations + \
chat_history["ask_conversation"]

if args.human_as_model:
console = Console()
Expand All @@ -764,20 +782,20 @@ def chat_with_human_as_model(
{% endfor %}
{% endif %}
参考上面的文件以及对话,回答用户的问题。
用户的问题: {{ last_conversation.content }}
"""

source_codes_conversations = loaded_conversations[0 : source_count * 2]
source_codes_conversations = loaded_conversations[0: source_count * 2]
source_codes = ""
for conv in source_codes_conversations:
if conv["role"] == "user":
source_codes += conv["content"]

chat_content = chat_with_human_as_model.prompt(
source_codes=source_codes,
pre_conversations=loaded_conversations[source_count * 2 : -1],
pre_conversations=loaded_conversations[source_count * 2: -1],
last_conversation=loaded_conversations[-1],
)
try:
Expand All @@ -796,20 +814,22 @@ def chat_with_human_as_model(
logger.warning(get_message("clipboard_not_supported"))
console.print(
Panel(
get_message("human_as_model_instructions_no_clipboard"),
get_message(
"human_as_model_instructions_no_clipboard"),
title="Instructions",
border_style="blue",
expand=False,
)
)
return
return
# Save chat content to file
with open(args.target_file, "w") as f:
f.write(chat_content)

lines = []
while True:
line = prompt(FormattedText([("#00FF00", "> ")]), multiline=False)
line = prompt(FormattedText(
[("#00FF00", "> ")]), multiline=False)
line_lower = line.strip().lower()
if line_lower in ["eof", "/eof"]:
break
Expand All @@ -818,7 +838,8 @@ def chat_with_human_as_model(
print("\033[2J\033[H") # Clear terminal screen
continue
elif line_lower in ["/break"]:
raise Exception("User requested to break the operation.")
raise Exception(
"User requested to break the operation.")
lines.append(line)

result = "\n".join(lines)
Expand All @@ -830,7 +851,7 @@ def chat_with_human_as_model(

with open(memory_file, "w") as f:
json.dump(chat_history, f, ensure_ascii=False)

request_queue.add_request(
args.request_id,
RequestValue(
Expand All @@ -842,7 +863,8 @@ def chat_with_human_as_model(

if args.enable_rag_search or args.enable_rag_context:
rag = RAGFactory.get_rag(llm=chat_llm, args=args, path="")
response = rag.stream_chat_oai(conversations=loaded_conversations)[0]
response = rag.stream_chat_oai(
conversations=loaded_conversations)[0]
v = ([item, None] for item in response)
else:
v = chat_llm.stream_chat_oai(
Expand All @@ -852,35 +874,43 @@ def chat_with_human_as_model(
assistant_response = ""
markdown_content = ""

with Live(
Panel("", title="Response"),
refresh_per_second=4,
) as live:
for res in v:
markdown_content += res[0]
assistant_response += res[0]
request_queue.add_request(
args.request_id,
RequestValue(
value=StreamValue(value=[res[0]]),
status=RequestOption.RUNNING,
),
)
live.update(
Panel(
Markdown(markdown_content),
title="Response",
border_style="green",
expand=False,
try:
with Live(
Panel("", title="Response"),
refresh_per_second=4,
) as live:
for res in v:
markdown_content += res[0]
assistant_response += res[0]
request_queue.add_request(
args.request_id,
RequestValue(
value=StreamValue(value=[res[0]]),
status=RequestOption.RUNNING,
),
)
)

request_queue.add_request(
args.request_id,
RequestValue(
value=StreamValue(value=[""]), status=RequestOption.COMPLETED
),
)
live.update(
Panel(
Markdown(markdown_content),
title="Response",
border_style="green",
expand=False,
)
)
except Exception as e:
request_queue.add_request(
args.request_id,
RequestValue(
value=StreamValue(value=[str(e)]), status=RequestOption.FAILED
),
)
finally:
request_queue.add_request(
args.request_id,
RequestValue(
value=StreamValue(value=[""]), status=RequestOption.COMPLETED
),
)

chat_history["ask_conversation"].append(
{"role": "assistant", "content": assistant_response}
Expand Down
4 changes: 2 additions & 2 deletions src/autocoder/common/command_templates.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,8 +174,8 @@ def base_base(source_dir:str,project_type:str)->str:
model_max_input_length: 100000
model_max_input_length: 120000
enable_multi_round_generate: false
index_filter_workers: 5
index_build_workers: 20
index_filter_workers: 100
index_build_workers: 100
index_filter_level: 1
execute: true
Expand Down
Loading

0 comments on commit cdeece2

Please sign in to comment.