[Python] Error: '>=' not supported between instances of 'int' and 'str' when searching for...

Discussão em 'Python' iniciado por Stack, Fevereiro 19, 2025.

  1. Stack

    Stack Membro Participativo

    I'm working on a Python script that uses LangChain and OpenAI to search for machine learning jobs based on my CV. However, I'm encountering the following error:

    Error searching for jobs: '>=' not supported between instances of 'int' and 'str'


    code:

    from langchain_openai import ChatOpenAI
    from browser_use import Agent
    import asyncio
    from dotenv import load_dotenv
    import json
    import PyPDF2

    # Load environment variables (e.g., OpenAI API key)
    load_dotenv()

    # Function to read a PDF CV
    def read_pdf_cv(file_path):
    try:
    with open(file_path, "rb") as file:
    reader = PyPDF2.PdfReader(file)
    text = ""
    for page in reader.pages:
    page_text = page.extract_text()
    if page_text: # Check if text extraction was successful
    text += page_text
    return text
    except Exception as e:
    print(f"Error reading PDF: {e}")
    return ""

    async def main():
    # Step 1: Read the CV
    cv_path = "my_cv.pdf" # Replace with your CV file path
    cv_content = read_pdf_cv(cv_path)

    if not cv_content:
    print("No content extracted from CV. Exiting.")
    return

    print("CV Content Extracted:", cv_content)

    # Initialize the Agent
    agent = Agent(
    task=f"Read my CV and extract relevant information for ML job applications. CV content: {cv_content}",
    llm=ChatOpenAI(model="gpt-4"),
    )

    # Step 2: Search for ML jobs
    try:
    ml_jobs = await agent.run("Search for machine learning jobs based on the CV information.")
    print("Raw ML Jobs Data:", ml_jobs)

    # Ensure all job entries are dictionaries with consistent fields
    if isinstance(ml_jobs, list):
    for job in ml_jobs:
    if isinstance(job, dict):
    # Normalize 'salary' field
    if 'salary' in job:
    try:
    job['salary'] = int(job['salary']) # Convert salary to int
    except (ValueError, TypeError):
    print(f"Invalid salary value for job: {job['salary']}. Setting to 0.")
    job['salary'] = 0
    else:
    print(f"Warning: Job entry is not a dictionary: {job}")
    else:
    print(f"Error: Expected 'ml_jobs' to be a list, but got {type(ml_jobs)}")
    return

    except Exception as e:
    print(f"Error searching for jobs: {e}")
    return

    # Step 3: Save the ML jobs to a file
    try:
    with open("ml_jobs.json", "w") as file:
    json.dump(ml_jobs, file, indent=4)
    print("ML jobs saved to 'ml_jobs.json'.")
    except Exception as e:
    print(f"Error saving jobs to JSON: {e}")

    # Step 4: Start applying for the jobs in new tabs
    for job in ml_jobs:
    try:
    apply_result = await agent.run(f"Apply for the ML job: {job}. If you need help, ask me.")
    print(f"Application Result for {job}:", apply_result)
    except Exception as e:
    print(f"Error applying for job {job}: {e}")

    # Run the main function
    if __name__ == "__main__":
    asyncio.run(main())


    Error Details:

    The error occurs in the Step 2: Search for ML jobs section. Specifically, the error message indicates that a comparison (>=) is being attempted between an integer and a string. However, I'm not explicitly using the >= operator in my code, so I suspect it might be happening internally within the Agent or ChatOpenAI logic.

    Debugging Attempts:

    I added debugging statements to inspect the structure and types of ml_jobs. It appears that ml_jobs is a list of dictionaries, and I ensured that numeric fields like salary are converted to integers.

    I also checked if ml_jobs is a list and if each job entry is a dictionary. If not, I added warnings to log the issue.

    Environment: Python 3.x

    Libraries: langchain-openai, browser-use, python-dotenv, PyPDF2

    OpenAI model: gpt-4

    Question:

    Why is the >= operator being used internally, and how can I resolve this type mismatch?

    full error:

    Traceback (most recent call last):
    File "C:\Users\LENOVO\anaconda3\Lib\site-packages\browser_use\agent\service.py", line 468, in run
    for step in range(max_steps):
    ^^^^^^^^^^^^^^^^
    TypeError: 'str' object cannot be interpreted
    as an integer

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
    File "C:\browser-use\app.py", line 78, in <module>
    asyncio.run(main())
    File "C:\Users\LENOVO\anaconda3\Lib\asyncio\runners.py", line 194, in run
    return runner.run(main)
    ^^^^^^^^^^^^^^^^
    File "C:\Users\LENOVO\anaconda3\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\LENOVO\anaconda3\Lib\asyncio\base_events.py", line 687, in run_until_complete
    return future.result()
    ^^^^^^^^^^^^^^^
    File "C:\browser-use\app.py", line 44, in main
    ml_jobs = await agent.run("Search for machine learning jobs based on the CV information.")
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\LENOVO\anaconda3\Lib\site-packages\lmnr\openllmetry_sdk\decorators\base.py", line 107, in wrap
    return await fn(*args, **kwargs)
    ^^^^^^^^^^^^^^^^^^^^^^^^^
    File "C:\Users\LENOVO\anaconda3\Lib\site-packages\browser_use\agent\service.py", line 497, in run
    max_steps_reached=self.n_steps >= max_steps,
    ^^^^^^^^^^^^^^^^^^^^^^^^^
    TypeError: '>=' not supported between instances of 'int' and 'str'

    Continue reading...

Compartilhe esta Página