这是indexloc提供的服务,不要输入任何密码
Skip to content

Gbnn #24

@ManuelJimenezzr

Description

@ManuelJimenezzr

Description of the bug:

import Foundation
import SwiftUI
import GoogleGenerativeAI

enum ChatRole {
case user
case model
}

struct ChatMessage: Identifiable, Equatable {
let id = UUID().uuidString
var role: ChatRole
var message: String
}

class ChatService: ObservableObject {
@published private var chat: Chat?
@published private(set) var messages = ChatMessage
@published private(set) var loadingResponse = false

func sendMessage(_ message: String) {
    loadingResponse = true
    if (chat == nil) {
 let history: [ModelContent] = messages.map { ModelContent(role: $0.role == .user ? "user" : "model", parts: $0.message)}
        chat = GenerativeModel(name: "gemini-2.0-flash-lite-preview-02-05", apiKey: APIKey.default, systemInstruction: "You are a financial AI assistant. You are called Assist, and is supposed to do nothing other than answer questions.").startChat(history: history)

}

// MARK: Add user's message to the list
messages.append(.init(role: .user, message: message))

Task {
do {
let response = try await chat?.sendMessage(message)

     loadingResponse = false
     
     guard let text = response?.text else {
         messages.append(.init(role: .model, message: "Something went wrong, please try again."))
         return
     }
     
     messages.append(.init(role: .model, message: text))
 }
 catch {
     loadingResponse = false
     messages.append(.init(role: .model, message: "Something went wrong, please try again."))
 }

}
}
}

Actual vs expected behavior:

No response

Any other information you'd like to share?

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions