Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PraisonAI NameError: name 'l' is not defined #147

Open
DMTarmey opened this issue Aug 24, 2024 · 2 comments
Open

PraisonAI NameError: name 'l' is not defined #147

DMTarmey opened this issue Aug 24, 2024 · 2 comments

Comments

@DMTarmey
Copy link

(venv) (base) @DMTarmey ➜ /workspaces/PraisonAI (main) $ python -m praisonai ui
/workspaces/PraisonAI/venv/lib/python3.12/site-packages/pydantic/_internal/_config.py:341: UserWarning: Valid config keys have changed in V2:

  • 'allow_population_by_field_name' has been renamed to 'populate_by_name'
  • 'smart_union' has been removed
    warnings.warn(message, UserWarning)
    Traceback (most recent call last):
    File "", line 189, in _run_module_as_main
    File "", line 148, in _get_module_details
    File "", line 112, in _get_module_details
    File "/workspaces/PraisonAI/praisonai/init.py", line 7, in
    from .cli import PraisonAI
    File "/workspaces/PraisonAI/praisonai/cli.py", line 10, in
    from .auto import AutoGenerator
    File "/workspaces/PraisonAI/praisonai/auto.py", line 10, in
    l
    NameError: name 'l' is not defined
    (venv) (base) @DMTarmey ➜ /workspaces/PraisonAI (main) $

This issue seem to be realted to libraries as after very long time i fixed it and then was told to re load rewuirment.txt which i had updated but the system broke again, i have treid everythink i can using serch in vs code and asked chatgpt i tried everythink any thought would be great thakyou Daz

@DMTarmey
Copy link
Author

my auto.py code

from openai import BaseModel, OpenAI
from typing import Dict, List, Optional
import instructor
import os
import json
import yaml
from rich import print
import logging

logging.basicConfig(level=os.environ.get('LOGLEVEL', 'INFO').upper(), format='%(asctime)s - %(levelname)s - %(message)s')

class TaskDetails(BaseModel):
description: str
expected_output: str

class RoleDetails(BaseModel):
role: str
goal: str
backstory: str
tasks: Dict[str, TaskDetails]
tools: List[str]

class TeamStructure(BaseModel):
roles: Dict[str, RoleDetails]

class AutoGenerator:
def init(self, topic="Movie Story writing about AI", agent_file="test.yaml", framework="crewai", config_list: Optional[List[Dict]] = None):
self.config_list = config_list or [
{
'model': os.environ.get("OPENAI_MODEL_NAME", "gpt-4"),
'base_url': os.environ.get("OPENAI_API_BASE", "https://api.openai.com/v1"),
'api_key': os.environ.get("OPENAI_API_KEY")
}
]
self.topic = topic

    if os.path.isdir(agent_file):
        raise IsADirectoryError(f"Expected a file, but got a directory: '{agent_file}'")

    if not os.path.isfile(agent_file):
        raise FileNotFoundError(f"Agent file '{agent_file}' does not exist or is not a file.")

    self.agent_file = agent_file
    self.framework = framework or "crewai"
    self.client = instructor.patch(
        OpenAI(
            base_url=self.config_list[0]['base_url'],
            api_key=self.config_list[0]['api_key'],
        ),
        mode=instructor.Mode.JSON,
    )

def generate(self):
    response = self.client.Completion.create(
        model=self.config_list[0]['model'],
        prompt=self.get_user_content(),
        max_tokens=1000
    )
    json_data = json.loads(response.choices[0].text)
    self.convert_and_save(json_data)
    full_path = os.path.abspath(self.agent_file)
    return full_path

def convert_and_save(self, json_data):
    yaml_data = {
        "framework": self.framework,
        "topic": self.topic,
        "roles": {},
        "dependencies": []
    }

    for role_id, role_details in json_data['roles'].items():
        yaml_data['roles'][role_id] = {
            "backstory": role_details['backstory'],
            "goal": role_details['goal'],
            "role": role_details['role'],
            "tasks": {},
            "tools": role_details.get('tools', [])
        }

        for task_id, task_details in role_details['tasks'].items():
            yaml_data['roles'][role_id]['tasks'][task_id] = {
                "description": task_details['description'],
                "expected_output": task_details['expected_output']
            }

    with open(self.agent_file, 'w') as f:
        yaml.dump(yaml_data, f, allow_unicode=True, sort_keys=False)

def get_user_content(self):
    user_content = """Generate a team structure for  \"""" + self.topic + """\" task. 

No Input data will be provided to the team.
The team will work in sequence. First role will pass the output to the next role, and so on.
The last role will generate the final output.
Think step by step.
With maximum 3 roles, each with 1 task. Include role goals, backstories, task descriptions, and expected outputs.
List of Available Tools: CodeDocsSearchTool, CSVSearchTool, DirectorySearchTool, DOCXSearchTool, DirectoryReadTool, FileReadTool, TXTSearchTool, JSONSearchTool, MDXSearchTool, PDFSearchTool, RagTool, ScrapeElementFromWebsiteTool, ScrapeWebsiteTool, WebsiteSearchTool, XMLSearchTool, YoutubeChannelSearchTool, YoutubeVideoSearchTool.
Only use Available Tools. Do Not use any other tools.
Example Below:
Use below example to understand the structure of the output.
The final role you create should satisfy the provided task: """ + self.topic + """.
{
"roles": {
"narrative_designer": {
"role": "Narrative Designer",
"goal": "Create AI storylines",
"backstory": "Skilled in narrative development for AI, with a focus on story resonance.",
"tools": ["ScrapeWebsiteTool"],
"tasks": {
"story_concept_development": {
"description": "Craft a unique AI story concept with depth and engagement using concept from this page the content https://www.asthebirdfliesblog.com/posts/how-to-write-book-story-development .",
"expected_output": "Document with narrative arcs, character bios, and settings."
}
}
},
"scriptwriter": {
"role": "Scriptwriter",
"goal": "Write scripts from AI concepts",
"backstory": "Expert in dialogue and script structure, translating concepts into scripts.",
"tasks": {
"scriptwriting_task": {
"description": "Turn narrative concepts into scripts, including dialogue and scenes.",
"expected_output": "Production-ready script with dialogue and scene details."
}
}
}
}
}
"""
return user_content

@DMTarmey
Copy link
Author

this is line 10 as it keep flagging up

logging.basicConfig(level=os.environ.get('LOGLEVEL', 'INFO').upper(), format='%(asctime)s - %(levelname)s - %(message)s')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant