Spaces:
Sleeping
Sleeping
import os | |
import gradio as gr | |
from crewai import Agent, Task, Crew, Process | |
from huggingface_hub import login | |
from langchain_community.llms import HuggingFaceEndpoint | |
from pydantic import BaseModel # Using Pydantic v2 | |
from typing import Dict, Any | |
# Set all required environment variables explicitly | |
os.environ["AZURE_API_TYPE"] = "azure" | |
os.environ["AZURE_API_BASE"] = os.getenv("AZURE_OPENAI_ENDPOINT") | |
os.environ["AZURE_API_KEY"] = os.getenv("AZURE_OPENAI_API_KEY") | |
os.environ["AZURE_API_VERSION"] = os.getenv("OPENAI_API_VERSION") | |
os.environ["AZURE_DEPLOYMENT_NAME"] = os.getenv("AZURE_DEPLOYMENT_NAME") | |
AZURE_API_BASE = os.getenv("AZURE_OPENAI_ENDPOINT") | |
AZURE_API_KEY = os.getenv("AZURE_OPENAI_API_KEY") | |
AZURE_API_VERSION = os.getenv("OPENAI_API_VERSION") | |
AZURE_DEPLOYMENT_NAME = os.getenv("AZURE_DEPLOYMENT_NAME") | |
if not AZURE_API_KEY or not AZURE_API_BASE or not AZURE_API_VERSION or not AZURE_DEPLOYMENT_NAME: | |
raise ValueError("Missing Azure OpenAI environment variables. Check your Hugging Face Space settings.") | |
# Configuring AzureChatOpenAI client... | |
from langchain_openai import AzureChatOpenAI | |
llm = AzureChatOpenAI( | |
azure_deployment=os.getenv("AZURE_DEPLOYMENT_NAME"), | |
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"), | |
api_key=os.getenv("AZURE_OPENAI_API_KEY"), | |
api_version=os.getenv("OPENAI_API_VERSION") , | |
model=f"azure/{os.getenv('AZURE_DEPLOYMENT_NAME')}", | |
max_retries=3, | |
timeout=30, | |
# max_tokens=2000 # max possible.. | |
temperature=0.3, # Adjust based on requirements | |
) | |
# ================= AGENTS ================= | |
proposal_writer = Agent( | |
role="Humanitarian Proposal Writer", | |
llm=llm, | |
goal="Write compelling funding proposals for humanitarian projects", | |
backstory="You are an expert in humanitarian aid and grant writing.", | |
verbose=True, | |
allow_delegation=False | |
) | |
proposal_reviewer = Agent( | |
role="Proposal Quality Assurance Specialist", | |
llm=llm, | |
goal="Ensure proposals meet funding criteria and formatting requirements", | |
backstory="You are a grant evaluator for major humanitarian organizations.", | |
verbose=True, | |
allow_delegation=False | |
) | |
# ================= TASKS ================= | |
def create_proposal_task(idea: str, budget: str, duration: str, scope: str): | |
return Task( | |
description=( | |
f"Write a detailed project proposal. Project: {idea}, Budget: {budget}, Duration: {duration}, Scope: {scope}" | |
), | |
expected_output="A well-structured proposal document.", | |
agent=proposal_writer, | |
output_file="proposal_draft.md" | |
) | |
def review_task(): | |
return Task( | |
description="Review the proposal for formatting, compliance, and logical flow.", | |
expected_output="Reviewed proposal with feedback.", | |
agent=proposal_reviewer, | |
output_file="proposal_review.md" | |
) | |
# ================= CREW ================= | |
def generate_proposal(description: str, org: str, duration: str, budget: str, region: str): | |
inputs = { | |
"idea": description, | |
"budget": budget, | |
"duration": duration, | |
"scope": f"Target region: {region}, Funding organization: {org}" | |
} | |
crew = Crew( | |
agents=[proposal_writer, proposal_reviewer], | |
tasks=[create_proposal_task(**inputs), review_task()], | |
process=Process.sequential, | |
verbose=2, | |
memory=True | |
) | |
return crew.kickoff() | |
# ================= GRADIO INTERFACE ================= | |
with gr.Blocks() as demo: | |
gr.Markdown("# π Humanitarian Proposal Generator") | |
description = gr.Textbox(label="Project Description", placeholder="Describe your project...") | |
org = gr.Dropdown(["UN", "EU", "USAID", "IOM"], label="Funding Organization") | |
duration = gr.Dropdown(["6 months", "1 year", "2 years"], label="Project Duration") | |
budget = gr.Dropdown(["$50,000 - $100,000", "$100,000 - $150,000", "$200,000 - $300,000"], label="Budget Range") | |
region = gr.Textbox(label="Target Region", placeholder="Enter project region (e.g., Africa, Asia)") | |
generate_button = gr.Button("Generate", visible=True) | |
output = gr.Markdown() | |
debug_output = gr.Textbox(label="Debug Console", interactive=False) | |
def process_proposal(desc, org, duration, budget, region): | |
debug_logs = "π Debug Log:\n" | |
try: | |
if not desc: | |
raise ValueError("β οΈ Error: Project description cannot be empty.") | |
debug_logs += f"β Inputs: {desc[:50]}..., {org}, {duration}, {budget}, {region}\n" | |
result = generate_proposal(desc, org, duration, budget, region) | |
debug_logs += "β Proposal successfully generated!\n" | |
return result, debug_logs | |
except Exception as e: | |
debug_logs += f"β Error: {str(e)}\n" | |
return f"<div style='color:red;'>β {str(e)}</div>", debug_logs | |
generate_button.click( | |
process_proposal, | |
inputs=[description, org, duration, budget, region], | |
outputs=[output, debug_output] | |
) | |
if __name__ == "__main__": | |
print("π Starting Gradio app...") | |
demo.launch(server_name="0.0.0.0", share=False, debug=True, show_error=True) | |