Skip to content

Commit

Permalink
Fix client render
Browse files Browse the repository at this point in the history
  • Loading branch information
nik committed Feb 20, 2024
1 parent 0454d87 commit c0fbf8d
Show file tree
Hide file tree
Showing 5 changed files with 107 additions and 63 deletions.
2 changes: 1 addition & 1 deletion adala/environments/kafka.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ class FileStreamAsyncKafkaEnvironment(AsyncKafkaEnvironment):
input_file: str
output_file: str
error_file: str
pass_through_columns: List[str]
pass_through_columns: Optional[List[str]] = None

def _iter_csv_local(self, csv_file_path):
"""
Expand Down
13 changes: 10 additions & 3 deletions adala/server/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,10 @@ class JobStatusResponse(BaseModel):
Example: [10, 100] means 10% of the completeness.
"""
status: str
processed_total: List[int] = Annotated[List[int], AfterValidator(lambda x: len(x) == 2)]
# processed_total: List[int] = Annotated[List[int], AfterValidator(lambda x: len(x) == 2)]


@app.get('/get-status')
@app.post('/get-status')
def get_status(request: JobStatusRequest):
"""
Get the status of a job.
Expand All @@ -133,7 +133,14 @@ def get_status(request: JobStatusRequest):
JobStatusResponse: The response model for getting the status of a job.
"""
job = process_file.AsyncResult(request.job_id)
return Response[JobStatusResponse](data=JobStatusResponse(status=job.status))
try:
status = job.status
except Exception as e:
logger.error(f"Error getting job status: {e}")
status = 'FAILURE'
else:
logger.info(f"Job {request.job_id} status: {status}")
return Response[JobStatusResponse](data=JobStatusResponse(status=status))


class JobCancelRequest(BaseModel):
Expand Down
143 changes: 89 additions & 54 deletions adala/server/ui/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,66 +1,101 @@
// @ts-nocheck

import React, {useState, useEffect} from "react";
import React, { useState } from "react";
import "./App.css";
import { Adala } from "./adala";
import testData from "./testData";

type FormData = {
inputFile: string;
outputFile: string;
errorFile: string;
instructions: string;
labels: string[]; // Explicitly typing labels as an array of strings
model: string;
apiKey: string;
passThroughColumns: string[];
};

const App = () => {
const [input, setInput] = useState("");
const [status, setStatus] = useState("");
const [jobId, setJobId] = useState(""); // This should be set to the jobId returned from the submit call
const adala = new Adala("http://localhost:30001");
const [formData, setFormData] = useState<FormData>(testData);
const [status, setStatus] = useState("");
const [jobId, setJobId] = useState("");
const adala = new Adala("http://localhost:30001");

const handleSubmit = async () => {
try {
const response = await adala.submit({
inputFile: "input.txt",
outputFile: "output.txt",
errorFile: "error.txt",
instructions: input,
labels: ["positive", "negative"],
model: "gpt-3.5-turbo",
apiKey: "your-api-key"
});
setJobId(response.data.jobId);
checkStatusPeriodically();
} catch
(error) {
console.error("Error submitting data to server:", error);
}
};
const handleSubmit = async () => {
try {
const response = await adala.submit({
...formData,
labels: formData.labels,
});
setJobId(response.job_id);
checkStatusPeriodically(response.job_id);
} catch (error) {
console.error("Error submitting data to server:", error);
}
};

const checkStatusPeriodically = () => {
const intervalId = setInterval(async () => {
try {
const response = await adala.getStatus({jobId});
setStatus(response.data.status);
if (response.data.status === "Complete" || response.data.status === "Error") {
clearInterval(intervalId);
}
} catch (error) {
console.error("Error fetching status from server:", error);
const checkStatusPeriodically = (currentJobId: string) => {
const intervalId = setInterval(async () => {
try {
const response = await adala.getStatus({ jobId: currentJobId });
setStatus(response.status); // Adjust this according to your actual response structure
if (response.status === "SUCCESS" || response.status === "FAILURE") {
clearInterval(intervalId);
}
}, 5000); // Poll every 5 seconds
};
} catch (error) {
console.error("Error fetching status from server:", error);
clearInterval(intervalId);
}
}, 5000); // Poll every 5 seconds
};

const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => {
const { name, value } = event.target;
setFormData(prevState => ({
...prevState,
// for list based fields (labels, passThroughColumns), split the value by comma and trim each item
[name]: name === "labels" || name === "passThroughColumns" ? value.split(",").map(item => item.trim()) : value,
}));
};

return (
<div className="app-container">
<div className="left-panel">
<input
type="text"
value={input}
onChange={(e) => setInput(e.target.value)}
placeholder="Enter your input"
/>
<button onClick={handleSubmit}>Submit</button>
</div>
<div className="right-panel">
<textarea readOnly value={status} placeholder="Status will be displayed here"/>
</div>
return (
<div className="app-container">
<div className="left-panel">
{/* Text inputs for each field */}
{Object.entries(formData).map(([key, value]) => {
if ((key !== "labels") && (key !== "passThroughColumns"))
{
return (
<input
key={key}
type="text"
name={key}
value={value}
onChange={handleChange}
placeholder={key.charAt(0).toUpperCase() + key.slice(1).replace(/([A-Z])/g, ' $1').trim()} // Formatting key to human-readable form
/>
);
} else {
return (
<input
key={key}
type="text"
name={key}
value={Array.isArray(value) ? value.join(", ") : ""}
onChange={handleChange}
placeholder="Comma-separated list of items"
/>
);
}
})}
<button onClick={handleSubmit}>Submit</button>
</div>
<div className="right-panel">
{/*Display job id and status*/}
<p>Job ID: {jobId}</p>
<textarea readOnly value={status} placeholder="Status will be displayed here" />
</div>
);
}
;
</div>
);
};

export default App;
4 changes: 2 additions & 2 deletions adala/server/ui/src/_api/services/DefaultService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,13 +60,13 @@ export class DefaultService {
* @returns any Successful Response
* @throws ApiError
*/
public getStatusGetStatusGet({
public getStatusGetStatusPost({
requestBody,
}: {
requestBody: JobStatusRequest,
}): CancelablePromise<any> {
return this.httpRequest.request({
method: 'GET',
method: 'POST',
url: '/get-status',
body: requestBody,
mediaType: 'application/json',
Expand Down
8 changes: 5 additions & 3 deletions adala/server/ui/src/adala.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ interface AdalaSubmitInterface {
inputFile: string;
outputFile: string;
errorFile: string;
passThroughColumns: string[];
instructions: string;
labels: string[];
model: string;
Expand Down Expand Up @@ -35,13 +36,14 @@ export class Adala {
agent: {
environment: {
type: "FileStreamAsyncKafkaEnvironment",
kafka_bootstrap_servers: "kafka:9093",
// kafka_bootstrap_servers: "kafka:9093",
kafka_bootstrap_servers: "localhost:9093",
kafka_input_topic: "adala-input",
kafka_output_topic: "adala-output",
input_file: req.inputFile,
output_file: req.outputFile,
error_file: req.errorFile,
pass_through_columns: null
pass_through_columns: req.passThroughColumns
},
skills: [{
type: "ClassificationSkill",
Expand Down Expand Up @@ -78,7 +80,7 @@ export class Adala {
// Example method for getting the status
async getStatus(req: AdalaGetStatusInterface): Promise<any> {
try {
const response = await this.apiClientInstance.default.getStatusGetStatusGet({
const response = await this.apiClientInstance.default.getStatusGetStatusPost({
requestBody: {
job_id: req.jobId
}
Expand Down

0 comments on commit c0fbf8d

Please sign in to comment.